package com.grayben.riskExtractor.helpers;

import com.grayben.riskExtractor.htmlScorer.ScoredText;
import com.grayben.riskExtractor.htmlScorer.partScorers.Scorer;
import org.apache.commons.io.IOUtils;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;

import java.io.InputStream;
import java.util.Set;

/**
 * Created by beng on 20/04/2016.
 */
public final class ScoredTextReverseEngineerer {

    public static Node treeFrom(ScoredText scoredText, Set<Scorer<Element>> elementScorers){
        throw new UnsupportedOperationException("Not implemented");
    }

    public static String htmlFrom(Node tree){
        StringBuilder sb = new StringBuilder();
        tree.html(sb);
        return sb.toString();
    }

    public static String htmlFrom(ScoredText scoredText, Set<Scorer<Element>> elementScorers){
        Node tree = treeFrom(scoredText, elementScorers);
        return htmlFrom(tree);
    }

    public static InputStream inputStreamFrom(String html){
        return IOUtils.toInputStream(html);
    }

    public static InputStream inputStreamFrom(Node tree){
        String html = htmlFrom(tree);
        return inputStreamFrom(html);
    }

    public static InputStream inputSteamFrom(ScoredText scoredText, Set<Scorer<Element>> elementScorers){
        String html = htmlFrom(scoredText, elementScorers);
        return inputStreamFrom(html);
    }

}

package com.grayben.riskExtractor.helpers;

import com.grayben.riskExtractor.htmlScorer.ScoredText;
import com.grayben.riskExtractor.htmlScorer.partScorers.Scorer;
import org.apache.commons.io.IOUtils;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;

import java.io.InputStream;
import java.util.List;
import java.util.Set;

/**
 * Created by beng on 20/04/2016.
 */
public final class ScoredTextReverseEngineerer {

    public static String htmlFrom(Node tree){
        StringBuilder sb = new StringBuilder();
        tree.html(sb);
        return sb.toString();
    }

    public static String htmlFrom(ScoredText scoredText, Set<Scorer<Element>> elementScorers){
        List<String> textElementsSurroundedByAppropriateTags = null;
        String taggedTextSurroundedByFrame = null;
        return taggedTextSurroundedByFrame;
    }

    public static InputStream inputStreamFrom(String html){
        return IOUtils.toInputStream(html);
    }

    public static InputStream inputStreamFrom(Node tree){
        String html = htmlFrom(tree);
        return inputStreamFrom(html);
    }

    public static InputStream inputSteamFrom(ScoredText scoredText, Set<Scorer<Element>> elementScorers){
        String html = htmlFrom(scoredText, elementScorers);
        return inputStreamFrom(html);
    }

}

Remove a step in reversal; can go ScoredText -> html directly


package com.elmakers.mine.bukkit.magic.command;

import com.elmakers.mine.bukkit.api.magic.MagicAPI;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.util.ArrayList;
import java.util.Collection;

public class RPCommandExecutor extends MagicTabExecutor {

	public RPCommandExecutor(MagicAPI api) {
		super(api);
	}

	@Override
	public Collection<String> onTabComplete(CommandSender sender, String commandName, String[] args) {
		return new ArrayList<>();
	}

	@Override
	public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
		if (!api.hasPermission(sender, "Magic.commands.rp")) {
			sendNoPermission(sender);
			return true;
		}
		if (!(sender instanceof Player)) {
			sender.sendMessage(ChatColor.RED + "This command may only be used in-game");
			return true;
		}

		api.getController().sendResourcePack((Player)sender);
		return true;
	}
}

package com.elmakers.mine.bukkit.magic.command;

import com.elmakers.mine.bukkit.api.magic.MagicAPI;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.util.ArrayList;
import java.util.Collection;

public class RPCommandExecutor extends MagicTabExecutor {

	public RPCommandExecutor(MagicAPI api) {
		super(api);
	}

	@Override
	public Collection<String> onTabComplete(CommandSender sender, String commandName, String[] args) {
		return new ArrayList<>();
	}

	@Override
	public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
		if (!api.hasPermission(sender, "Magic.commands.getrp")) {
			sendNoPermission(sender);
			return true;
		}
		if (!(sender instanceof Player)) {
			sender.sendMessage(ChatColor.RED + "This command may only be used in-game");
			return true;
		}

		api.getController().sendResourcePack((Player)sender);
		return true;
	}
}

Fix permission check on /getrp command

Fix permission check on /getrp command


package com.amitness.photon;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class SplashScreen extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);

        Thread myThread = new Thread() {
            @Override
            public void run() {
                try{
                    sleep(4000);
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(intent);
                    finish();
                } catch(InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        myThread.start();
    }
}

package com.amitness.photon;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class SplashScreen extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);

        Thread myThread = new Thread() {
            @Override
            public void run() {
                try{
                    sleep(2000);
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(intent);
                    finish();
                } catch(InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        myThread.start();
    }
}

Reduce splash screen load time

Reduce splash screen load time


package io.spacedog.test;

import org.junit.Test;

import io.spacedog.client.SpaceDog;
import io.spacedog.client.http.SpaceRequest;

public class ServiceErrorFilterTest extends SpaceTest {

	@Test
	public void catchesFluentResourceErrors() {

		prepareTest();
		SpaceDog superadmin = clearServer();

		// should fail to access invalid route
		SpaceRequest.get("/1/toto")//
				.backend(superadmin.backend())//
				.go(404)//
				.assertEquals("path [/1/toto] invalid", "error.message");

		// should fail to use this method for this valid route
		superadmin.put("/1/login").go(405)//
				.assertEquals("method [PUT] invalid for path [/1/login]", "error.message");
	}

	@Test
	public void notifySuperdogsForInternalServerErrors() {

		// prepare
		prepareTest();

		// this fails and send notification to superdogs with error details
		SpaceRequest.post("/1/admin/_return_500").go(500);
	}
}

package io.spacedog.test;

import org.junit.Test;

import io.spacedog.client.SpaceDog;
import io.spacedog.client.http.SpaceRequest;

public class ServiceErrorFilterTest extends SpaceTest {

	@Test
	public void catchesFluentResourceErrors() {

		prepareTest();
		SpaceDog superadmin = clearServer();

		// should fail to access invalid route
		SpaceRequest.get("/1/toto")//
				.backend(superadmin.backend())//
				.go(404)//
				.assertEquals("[path][/1/toto] not found", "error.message");

		// should fail to use this method for this valid route
		superadmin.put("/1/login").go(405)//
				.assertEquals("[PUT][/1/login] is not supported", "error.message");
	}

	@Test
	public void notifySuperdogsForInternalServerErrors() {

		// prepare
		prepareTest();

		// this fails and send notification to superdogs with error details
		SpaceRequest.post("/1/admin/_return_500").go(500);
	}
}

Fix service error filter tests due to error message refactoring


/*
 * Copyright 2017 Open mHealth
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.openmhealth.shim.googlefit;

import org.openmhealth.shim.OAuth2ClientSettings;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @author Emerson Farrugia
 */
@Component
@ConfigurationProperties("openmhealth.shim.googlefit")
public class GoogleFitClientSettings extends OAuth2ClientSettings {

    private List<String> scopes = Arrays.asList(
            "https://www.googleapis.com/auth/fitness.activity.read",
            "https://www.googleapis.com/auth/fitness.body.read"
    );

    @Override
    public List<String> getScopes() {

        return scopes;
    }

    public void setScopes(List<String> scopes) {

        this.scopes = scopes;
    }
}

/*
 * Copyright 2017 Open mHealth
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.openmhealth.shim.googlefit;

import org.openmhealth.shim.OAuth2ClientSettings;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @author Emerson Farrugia
 */
@Component
@ConfigurationProperties("openmhealth.shim.googlefit")
public class GoogleFitClientSettings extends OAuth2ClientSettings {

    private List<String> scopes = Arrays.asList(
            "https://www.googleapis.com/auth/fitness.activity.read",
            "https://www.googleapis.com/auth/fitness.body.read",
            "https://www.googleapis.com/auth/fitness.location.read"
    );

    @Override
    public List<String> getScopes() {

        return scopes;
    }

    public void setScopes(List<String> scopes) {

        this.scopes = scopes;
    }
}

Add location scope to Google Fit

Add location scope to Google Fit


module test.base {
  requires com.greetings;
  requires org.astro;

  requires org.junit.jupiter;
}

module test.base {
  requires com.greetings;
  requires org.astro;
}

Remove 3rd-party module requires for the time being


package passel.w21789.com.passel;

import java.net.URL;

/**
 * Created by aneesh on 4/5/15.
 */
public class Constants {
    public static final String API_BASE_URL = "http://18.111.3.60:5000";
}

package passel.w21789.com.passel;

import java.net.URL;

/**
 * Created by aneesh on 4/5/15.
 */
public class Constants {
    public static final String API_BASE_URL = "http://18.189.28.225:5000";
}

Update URL to current IP.

Update URL to current IP.


package com.forter.contracts.validation;

import com.google.common.base.Preconditions;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.List;

/**
 * Checks against one of the specified values
 */
public class OneOfValidator  implements ConstraintValidator<OneOf, Object>{

    private List<String> values;

    @Override
    public void initialize(OneOf constraintAnnotation) {
        values = Arrays.asList(constraintAnnotation.value());
        Preconditions.checkArgument(values.size() > 0, "Empty list input found in @OneOf annotation");
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        return value != null && values.contains(String.valueOf(value));
    }
}

package com.forter.contracts.validation;

import com.google.common.base.Preconditions;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.List;

/**
 * Checks against one of the specified values.
 * Returns isValid true if the value is null. Use @NotNull to explicitly reject null values.
 */
public class OneOfValidator  implements ConstraintValidator<OneOf, Object>{

    private List<String> values;

    @Override
    public void initialize(OneOf constraintAnnotation) {
        values = Arrays.asList(constraintAnnotation.value());
        Preconditions.checkArgument(values.size() > 0, "Empty list input found in @OneOf annotation");
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        return value == null || values.contains(String.valueOf(value));
    }
}

Fix @OneOf to approve null values

Fix @OneOf to approve null values


package org.jboss.da.bc.backend.impl;

import org.jboss.da.scm.SCMType;
import org.junit.Test;

public class RepositoryClonerImplTest {

    private RepositoryClonerImpl clonner = new RepositoryClonerImpl();

    @Test(expected = UnsupportedOperationException.class)
    public void testCloneNonGitRepository() throws Exception {
        clonner.cloneRepository("", "", SCMType.SVN, "");
    }

    @Test
    public void testCloneGitRepository() throws Exception {
        String url = clonner.cloneRepository("https://github.com/project-ncl/dependency-analysis",
                "master", SCMType.GIT, "TEST_DA3");
        System.out.println("\n\n" + url + "\n\n");
    }

}

package org.jboss.da.bc.backend.impl;

import org.jboss.da.scm.SCMType;
import org.junit.Test;

public class RepositoryClonerImplTest {

    private RepositoryClonerImpl clonner = new RepositoryClonerImpl();

    @Test(expected = UnsupportedOperationException.class)
    public void testCloneNonGitRepository() throws Exception {
        clonner.cloneRepository("", "", SCMType.SVN, "");
    }

}

Remove temporary test. We cannot clone repository in every test run


/*
 * Copyright (c) 2016-present, Jim Kynde Meyer
 * All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
package com.intellij.react.css.modules.psi;

import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReferenceBase;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Represents an invalid CSS class reference in a specific style sheet file.
 */
public class CssModulesUnknownClassPsiReference extends PsiReferenceBase<PsiElement> {

    public CssModulesUnknownClassPsiReference(@NotNull PsiElement element, TextRange rangeInElement) {
        super(element, rangeInElement);
    }

    @Nullable
    @Override
    public PsiElement resolve() {
        return null;
    }

    @NotNull
    @Override
    public Object[] getVariants() {
        return new Object[0];
    }

}

/*
 * Copyright (c) 2016-present, Jim Kynde Meyer
 * All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
package com.intellij.react.css.modules.psi;

import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReferenceBase;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Represents an invalid CSS class reference in a specific style sheet file.
 */
public class CssModulesUnknownClassPsiReference extends PsiReferenceBase<PsiElement> {

    public CssModulesUnknownClassPsiReference(@NotNull PsiElement element, TextRange rangeInElement) {
        super(element, rangeInElement);
    }

    @Nullable
    @Override
    public PsiElement resolve() {
        // self reference to prevent JS tooling from reporting unresolved symbol
        return this.getElement();
    }

    @NotNull
    @Override
    public Object[] getVariants() {
        return new Object[0];
    }

}

Use self reference to prevent JS tooling from reporting unresolved symbol


package io.github.vcuswimlab.stackintheflow.controller.component;

import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.Nullable;

import java.util.HashMap;
import java.util.Map;

/**
 *
PersistProfileComponent

 * Created on: 8/1/2017
 *
 * @author Tyler John Haden
 */

@State(
        name = "ProfileState", storages = {
        @Storage(
                id = "stack-overflow",
                file = "$PROJECT_CONFIG_DIR$/stackoverflow-profile.xml")
})
public class PersistProfileComponent implements PersistentStateComponent<PersistProfileComponent> {

    private Map<String, Integer> userStatMap;

    public Map<String, Integer> getUserStatMap() {
        return userStatMap;
    }

    @Override
    public void noStateLoaded() {
        userStatMap = new HashMap<>();
    }

    @Override
    public void loadState(PersistProfileComponent state) {
        XmlSerializerUtil.copyBean(state, this);
    }

    @Nullable
    @Override
    public PersistProfileComponent getState() {
        return this;
    }

}

package io.github.vcuswimlab.stackintheflow.controller.component;

import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.Nullable;

import java.util.HashMap;
import java.util.Map;

/**
 *
PersistProfileComponent

 * Created on: 8/1/2017
 *
 * @author Tyler John Haden
 */

@State(
        name = "ProfileState", storages = {
        @Storage("stackoverflow-profile.xml")
})
public class PersistProfileComponent implements PersistentStateComponent<PersistProfileComponent> {

    public Map<String, Integer> userStatMap;

    public Map<String, Integer> getUserStatMap() {
        return userStatMap;
    }

    @Override
    public void noStateLoaded() {
        userStatMap = new HashMap<>();
    }

    @Override
    public void loadState(PersistProfileComponent state) {
        XmlSerializerUtil.copyBean(state, this);
    }

    @Nullable
    @Override
    public PersistProfileComponent getState() {
        return this;
    }

}

Fix user profile not serializing.

Fix user profile not serializing.


package org.robolectric.shadows;

import android.app.QueuedWork;
import android.os.Build;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.Resetter;
import org.robolectric.util.ReflectionHelpers;

@Implements(value = QueuedWork.class, isInAndroidSdk = false)
public class ShadowQueuedWork {

  @Resetter
  public static void reset() {
    QueuedWork.waitToFinish();
    if (RuntimeEnvironment.getApiLevel() >= Build.VERSION_CODES.O) {
      ReflectionHelpers.setStaticField(QueuedWork.class, "sHandler", null);
    } else {
      ReflectionHelpers.setStaticField(QueuedWork.class, "sSingleThreadExecutor", null);
    }
  }
}

package org.robolectric.shadows;

import android.app.QueuedWork;
import android.os.Build;
import android.os.Handler;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.Resetter;
import org.robolectric.util.ReflectionHelpers;

import java.util.List;

@Implements(value = QueuedWork.class, isInAndroidSdk = false)
public class ShadowQueuedWork {

  @Resetter
  public static void reset() {
    if (RuntimeEnvironment.getApiLevel() >= Build.VERSION_CODES.O) {
      resetStateApi26();
    } else {
      QueuedWork.waitToFinish();
      ReflectionHelpers.setStaticField(QueuedWork.class, "sSingleThreadExecutor", null);
    }
  }

  private static void resetStateApi26() {
    Handler queuedWorkHandler = ReflectionHelpers.getStaticField(QueuedWork.class, "sHandler");
    if (queuedWorkHandler != null) {
      queuedWorkHandler.removeCallbacksAndMessages(null);
    }
    ((List) ReflectionHelpers.getStaticField(QueuedWork.class, "sFinishers")).clear();
    ((List) ReflectionHelpers.getStaticField(QueuedWork.class, "sWork")).clear();
    ReflectionHelpers.setStaticField(QueuedWork.class, "mNumWaits", 0);
  }
}

Update QueuedWork Resetter for API 26

Update QueuedWork Resetter for API 26

This is part of an effort to resolve deadlocks that may occur with
SharedPreferences on SDK 26.

In API 26, the implementation of QueuedWork changed from a
ThreadPoolExecutor to a Handler combined with two lists of Runnables. In
this API level, setting the `sHandler` static variable to null led to a
memory leak. Each test that called `QueuedWork.getHandler()` caused a
new Handler to be created and added to `ShadowLooper.loopingLoopers`.

Because the Handler and Runnable lists are being cleared, there's no
need to call `QueuedWork.waitToFinish()` in API 26.


package fr.insee.pogues.transforms;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Service
public class StromaeServiceImpl implements StromaeService {

    @Autowired
    Environment env;

    private String serviceUri;

    @PostConstruct
    public void setUp(){
        serviceUri = env.getProperty("fr.insee.pogues.api.remote.stromae.vis.url");
    }
    @Override
    public String transform(String input, Map<String, Object> params) throws Exception {
        try {
            String uri = String.format("%s/%s", serviceUri,
                    params.get("name"));
            HttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(uri);
            post.setEntity(new StringEntity(input, StandardCharsets.UTF_8));
            post.setHeader("Content-type", "application/xml");
            HttpResponse response = client.execute(post);
            return EntityUtils.toString(response.getEntity());
        } catch(Exception e) {
            throw e;
        }

    }
}

package fr.insee.pogues.transforms;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Service
public class StromaeServiceImpl implements StromaeService {

    @Autowired
    Environment env;

    private String serviceUri;

    @PostConstruct
    public void setUp(){
        serviceUri = env.getProperty("fr.insee.pogues.api.remote.stromae.vis.url");
    }

    @Override
    public String transform(String input, Map<String, Object> params) throws Exception {
        try {
            String uri = String.format("%s/%s", serviceUri,
                    params.get("name"));
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost post = new HttpPost(uri);
            post.setEntity(new StringEntity(input, StandardCharsets.UTF_8));
            post.setHeader("Content-type", "application/xml");
            HttpResponse response = httpClient.execute(post);
            return EntityUtils.toString(response.getEntity());
        } catch(Exception e) {
            throw e;
        }

    }
}

Rename client to httpClient for more clarity


/*
 * Mutability Detector
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 * Further licensing information for this project can be found in
 * 		license/LICENSE.txt
 */

package org.mutabilitydetector.cli;

import static org.junit.Assert.assertTrue;

import java.io.File;

import org.junit.After;
import org.junit.Test;

public class ClassListReaderFactoryTest {

	private File classListFile;

	@Test
	public void testDefaultReturnedReaderIsPlainTextClassListReader() throws Exception {
		classListFile = new File("somePlainTextFile.txt");
		classListFile.createNewFile();
		ClassListToReportCollector collector = new ClassListReaderFactory(classListFile).createReader();

		assertTrue("Should be a plain text reader.", collector instanceof PlainTextClassListToReportReader);
	}

	@After
	public void tearDown() {
		if (classListFile != null) classListFile.delete();
	}
}

/*
 * Mutability Detector
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 * Further licensing information for this project can be found in
 * 		license/LICENSE.txt
 */

package org.mutabilitydetector.cli;

import static org.junit.Assert.assertTrue;

import java.io.File;

import org.junit.After;
import org.junit.Test;

public class ClassListReaderFactoryTest {

	private File classListFile;

	@Test
	public void testDefaultReturnedReaderIsPlainTextClassListReader() throws Exception {
		classListFile = new File("somePlainTextFile.txt");
		assertTrue(classListFile.createNewFile());
		ClassListToReportCollector collector = new ClassListReaderFactory(classListFile).createReader();

		assertTrue("Should be a plain text reader.", collector instanceof PlainTextClassListToReportReader);
	}

	@After
	public void tearDown() {
		if (classListFile != null) {
			assertTrue(classListFile.delete());
		}
	}
}

Change how the test asserts a file has been deleted.

git-svn-id: ed609ce04ec9e3c0bc25e071e87814dd6d976548@63 c7a0535c-eda6-11de-83d8-6d5adf01d787


package com.kickstarter.libs.utils;

import junit.framework.TestCase;

public class StringUtilsTest extends TestCase {

  public void testIsEmail() {
    assertTrue(StringUtils.isEmail("hello@kickstarter.com"));
  }

  public void testIsEmpty() {
    assertTrue(StringUtils.isEmpty(""));
    assertTrue(StringUtils.isEmpty(" "));
    assertTrue(StringUtils.isEmpty("     "));
    assertTrue(StringUtils.isEmpty(null));
    assertFalse(StringUtils.isEmpty("a"));
    assertFalse(StringUtils.isEmpty(" a "));
  }

  public void testIsPresent() {
    assertFalse(StringUtils.isPresent(""));
    assertFalse(StringUtils.isPresent(" "));
    assertFalse(StringUtils.isPresent("     "));
    assertFalse(StringUtils.isPresent(null));
    assertTrue(StringUtils.isPresent("a"));
    assertTrue(StringUtils.isPresent(" a "));
  }
}

package com.kickstarter.libs.utils;

import com.kickstarter.KSRobolectricTestCase;

import org.junit.Test;

public class StringUtilsTest extends KSRobolectricTestCase {

  @Test
  public void testIsEmail() {
    assertTrue(StringUtils.isEmail("hello@kickstarter.com"));
    assertFalse(StringUtils.isEmail("hello@kickstarter"));
  }

  @Test
  public void testIsEmpty() {
    assertTrue(StringUtils.isEmpty(""));
    assertTrue(StringUtils.isEmpty(" "));
    assertTrue(StringUtils.isEmpty("     "));
    assertTrue(StringUtils.isEmpty(null));
    assertFalse(StringUtils.isEmpty("a"));
    assertFalse(StringUtils.isEmpty(" a "));
  }

  @Test
  public void testIsPresent() {
    assertFalse(StringUtils.isPresent(""));
    assertFalse(StringUtils.isPresent(" "));
    assertFalse(StringUtils.isPresent("     "));
    assertFalse(StringUtils.isPresent(null));
    assertTrue(StringUtils.isPresent("a"));
    assertTrue(StringUtils.isPresent(" a "));
  }
}

Make into roboelectric test so pattern is available.


/*
 * Copyright (c) 2016-2017 Contributors to the Eclipse Foundation
 *
 * See the NOTICE file(s) distributed with this work for additional
 * information regarding copyright ownership.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.eclipse.microprofile.config.tck.converters.implicit;

/**
 * Part of the implicit Converter test.
 *
 * Sample class which has a String param constructor
 *
 * @author Mark Struberg
 */
public class ConvTestTypeWStringCt {
    private final String val;

    ConvTestTypeWStringCt(String val) {
        this.val = val;
    }

    public String getVal() {
        return val;
    }
}

/*
 * Copyright (c) 2016-2018 Contributors to the Eclipse Foundation
 *
 * See the NOTICE file(s) distributed with this work for additional
 * information regarding copyright ownership.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.eclipse.microprofile.config.tck.converters.implicit;

/**
 * Part of the implicit Converter test.
 *
 * Sample class which has a String param constructor
 *
 * @author Mark Struberg
 */
public class ConvTestTypeWStringCt {
    private final String val;

    public ConvTestTypeWStringCt(String val) {
        this.val = val;
    }

    public String getVal() {
        return val;
    }
}

Make the string constructor public

Make the string constructor public

Signed-off-by: Tom Evans <bbb6cb1c35947eed47a195f3a89b506a71fc89e5@uk.ibm.com>


package org.duckdns.raven.ttscallresponder.tts;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;

public class StartAnsweringServiceReceiver extends BroadcastReceiver {
	private static final String TAG = "StartAnsweringServiceReceiver";

	@Override
	public void onReceive(Context context, Intent intent) {
		String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
		Log.i(TAG, "Phone state changed: " + state);

		if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
			Log.i(TAG, "Ringing - preparing service");
			Intent startResponderService = new Intent(context, TtsAnsweringService.class);
			context.startService(startResponderService);
			Log.i(TAG, "Service started");
		}

		if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
			Log.i(TAG, "InCall - answering");
		}
	}
}

package org.duckdns.raven.ttscallresponder.tts;

import org.duckdns.raven.ttscallresponder.domain.call.Call;
import org.duckdns.raven.ttscallresponder.domain.call.PersistentCallList;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;

public class StartAnsweringServiceReceiver extends BroadcastReceiver {
	private static final String TAG = "StartAnsweringServiceReceiver";

	@Override
	public void onReceive(Context context, Intent intent) {
		String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
		Log.i(TAG, "Phone state changed: " + state);

		if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
			Log.i(TAG, "Ringing - preparing service");
			Intent startResponderService = new Intent(context, TtsAnsweringService.class);
			context.startService(startResponderService);
			Log.i(TAG, "Service started");

			Log.i(TAG, "Adding to answered calls: " + intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
			PersistentCallList callList = new PersistentCallList(context.getFilesDir());
			callList.add(new Call(intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER)));
			callList.savePersistentList();
		}
	}
}

Add calls to list of answered calls.

[CallResponder] Add calls to list of answered calls.

Signed-off-by: Juri Berlanda <5bfdca9e82c53adb0603ce7083f4ba4f2da5cacf@hotmail.com>


package org.utplsql.cli;

import org.utplsql.api.JavaApiVersionInfo;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

/** This class is getting updated automatically by the build process.
 * Please do not update its constants manually cause they will be overwritten.
 *
 * @author pesse
 */
public class CliVersionInfo {

    private static final String MAVEN_PROJECT_NAME = "utPLSL-cli";
    private static String MAVEN_PROJECT_VERSION = "unknown";

    static {
        try {
            MAVEN_PROJECT_VERSION = Files.readAllLines(
                    Paths.get(CliVersionInfo.class.getClassLoader().getResource("utplsql-cli.version").toURI())
                    , Charset.defaultCharset())
                    .get(0);
        }
        catch ( IOException | URISyntaxException e ) {
            System.out.println("WARNING: Could not get Version information!");
        }
    }

    public static String getVersion() { return MAVEN_PROJECT_VERSION; }
    public static String getInfo() { return MAVEN_PROJECT_NAME + " " + getVersion(); }

}

package org.utplsql.cli;

import org.utplsql.api.JavaApiVersionInfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;

/** This class is getting updated automatically by the build process.
 * Please do not update its constants manually cause they will be overwritten.
 *
 * @author pesse
 */
public class CliVersionInfo {

    private static final String MAVEN_PROJECT_NAME = "utPLSL-cli";
    private static String MAVEN_PROJECT_VERSION = "unknown";

    static {
        try {
            try ( InputStream in = JavaApiVersionInfo.class.getClassLoader().getResourceAsStream("utplsql-cli.version")) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                MAVEN_PROJECT_VERSION = reader.readLine();

                reader.close();
            }
        }
        catch ( IOException e ) {
            System.out.println("WARNING: Could not get Version information!");
        }
    }

    public static String getVersion() { return MAVEN_PROJECT_VERSION; }
    public static String getInfo() { return MAVEN_PROJECT_NAME + " " + getVersion(); }

}

Read the info from stream instead of NIO


package com.uwetrottmann.trakt5.enums;

/**
 * By default, all methods will return minimal info for movies, shows, episodes, and users. Minimal info is typically
 * all you need to match locally cached items and includes the title, year, and ids. However, you can request different
 * extended levels of information.
 */
public enum Extended implements TraktEnum {

    /** Default. Returns enough info to match locally. */
    DEFAULT_MIN("min"),
    /** Minimal info and all images. */
    IMAGES("images"),
    /** Complete info for an item. */
    FULL("full"),
    /** Complete info and all images. */
    FULLIMAGES("full,images");

    private final String value;

    private Extended(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return value;
    }
}

package com.uwetrottmann.trakt5.enums;

/**
 * By default, all methods will return minimal info for movies, shows, episodes, and users. Minimal info is typically
 * all you need to match locally cached items and includes the title, year, and ids. However, you can request different
 * extended levels of information.
 */
public enum Extended implements TraktEnum {

    /** Default. Returns enough info to match locally. */
    DEFAULT_MIN("min"),
    /** Minimal info and all images. */
    IMAGES("images"),
    /** Complete info for an item. */
    FULL("full"),
    /** Complete info and all images. */
    FULLIMAGES("full,images"),
    /** Only works with sync watchedShows. */
    NOSEASONS("noseasons"),
    /** Only works with sync watchedShows. */
    NOSEASONSIMAGES("noseasons,images");

    private final String value;

    Extended(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return value;
    }
}

Add support for noseasons extended flag.

- Only works with sync watchedShows.


package org.jaudiotagger.issues;

import org.jaudiotagger.AbstractTestCase;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.tag.FieldKey;

import java.io.File;

/**
 *File corrupt after write
 */
public class Issue290Test extends AbstractTestCase
{
    public void testSavingFile()
    {
        File orig = new File("testdata", "test59.mp4");
        if (!orig.isFile())
        {
            System.err.println("Unable to test file - not available");
            return;
        }

        File testFile = null;
        Exception exceptionCaught = null;
        try
        {
            testFile = AbstractTestCase.copyAudioToTmp("test59.mp4");
            AudioFile af = AudioFileIO.read(testFile);
            System.out.println("Tag is"+af.getTag().toString());
            af.getTag().setField(af.getTag().createField(FieldKey.ARTIST,"fred"));
            af.commit();

            af = AudioFileIO.read(testFile);
            assertEquals("fred",af.getTag().getFirst(FieldKey.ARTIST));
        }
        catch (Exception e)
        {
            e.printStackTrace();
            exceptionCaught = e;
        }

        assertNull(exceptionCaught);
    }

}

package org.jaudiotagger.issues;

import org.jaudiotagger.AbstractTestCase;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.tag.FieldKey;

import java.io.File;

/**
 *File corrupt after write
 */
public class Issue290Test extends AbstractTestCase
{
    public void testSavingFile()
    {
        File orig = new File("testdata", "test59.mp4");
        if (!orig.isFile())
        {
            System.err.println("Unable to test file - not available");
            return;
        }

        /* Issue still needs fixing
        File testFile = null;
        Exception exceptionCaught = null;
        try
        {
            testFile = AbstractTestCase.copyAudioToTmp("test59.mp4");
            AudioFile af = AudioFileIO.read(testFile);
            System.out.println("Tag is"+af.getTag().toString());
            af.getTag().setField(af.getTag().createField(FieldKey.ARTIST,"fred"));
            af.commit();

            af = AudioFileIO.read(testFile);
            assertEquals("fred",af.getTag().getFirst(FieldKey.ARTIST));
        }
        catch (Exception e)
        {
            e.printStackTrace();
            exceptionCaught = e;
        }

        assertNull(exceptionCaught);
        */
    }

}

Comment out test that fails locally because issue not resolved yet because preventing mvn deploy

git-svn-id: 545e707062091c2f19509f4812c0e7d129870002@853 922cec90-98bc-ecba-b0a9-867c771b4a74


package org.robockets.buttonmanger;

public class ButtonThread implements Runnable {
	private long startTime = 0;

	public void run() {
		while (true) {
			setTimeout();
			ButtonManager.checkButtons();
			waitUntilTimedOut();
		}
	}

	private void setTimeout() {
		startTime = System.nanoTime();
	}

	private void waitUntilTimedOut() {
		while (System.nanoTime() == startTime + 1000000000) { // 1000000000ns should be 1s
			// Just wait
		}
	}
}

package org.robockets.buttonmanger;

public class ButtonThread implements Runnable {
	private long startTime = 0;

	public void run() {
		while (true) {
			setTimeout();
			ButtonManager.checkButtons();
			waitUntilTimedOut();
		}
	}

	private void setTimeout() {
		startTime = System.nanoTime();
	}

	private void waitUntilTimedOut() {
		while (System.nanoTime() >= startTime + 1000000000) { // 1000000000ns should be 1s
			// Just wait
		}
	}
}

Make sure wait function catches everything


package com.speedment.runtime.core.internal.db;

import com.speedment.common.logger.Level;
import com.speedment.common.logger.Logger;

import java.util.List;
import java.util.stream.Collectors;

public final class SqlQueryLoggerUtil {

    public SqlQueryLoggerUtil() {}

    public static void logOperation(Logger logger, final String sql, final List<?> values) {
        if (logger.getLevel().isEqualOrLowerThan(Level.DEBUG)) {
            final String text = sql + " " + values.stream()
                    .map(o -> o.getClass().getSimpleName() + " " + o.toString())
                    .collect(Collectors.joining(", ", "[", "]"));
            logger.debug(text);
        }
    }
}

package com.speedment.runtime.core.internal.db;

import com.speedment.common.logger.Level;
import com.speedment.common.logger.Logger;

import java.util.List;
import java.util.stream.Collectors;

public final class SqlQueryLoggerUtil {

    public SqlQueryLoggerUtil() {}

    public static void logOperation(Logger logger, final String sql, final List<?> values) {
        if (logger.getLevel().isEqualOrLowerThan(Level.DEBUG)) {
            final String text = sql + " " + values.stream()
                    .map(o -> o == null
                            ? "null"
                            : o.getClass().getSimpleName() + " " + o.toString())
                    .collect(Collectors.joining(", ", "[", "]"));
            logger.debug(text);
        }
    }
}

Handle null values in query logger

Handle null values in query logger


package org.ethereum.datasource;

/**
 * Created by Anton Nashatyrev on 06.12.2016.
 */
public abstract class AbstractChainedSource<Key, Value, SourceKey, SourceValue> implements Source<Key, Value> {

    protected Source<SourceKey, SourceValue> source;
    protected boolean flushSource;

    protected AbstractChainedSource() {
    }

    public AbstractChainedSource(Source<SourceKey, SourceValue> source) {
        this.source = source;
    }

    protected void setSource(Source<SourceKey, SourceValue> src) {
        source = src;
    }

    public Source<SourceKey, SourceValue> getSource() {
        return source;
    }

    public void setFlushSource(boolean flushSource) {
        this.flushSource = flushSource;
    }

    @Override
    public final synchronized boolean flush() {
        if (flushSource) {
            getSource().flush();
        }
        return flushImpl();
    }

    protected abstract boolean flushImpl();
}

package org.ethereum.datasource;

/**
 * Abstract Source implementation with underlying backing Source
 * The class has control whether the backing Source should be flushed
 * in 'cascade' manner
 *
 * Created by Anton Nashatyrev on 06.12.2016.
 */
public abstract class AbstractChainedSource<Key, Value, SourceKey, SourceValue> implements Source<Key, Value> {

    private Source<SourceKey, SourceValue> source;
    private boolean flushSource;

    /**
     * Intended for subclasses which wishes to initialize the source
     * later via {@link #setSource(Source)} method
     */
    protected AbstractChainedSource() {
    }

    public AbstractChainedSource(Source<SourceKey, SourceValue> source) {
        this.source = source;
    }

    /**
     * Intended for subclasses which wishes to initialize the source later
     */
    protected void setSource(Source<SourceKey, SourceValue> src) {
        source = src;
    }

    public Source<SourceKey, SourceValue> getSource() {
        return source;
    }

    public void setFlushSource(boolean flushSource) {
        this.flushSource = flushSource;
    }

    /**
     * Invokes {@link #flushImpl()} and does backing Source flush if required
     * @return true if this or source flush did any changes
     */
    @Override
    public final synchronized boolean flush() {
        boolean ret = flushImpl();
        if (flushSource) {
            ret |= getSource().flush();
        }
        return ret;
    }

    /**
     * Should be overridden to do actual source flush
     */
    protected abstract boolean flushImpl();
}

Fix flush implementation: first own flush() should be performed. Add docs


package com.example.android.groupschedulecoordinator;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;

public class ActivityCreateGroup extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_group);
    }

    public void createGroup(View v) {
        EditText text =  (EditText) findViewById(R.id.tbGroupName);
        String groupName = text.getText().toString();
        if(groupName.isEmpty())
        {
            android.content.Context context = getApplicationContext();
            CharSequence warning = "Please enter a valid group name.";
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, warning, duration);
            toast.show();
        }
        else
        {
            Intent intent = new Intent(ActivityCreateGroup.this, MainActivity.class);

            Bundle extras = getIntent().getExtras();
            ArrayList<String> group_list = extras.getStringArrayList("groupList");
            group_list.add(groupName);

            //intent.putExtra("groupName", groupName);
            intent.putStringArrayListExtra("groupList", group_list);

            startActivity(intent);
        }

    }
}

package com.example.android.groupschedulecoordinator;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;

public class ActivityCreateGroup extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_group);
    }

    public void createGroup(View v) {
        EditText text =  (EditText) findViewById(R.id.tbGroupName);
        String groupName = text.getText().toString();
        if(groupName.isEmpty())
        {
            android.content.Context context = getApplicationContext();
            CharSequence warning = "Please enter a valid group name.";
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, warning, duration);
            toast.show();
        }
        else
        {
            Intent intent = new Intent(ActivityCreateGroup.this, MainActivity.class);

            Bundle extras = getIntent().getExtras();
            ArrayList<String> group_list = extras.getStringArrayList("groupList");

            if(group_list == null)
            {
                group_list = new ArrayList<>();
            }
            group_list.add(groupName);

            //intent.putExtra("groupName", groupName);
            intent.putStringArrayListExtra("groupList", group_list);

            startActivity(intent);
        }

    }
}

Fix crash when adding new group names

Fix crash when adding new group names


package io.github.lionell.lab1;

import com.google.common.base.Joiner;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import io.github.lionell.lab1.io.WordReader;

/**
 * Usage example: $ bazel run //java/util/github/lionell/lab1 --
 * /home/lionell/dev/labs/volohov/res/in.txt
 * /home/lionell/dev/labs/volohov/res/out.txt
 *
 * @author lionell
 */
public class Runner {
  public static void main(String[] args) throws IOException {
    WordReader reader = new WordReader(args[0]);
    System.out.println(args[0]);

    List<String> words = new ArrayList<>();
    while (reader.hasNext()) {
      words.add(reader.next());
    }

    reader.close();

    // FrequencySorter.sort(words);
    // System.out.println(Joiner.on(", ").join(words));

    Set<Set<String>> sets = new CliquesFinder(words).findCliques();

    PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(args[1])));

    for (Set<String> set : sets) {
      writer.println("{" + Joiner.on(", ").join(set) + "}");
    }

    writer.close();
  }
}

package io.github.lionell.lab1;

import com.google.common.base.Joiner;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import io.github.lionell.lab1.io.WordReader;

/**
 * Usage example: $ bazel run //java/io/github/lionell/lab1 --
 * /home/lionell/dev/labs/volohov/res/in.txt
 * /home/lionell/dev/labs/volohov/res/out.txt
 *
 * @author lionell
 */
public class Runner {
  public static void main(String[] args) throws IOException {
    WordReader reader = new WordReader(args[0]);
    System.out.println(args[0]);

    List<String> words = new ArrayList<>();
    while (reader.hasNext()) {
      words.add(reader.next());
    }

    reader.close();

    // FrequencySorter.sort(words);
    // System.out.println(Joiner.on(", ").join(words));

    Set<Set<String>> sets = new CliquesFinder(words).findCliques();

    PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(args[1])));

    for (Set<String> set : sets) {
      writer.println("{" + Joiner.on(", ").join(set) + "}");
    }

    writer.close();
  }
}

Fix minor bug in docs

Fix minor bug in docs


package br.com.bloder.blormlib;

import android.content.Context;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import br.com.bloder.blormlib.validation.Validate;
import br.com.bloder.blormlib.validation.Validation;

/**
 * Created by bloder on 05/06/16.
 */
public class Blorm {

  public static class Builder {

    private List<Validate> validations;
    private View field;

    public Builder() {
      validations = new ArrayList<>();
    }

    public Builder field(View field) {
      this.field = field;
      return this;
    }

    public Builder is(Validate validation) {
      this.validations.add(validation);
      return this;
    }

    public Builder is(Validation validation) {
      validation.field = this.field;
      this.validations.add(validation.validate());
      return this;
    }

    public void onSubmit(View submittedItem) {
      new Blorm(this.validations).onSubmitted();
    }
  }

  private List<Validate> validations;

  public Blorm(List<Validate> validations) {
    this.validations = validations;
  }

  private void onSubmitted() {
    for(Validate validate : validations) {
      if(validate.validate()) {
      } else {
      }
    }
  }
}

package br.com.bloder.blormlib;

import android.view.View;

import java.util.ArrayList;
import java.util.List;

import br.com.bloder.blormlib.validation.Validate;
import br.com.bloder.blormlib.validation.Validation;

/**
 * Created by bloder on 05/06/16.
 */
public class Blorm {

  public static class Builder {

    private List<Validate> validations;
    private View field;

    public Builder() {
      validations = new ArrayList<>();
    }

    public Builder field(View field) {
      this.field = field;
      return this;
    }

    public Builder is(Validate validation) {
      this.validations.add(validation);
      return this;
    }

    public Builder is(Validation validation) {
      validation.field = this.field;
      this.validations.add(validation.validate());
      return this;
    }

    public Builder is(String errorMessgae, Validation validation) {
      validation.field = this.field;
      validation.errorMessage = errorMessgae;
      this.validations.add(validation.validate());
      return this;
    }

    public void onSubmit(View submittedItem) {
      new Blorm(this.validations).onSubmitted();
    }
  }

  private List<Validate> validations;

  public Blorm(List<Validate> validations) {
    this.validations = validations;
  }

  private void onSubmitted() {
    for(Validate validate : validations) {
      if(!validate.validate()) {
        validate.onError();
      }
    }
  }
}

Add is function with error message in blorm class


package com.github.seratch.jslack.api.methods.response.oauth;

import com.github.seratch.jslack.api.methods.SlackApiResponse;
import lombok.Data;

import java.util.List;

@Data
public class OAuthAccessResponse implements SlackApiResponse {

    private boolean ok;
    private String warning;
    private String error;
    private String needed;
    private String provided;

    private String tokenType;
    private String accessToken;
    private String scope;
    private String enterpriseId;
    private String teamName;
    private String teamId;
    private String userId;
    private IncomingWebhook incomingWebhook;
    private Bot bot;

    private AuthorizingUser authorizingUser;
    private InstallerUser installerUser;
    @Deprecated // for workspace apps
    private Scopes scopes;

    @Data
    public static class IncomingWebhook {
        private String url;
        private String channel;
        private String channelId;
        private String configurationUrl;
    }

    @Data
    public static class Bot {
        private String botUserId;
        private String botAccessToken;
    }

    @Data
    public static class AuthorizingUser {
        private String userId;
        private String appHome;
    }

    @Data
    public static class InstallerUser {
        private String userId;
        private String appHome;
    }

    @Data
    public static class Scopes {
        private List<String> appHome;
        private List<String> team;
        private List<String> channel;
        private List<String> group;
        private List<String> mpim;
        private List<String> im;
        private List<String> user;
    }

}

package com.github.seratch.jslack.api.methods.response.oauth;

import com.github.seratch.jslack.api.methods.SlackApiResponse;
import lombok.Data;

import java.util.List;

@Data
public class OAuthAccessResponse implements SlackApiResponse {

    private boolean ok;
    private String warning;
    private String error;
    private String needed;
    private String provided;

    private String tokenType;
    private String accessToken;
    private String scope;
    private String enterpriseId;
    private String teamName;
    private String teamId;
    private String userId;
    private IncomingWebhook incomingWebhook;
    private Bot bot;

    @Data
    public static class IncomingWebhook {
        private String url;
        private String channel;
        private String channelId;
        private String configurationUrl;
    }

    @Data
    public static class Bot {
        private String botUserId;
        private String botAccessToken;
    }

    @Deprecated // for workspace apps
    private AuthorizingUser authorizingUser;
    @Deprecated // for workspace apps
    private InstallerUser installerUser;
    @Deprecated // for workspace apps
    private Scopes scopes;

    @Deprecated
    @Data
    public static class AuthorizingUser {
        private String userId;
        private String appHome;
    }

    @Deprecated
    @Data
    public static class InstallerUser {
        private String userId;
        private String appHome;
    }

    @Deprecated
    @Data
    public static class Scopes {
        private List<String> appHome;
        private List<String> team;
        private List<String> channel;
        private List<String> group;
        private List<String> mpim;
        private List<String> im;
        private List<String> user;
    }

}

Mark workspace app related properties as deprecated


/*
 * Copyright (C) 2009 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.common.collect.testing;

import com.google.gwt.core.client.GwtScriptOnly;
import com.google.gwt.lang.Array;

/**
 * Version of {@link GwtPlatform} used in web-mode.  It includes methods in
 * {@link Platform} that requires different implementions in web mode and
 * hosted mode.  It is factored out from {@link Platform} because
 * {@literal @}GwtScriptOnly only supports public classes and methods.
 *
 * @author Hayward Chan
 */
@GwtScriptOnly
public final class GwtPlatform {

  private GwtPlatform() {}

  public static <T> T[] clone(T[] array) {
    return (T[]) Array.clone(array);
  }
}

/*
 * Copyright (C) 2009 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.common.collect.testing;

import com.google.gwt.core.client.GwtScriptOnly;

import java.util.Arrays;

/**
 * Version of {@link GwtPlatform} used in web-mode.  It includes methods in
 * {@link Platform} that requires different implementions in web mode and
 * hosted mode.  It is factored out from {@link Platform} because
 * {@literal @}GwtScriptOnly only supports public classes and methods.
 *
 * @author Hayward Chan
 */
@GwtScriptOnly
public final class GwtPlatform {

  private GwtPlatform() {}

  public static <T> T[] clone(T[] array) {
    return (T[]) Arrays.copyOfRange(array, 0, array.length);
  }
}

Fix guava test breakage due to GWT internal changes.

For some reason Guava tests call into GWT internal implementations.

I ported guava to use Arrays.copyRange instead of GWT's internal arrays methods. These
methods should never be called from any code outside of GWT's core module.
-------------
Created by MOE: http://code.google.com/p/moe-java
MOE_MIGRATED_REVID=98113442


package org.zalando.problem.spring.web.autoconfigure;

import org.apiguardian.api.API;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
import org.zalando.problem.spring.web.advice.AdviceTrait;

import static org.apiguardian.api.API.Status.INTERNAL;

@API(status = INTERNAL)
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication
@ConditionalOnClass(WebSecurityConfigurer.class)
public class ProblemAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(AdviceTrait.class)
    public AdviceTrait exceptionHandling() {
        return new ExceptionHandling();
    }

}

package org.zalando.problem.spring.web.autoconfigure;

import org.apiguardian.api.API;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zalando.problem.spring.web.advice.AdviceTrait;

import static org.apiguardian.api.API.Status.INTERNAL;

@API(status = INTERNAL)
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication
public class ProblemAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(AdviceTrait.class)
    public AdviceTrait exceptionHandling() {
        return new ExceptionHandling();
    }

}

Remove Spring Security class dependency

Remove Spring Security class dependency


package com.philliphsu.bottomsheetpickers.view.numberpad;

import com.philliphsu.bottomsheetpickers.view.LocaleModel;

public class NumberPadTimePickerDialogPresenterTest extends NumberPadTimePickerPresenterTest {

    @Override
    INumberPadTimePicker.DialogView getView(int mode) {
        return (INumberPadTimePicker.DialogView) super.getView(mode);
    }

    @Override
    INumberPadTimePicker.DialogPresenter getPresenter(int mode) {
        return (INumberPadTimePicker.DialogPresenter) super.getPresenter(mode);
    }

    @Override
    Class<? extends INumberPadTimePicker.DialogView> getViewClass() {
        return INumberPadTimePicker.DialogView.class;
    }

    @Override
    INumberPadTimePicker.DialogPresenter createPresenter(INumberPadTimePicker.View view,
                                                   LocaleModel localeModel,
                                                   boolean is24HourMode) {
        return new NumberPadTimePickerDialogPresenter((INumberPadTimePicker.DialogView) view,
                localeModel, is24HourMode);
    }
}

package com.philliphsu.bottomsheetpickers.view.numberpad;

import com.philliphsu.bottomsheetpickers.view.LocaleModel;

import static org.mockito.Mockito.verify;

public class NumberPadTimePickerDialogPresenterTest extends NumberPadTimePickerPresenterTest {

    @Override
    public void verifyViewEnabledStatesForEmptyState() {
        super.verifyViewEnabledStatesForEmptyState();
        verify(getView(MODE_12HR)).setOkButtonEnabled(false);
        verify(getView(MODE_24HR)).setOkButtonEnabled(false);
    }

    @Override
    INumberPadTimePicker.DialogView getView(int mode) {
        return (INumberPadTimePicker.DialogView) super.getView(mode);
    }

    @Override
    INumberPadTimePicker.DialogPresenter getPresenter(int mode) {
        return (INumberPadTimePicker.DialogPresenter) super.getPresenter(mode);
    }

    @Override
    Class<? extends INumberPadTimePicker.DialogView> getViewClass() {
        return INumberPadTimePicker.DialogView.class;
    }

    @Override
    INumberPadTimePicker.DialogPresenter createPresenter(INumberPadTimePicker.View view,
                                                   LocaleModel localeModel,
                                                   boolean is24HourMode) {
        return new NumberPadTimePickerDialogPresenter((INumberPadTimePicker.DialogView) view,
                localeModel, is24HourMode);
    }
}

Add check to verify the 'ok' button is set disabled for Dialogs on empty-state initialization.


package swimmingpool.service;

import org.chtijbug.drools.platform.runtime.servlet.DroolsPlatformKnowledgeBaseJavaEE;
import org.chtijbug.drools.runtime.DroolsChtijbugException;
import org.chtijbug.drools.runtime.RuleBaseSession;
import org.chtijbug.example.swimmingpool.Abonnement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jws.WebParam;
import javax.jws.WebService;

@WebService(endpointInterface = "swimmingpool.service.IServiceCalculate")
public class ServiceCalculate implements IServiceCalculate {
    private static Logger logger = LoggerFactory.getLogger(ServiceCalculate.class);

    private DroolsPlatformKnowledgeBaseJavaEE platformKnowledgeBaseJavaEE;

    public void setRuleBasePackage(DroolsPlatformKnowledgeBaseJavaEE ruleBasePackage) {
        this.platformKnowledgeBaseJavaEE = ruleBasePackage;
    }

    @Override
    public Abonnement calculate(@WebParam(name = "abonnement") Abonnement abonnement) {
        RuleBaseSession sessionStatefull = null;
        try {
            sessionStatefull = platformKnowledgeBaseJavaEE.createRuleBaseSession();
            sessionStatefull.fireAllRulesAndStartProcess(abonnement, "P1.P1");
            sessionStatefull.dispose();
        } catch (DroolsChtijbugException e) {
            logger.error("Error in fireallrules", e);
        }
        return abonnement;
    }
}

package swimmingpool.service;

import org.chtijbug.drools.platform.runtime.servlet.DroolsPlatformKnowledgeBaseJavaEE;
import org.chtijbug.drools.runtime.DroolsChtijbugException;
import org.chtijbug.drools.runtime.RuleBaseSession;
import org.chtijbug.example.swimmingpool.Abonnement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jws.WebParam;
import javax.jws.WebService;

@WebService(endpointInterface = "swimmingpool.service.IServiceCalculate")
public class ServiceCalculate implements IServiceCalculate {
    private static Logger logger = LoggerFactory.getLogger(ServiceCalculate.class);

    private DroolsPlatformKnowledgeBaseJavaEE platformKnowledgeBaseJavaEE;

    public void setRuleBasePackage(DroolsPlatformKnowledgeBaseJavaEE ruleBasePackage) {
        this.platformKnowledgeBaseJavaEE = ruleBasePackage;
    }

    @Override
    public Abonnement calculate(@WebParam(name = "abonnement") Abonnement abonnement) {
        RuleBaseSession sessionStatefull = null;
        try {
            sessionStatefull = platformKnowledgeBaseJavaEE.createRuleBaseSession();
            sessionStatefull.fireAllRulesAndStartProcess(abonnement, "P001");
            sessionStatefull.dispose();
        } catch (DroolsChtijbugException e) {
            logger.error("Error in fireallrules", e);
        }
        return abonnement;
    }
}

Use Correct Process Name for Swimming pool example


package com.github.jmchilton.blend4j.galaxy.beans;

import org.codehaus.jackson.annotate.JsonProperty;

public class User extends GalaxyObject {
  private String email;

  public String getEmail() {
    return email;
  }

  public void setEmail(final String email) {
    this.email = email;
  }

  @JsonProperty("nice_total_disk_usage")
  public void setNiceTotalDiskUsage(final String niceTotalDiskUsage) {

  }

  @JsonProperty("total_disk_usage")
  public void setTotalDiskUsage(final String totalDiskUsage) {

  }

  public void setUsername(final String username) {

  }

}

package com.github.jmchilton.blend4j.galaxy.beans;

import org.codehaus.jackson.annotate.JsonProperty;

public class User extends GalaxyObject {
  private String email;
  private String username;

  public String getEmail() {
    return email;
  }

  public void setEmail(final String email) {
    this.email = email;
  }

  @JsonProperty("nice_total_disk_usage")
  public void setNiceTotalDiskUsage(final String niceTotalDiskUsage) {

  }

  @JsonProperty("total_disk_usage")
  public void setTotalDiskUsage(final String totalDiskUsage) {

  }

  public void setUsername(final String username) {
    this.username = username;
  }

  public String getUsername() {
    return username;
  }

}

Include retrieval of username information


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.commons.math3.optimization;

import java.io.Serializable;

/**
 * Goal type for an optimization problem.
 * @version $Id$
 * @since 2.0
 */
public enum GoalType implements Serializable {

    /** Maximization goal. */
    MAXIMIZE,

    /** Minimization goal. */
    MINIMIZE

}

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.commons.math3.optimization;

import java.io.Serializable;

/**
 * Goal type for an optimization problem.
 *
 * @version $Id$
 * @since 2.0
 */
public enum GoalType implements Serializable {

    /** Maximization goal. */
    MAXIMIZE,

    /** Minimization goal. */
    MINIMIZE

}

Fix id tags and svn:keywords for optimization package.

git-svn-id: 80d496c472b8b763a5e941dba212da9bf48aeceb@1364392 13f79535-47bb-0310-9956-ffa450edef68


import java.util.*;
import org.xbill.DNS.*;

public class lookup {

public static void
printAnswer(String name, Lookup lookup) {
	System.out.print(name + ":");
	int result = lookup.getResult();
	if (result != Lookup.SUCCESSFUL)
		System.out.print(" " + lookup.getErrorString());
	System.out.println();
	if (lookup.getResult() == Lookup.SUCCESSFUL) {
		Record [] answers = lookup.getAnswers();
		for (int i = 0; i < answers.length; i++)
			System.out.println(answers[i]);
	}
}

public static void
main(String [] args) throws Exception {
	short type = Type.A;
	int start = 0;
	if (args.length > 2 && args[0].equals("-t")) {
		type = Type.value(args[1]);
		if (type < 0)
			throw new IllegalArgumentException("invalid type");
		start = 2;
	}
	for (int i = start; i < args.length; i++) {
		Lookup l = new Lookup(args[i], type);
		l.run();
		printAnswer(args[i], l);
	}
}

}

import java.util.*;
import org.xbill.DNS.*;

public class lookup {

public static void
printAnswer(String name, Lookup lookup) {
	System.out.print(name + ":");
	int result = lookup.getResult();
	if (result != Lookup.SUCCESSFUL)
		System.out.print(" " + lookup.getErrorString());
	System.out.println();
	Name [] aliases = lookup.getAliases();
	if (aliases.length > 0) {
		System.out.print("# aliases: ");
		for (int i = 0; i < aliases.length; i++) {
			System.out.print(aliases[i]);
			if (i < aliases.length - 1)
				System.out.print(" ");
		}
		System.out.println();
	}
	if (lookup.getResult() == Lookup.SUCCESSFUL) {
		Record [] answers = lookup.getAnswers();
		for (int i = 0; i < answers.length; i++)
			System.out.println(answers[i]);
	}
}

public static void
main(String [] args) throws Exception {
	short type = Type.A;
	int start = 0;
	if (args.length > 2 && args[0].equals("-t")) {
		type = Type.value(args[1]);
		if (type < 0)
			throw new IllegalArgumentException("invalid type");
		start = 2;
	}
	for (int i = start; i < args.length; i++) {
		Lookup l = new Lookup(args[i], type);
		l.run();
		printAnswer(args[i], l);
	}
}

}

Print a list of aliases, if any exist.

Print a list of aliases, if any exist.

git-svn-id: fcb33a7ee5ec38b96370833547f088a4e742b712@921 c76caeb1-94fd-44dd-870f-0c9d92034fc1


package de.danoeh.antennapod.core.util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

import java.util.List;

public class IntentUtils {

    public static boolean isCallable(final Context context, final Intent intent) {
        List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

}

package de.danoeh.antennapod.core.util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

import java.util.List;

public class IntentUtils {

    /*
     *  Checks if there is at least one exported activity that can be performed for the intent
     */
    public static boolean isCallable(final Context context, final Intent intent) {
        List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        for(ResolveInfo info : list) {
            if(info.activityInfo.exported) {
                return true;
            }
        }
        return false;
    }

}

Check if there is an exported activity for the intent


package uk.co.alynn.games.ld30;

import java.util.HashMap;
import java.util.Map;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;

public class AudioEngine {
    private final Map<String, Sound> m_fx = new HashMap<String, Sound>();
    private static AudioEngine s_sharedEngine = null;

    public AudioEngine() {
        loadEffect("shoot", "kick.wav");
        loadEffect("hit", "snare.wav");
        loadEffect("invader-warn", "meepmerp.wav");
        loadEffect("tractor", "tractor.wav");
        loadEffect("invader-shoot", "dink.wav");
        loadEffect("invader-hit-planet", "dop.wav");
        loadEffect("game-over", "tish.wav");
    }

    private void loadEffect(String name, String file) {
        Sound effect = Gdx.audio.newSound(Gdx.files.internal("sfx/" + file));
        m_fx.put(name, effect);
    }

    public void play(String effect) {
        Sound fx = m_fx.get(effect);
        if (effect.equals("tractor")) {
            fx.play(0.1f);
        } else {
            fx.play();
        }
    }

    public void stopAll(String effect) {
        Sound fx = m_fx.get(effect);
        fx.stop();
    }

    public static AudioEngine get() {
        if (s_sharedEngine == null) {
            s_sharedEngine = new AudioEngine();
        }
        return s_sharedEngine;
    }
}

package uk.co.alynn.games.ld30;

import java.util.HashMap;
import java.util.Map;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;

public class AudioEngine {
    private final Map<String, Sound> m_fx = new HashMap<String, Sound>();
    private static AudioEngine s_sharedEngine = null;

    public AudioEngine() {
        loadEffect("shoot", "kick.wav");
        loadEffect("hit", "snare.wav");
        loadEffect("invader-warn", "meepmerp.wav");
        loadEffect("tractor", "tractor.wav");
        loadEffect("invader-shoot", "dink.wav");
        loadEffect("invader-hit-planet", "dop.wav");
        loadEffect("game-over", "tish.wav");
    }

    private void loadEffect(String name, String file) {
        Sound effect = Gdx.audio.newSound(Gdx.files.internal("sfx/" + file));
        m_fx.put(name, effect);
    }

    public void play(String effect) {
        Sound fx = m_fx.get(effect);
        if (effect.equals("tractor")) {
            fx.play(0.6f);
        } else {
            fx.play();
        }
    }

    public void stopAll(String effect) {
        Sound fx = m_fx.get(effect);
        fx.stop();
    }

    public static AudioEngine get() {
        if (s_sharedEngine == null) {
            s_sharedEngine = new AudioEngine();
        }
        return s_sharedEngine;
    }
}

Make the tractor beam louder

Make the tractor beam louder


/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.jena.fuseki.server;

public enum OperationName {
    // Fixed names give the codebase some resilience.

    Query("SPARQL Query"),
    Update("SPARQL Update"),
    Upload("File Upload"),
    GSP("Graph Store Protocol"),
    GSP_R("Graph Store Protocol (Read)"),
    Quads("HTTP Quads")
    ;

    private final String description ;
    private OperationName(String description) { this.description = description ; }
    public String getDescription() { return description ; }

}

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.jena.fuseki.server;

public enum OperationName {
    // Fixed names give the codebase some resilience.
    Query("SPARQL Query"),
    Update("SPARQL Update"),
    Upload("File Upload"),
    GSP_RW("Graph Store Protocol"),
    GSP_R("Graph Store Protocol (Read)"),
    Quads_RW("HTTP Quads"),
    Quads_R("HTTP Quads (Read)")
    ;

    private final String description ;
    private OperationName(String description) { this.description = description ; }
    public String getDescription() { return description ; }

}

Add name to differentiate R and RW on quads/datatset.


/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software License
 * version 1.1, a copy of which has been included with this distribution in
 * the LICENSE file.
 */
package org.apache.james.services;

import java.util.Iterator;

import org.apache.avalon.phoenix.Service;

/**
 * Interface for Phoenix blocks to access a store of Users. A UserStore
 * contains one or more UserRepositories. Multiple UserRepositories may or may
 * not have overlapping membership.
 *
 * @version 1.0.0, 24/04/1999
 * @author  Federico Barbieri <scoobie@pop.systemy.it>
 * @author Charles Benett
 */
public interface UsersStore
    extends Service {

    String ROLE = "org.apache.james.services.UsersStore";

    UsersRepository getRepository( String name );

    Iterator getRepositoryNames();
}

/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software License
 * version 1.1, a copy of which has been included with this distribution in
 * the LICENSE file.
 */
package org.apache.james.services;

import java.util.Iterator;

/**
 * Interface for Phoenix blocks to access a store of Users. A UserStore
 * contains one or more UserRepositories. Multiple UserRepositories may or may
 * not have overlapping membership.
 *
 * @version 1.0.0, 24/04/1999
 * @author  Federico Barbieri <scoobie@pop.systemy.it>
 * @author Charles Benett
 */
public interface UsersStore {

    String ROLE = UsersStore.class.getName();

    UsersRepository getRepository( String name );

    Iterator getRepositoryNames();
}

Remove reference to long deprecated Service interface.

git-svn-id: 88158f914d5603334254b4adf21dfd50ec107162@107893 13f79535-47bb-0310-9956-ffa450edef68


/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.hive.util;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

public final class Types
{
    private Types() {}

    public static <A, B extends A> B checkType(A value, Class<B> target, String name)
    {
        checkNotNull(value, "%s is null", name);
        checkArgument(target.isInstance(value),
                "%s must be of type %s, not %s",
                name,
                target.getName(),
                value.getClass().getName());
        return target.cast(value);
    }
}

/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.hive.util;

import com.facebook.presto.spi.ErrorCode;
import com.facebook.presto.spi.PrestoException;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

public final class Types
{
    private Types() {}

    public static <A, B extends A> B checkType(A value, Class<B> target, String name)
    {
        checkNotNull(value, "%s is null", name);
        checkArgument(target.isInstance(value),
                "%s must be of type %s, not %s",
                name,
                target.getName(),
                value.getClass().getName());
        return target.cast(value);
    }

    public static <A, B extends A> B checkType(A value, Class<B> target, ErrorCode errorCode, String name)
    {
        checkNotNull(value, "%s is null", name);
        if (!target.isInstance(value)) {
            throw new PrestoException(errorCode, String.format(
                    "%s must be of type %s, not %s",
                    name,
                    target.getName(),
                    value.getClass().getName()));
        }
        return target.cast(value);
    }
}

Add checkType that takes an error code

Add checkType that takes an error code


package com.chaoticdawgsoftware.algorithms.providerutils;

import java.security.Provider;
import java.security.Security;
import java.util.*;

/**
 * ProviderAlgorithmRetrievingFactory.java
 * Created by ChaoticDawg on 1/20/17.
 */

public class ProviderAlgorithmRetrievingFactory {
    private static Provider[] providers = Security.getProviders();

    public static ArrayList<String> getAlgorithmList(String algorithm) {
        return getSortedAlgorithmList(buildAlgorithmList(algorithm));
    }

    private static ArrayList<String> buildAlgorithmList(String algorithm) {
        Set<String> keyNameSet = new HashSet<>();
        for (Provider provider : providers)
            ProviderKeyListCreator.getKeyList(algorithm, keyNameSet, provider);

        return new ArrayList<>(keyNameSet);
    }

    private static ArrayList<String> getSortedAlgorithmList(ArrayList<String> keyList) {
        Collections.sort(keyList);
        return keyList;
    }
}

package com.chaoticdawgsoftware.algorithms.providerutils;

import java.security.Provider;
import java.security.Security;
import java.util.*;

/**
 * ProviderAlgorithmRetrievingFactory.java
 * Created by ChaoticDawg on 1/20/17.
 */

public class ProviderAlgorithmRetrievingFactory {
    private static Provider[] providers = Security.getProviders();

    public static ArrayList<String> getAlgorithmList(String algorithm) {
        ArrayList<String> AlgorithmList = buildAlgorithmList(algorithm);
        Collections.sort(AlgorithmList);
        return AlgorithmList;
    }

    private static ArrayList<String> buildAlgorithmList(String algorithm) {
        Set<String> keyNameSet = new HashSet<>();
        for (Provider provider : providers)
            ProviderKeyListCreator.getKeyList(algorithm, keyNameSet, provider);

        return new ArrayList<>(keyNameSet);
    }
}

Remove getSortedAlgorithmList method add sort to getAlgorithmList


package net.openhft.chronicle.wire;

import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertEquals;

/**
 * Created by peter on 17/05/2017.
 */
public class TextMethodTesterTest {
    @Test
    public void run() throws IOException {
        TextMethodTester test = new TextMethodTester<>(
                "methods-in.yaml",
                MockMethodsImpl::new,
                MockMethods.class,
                "methods-in.yaml").run();
        assertEquals(test.expected(), test.actual());
    }
}

class MockMethodsImpl implements MockMethods {
    private final MockMethods out;

    public MockMethodsImpl(MockMethods out) {
        this.out = out;
    }

    @Override
    public void method1(MockDto dto) {
        out.method1(dto);
    }

    @Override
    public void method2(MockDto dto) {
        out.method2(dto);
    }
}

package net.openhft.chronicle.wire;

import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertEquals;

/**
 * Created by peter on 17/05/2017.
 */
public class TextMethodTesterTest {
    @Test
    public void run() throws IOException {
        TextMethodTester test = new TextMethodTester<>(
                "methods-in.yaml",
                MockMethodsImpl::new,
                MockMethods.class,
                "methods-in.yaml")
                .setup("methods-in.yaml") // calls made here are ignored.
                .run();
        assertEquals(test.expected(), test.actual());
    }
}

class MockMethodsImpl implements MockMethods {
    private final MockMethods out;

    public MockMethodsImpl(MockMethods out) {
        this.out = out;
    }

    @Override
    public void method1(MockDto dto) {
        out.method1(dto);
    }

    @Override
    public void method2(MockDto dto) {
        out.method2(dto);
    }
}

Add support for a setup phase which is not recorded.


/**
 * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.financial.aggregation;

import java.util.Collection;
import java.util.Collections;

import com.opengamma.core.position.Position;
import com.opengamma.financial.security.FinancialSecurityUtils;
/**
 * Function to classify positions by Currency.
 *
 */
public class CurrencyAggregationFunction implements AggregationFunction<String> {

  private static final String NAME = "Currency";

  @Override
  public String classifyPosition(Position position) {
    try {
      return FinancialSecurityUtils.getCurrency(position.getSecurity()).toString();
    } catch (UnsupportedOperationException ex) {
      return "No or multiple currencies";
    }
  }

  public String getName() {
    return NAME;
  }

  @Override
  public Collection<String> getRequiredEntries() {
    return Collections.emptyList();
  }
}

/**
 * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.financial.aggregation;

import java.util.Collection;
import java.util.Collections;

import com.opengamma.core.position.Position;
import com.opengamma.financial.security.FinancialSecurityUtils;
import com.opengamma.util.money.Currency;
/**
 * Function to classify positions by Currency.
 *
 */
public class CurrencyAggregationFunction implements AggregationFunction<String> {

  private static final String NAME = "Currency";
  private static final String NO_CURRENCY = "No or multiple currencies";

  @Override
  public String classifyPosition(Position position) {
    try {
      Currency currency = FinancialSecurityUtils.getCurrency(position.getSecurity());
      if (currency == null) {
        return NO_CURRENCY;
      }
      return currency.toString();
    } catch (UnsupportedOperationException ex) {
      return NO_CURRENCY;
    }
  }

  public String getName() {
    return NAME;
  }

  @Override
  public Collection<String> getRequiredEntries() {
    return Collections.emptyList();
  }
}

Handle no currency properly, as well as multiple currency


package org.jvnet.hudson.plugins.triggers.startup;

import hudson.model.Node;

import java.io.Serializable;

/**
 * @author Gregory Boissinot
 */
public class HudsonStartupService implements Serializable {

    public boolean has2Schedule(HudsonStartupTrigger startupTrigger, Node jobNode) {

        if (startupTrigger == null) {
            throw new NullPointerException("A startupTrigger object has to be set.");
        }
        if (jobNode == null) {
            throw new NullPointerException("A node object has to be set.");
        }

        String triggerLabel = startupTrigger.getLabel();

        return has2Schedule(triggerLabel, jobNode);
    }

    private boolean has2Schedule(String triggerLabel, Node jobNode) {

        String jobNodeName = jobNode.getNodeName();

        if (triggerLabel == null) { //Jobs on master has to schedule
            return isMaster(jobNodeName);
        }

        if (triggerLabel.equalsIgnoreCase("master")) { //User set 'master' string, Jobs on master has to schedule
            return isMaster(jobNodeName);
        }

        if (triggerLabel.equalsIgnoreCase(jobNodeName)) { //Match exactly node name
            return true;
        }

        return triggerLabel.equalsIgnoreCase(jobNode.getLabelString());  //Match node label
    }

    private boolean isMaster(String nodeName) {
        //Master node name is "", slave node name is never empty
        return nodeName.equals("");
    }

}

package org.jvnet.hudson.plugins.triggers.startup;

import hudson.model.Node;

import java.io.Serializable;

/**
 * @author Gregory Boissinot
 */
public class HudsonStartupService implements Serializable {

    public boolean has2Schedule(HudsonStartupTrigger startupTrigger, Node jobNode) {

        if (startupTrigger == null) {
            throw new NullPointerException("A startupTrigger object has to be set.");
        }
        if (jobNode == null) {
            throw new NullPointerException("A node object has to be set.");
        }

        String triggerLabel = startupTrigger.getLabel();

        return has2Schedule(triggerLabel, jobNode);
    }

    private boolean has2Schedule(String triggerLabel, Node jobNode) {

        String jobNodeName = jobNode.getNodeName();

        if (triggerLabel == null) { //Jobs on master has to schedule
            return isMaster(jobNodeName);
        }

        if (triggerLabel.equalsIgnoreCase("master")) { //User set 'master' string, Jobs on master has to schedule
            return isMaster(jobNodeName);
        }

        if (triggerLabel.equalsIgnoreCase(jobNodeName)) { //Match exactly node name
            return true;
        }

        String labelString = jobNode.getLabelString();
        if (labelString == null) {
            return false;
        }

        if (triggerLabel.equalsIgnoreCase(labelString)) { //Match node label
            return true;
        }

        return labelString.contains(triggerLabel);
    }

    private boolean isMaster(String nodeName) {
        //Master node name is "", slave node name is never empty
        return nodeName.equals("");
    }

}

Enable to specify a string for the trigger label as a substring of the node label. For example a node label with "WinXP Acceptance London" and 'Restricted node Label = London'


package org.realityforge.jeo.geolatte.jpa.eclipselink;

import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class DatabaseTestUtil
{
  static Properties initDatabaseProperties()
  {
    final Properties properties = new Properties();
    properties.put( "javax.persistence.jdbc.driver", "org.postgis.DriverWrapperAutoprobe" );
    final String databaseUrl = "jdbc:postgresql_autogis://127.0.0.1:5432/geolatte_test";
    setProperty( properties, "javax.persistence.jdbc.url", "test.db.url", databaseUrl );
    setProperty( properties, "javax.persistence.jdbc.user", "test.db.user", "geolatte" );
    setProperty( properties, "javax.persistence.jdbc.password", "test.db.password", null );
    properties.put( "eclipselink.session-event-listener", GeolatteExtension.class.getName() );
    return properties;
  }

  private static void setProperty( final Properties properties,
                                   final String key,
                                   final String systemPropertyKey, final String defaultValue )
  {
    final String value = System.getProperty( systemPropertyKey, defaultValue );
    if ( null != value )
    {
      properties.put( key, value );
    }
  }

  public static EntityManager createEntityManager( final String persistenceUnitName )
  {
    final Properties properties = initDatabaseProperties();
    final EntityManagerFactory factory = Persistence.createEntityManagerFactory( persistenceUnitName, properties );
    return factory.createEntityManager();
  }
}

package org.realityforge.jeo.geolatte.jpa.eclipselink;

import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class DatabaseTestUtil
{
  static Properties initDatabaseProperties()
  {
    final Properties properties = new Properties();
    properties.put( "javax.persistence.jdbc.driver", "org.postgresql.Driver" );
    final String databaseUrl = "jdbc:postgresql://127.0.0.1:5432/geolatte_test";
    setProperty( properties, "javax.persistence.jdbc.url", "test.db.url", databaseUrl );
    setProperty( properties, "javax.persistence.jdbc.user", "test.db.user", "geolatte" );
    setProperty( properties, "javax.persistence.jdbc.password", "test.db.password", null );
    properties.put( "eclipselink.session-event-listener", GeolatteExtension.class.getName() );
    return properties;
  }

  private static void setProperty( final Properties properties,
                                   final String key,
                                   final String systemPropertyKey, final String defaultValue )
  {
    final String value = System.getProperty( systemPropertyKey, defaultValue );
    if ( null != value )
    {
      properties.put( key, value );
    }
  }

  public static EntityManager createEntityManager( final String persistenceUnitName )
  {
    final Properties properties = initDatabaseProperties();
    final EntityManagerFactory factory = Persistence.createEntityManagerFactory( persistenceUnitName, properties );
    return factory.createEntityManager();
  }
}

Revert to using the base postgres driver in tests


package net.md_5.bungee.api.plugin;

import java.util.Set;
import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * POJO representing the plugin.yml file.
 */
@Data
@AllArgsConstructor
public class PluginDescription
{

    /**
     * Friendly name of the plugin.
     */
    private String name;
    /**
     * Plugin main class. Needs to extend {@link Plugin}.
     */
    private String main;
    /**
     * Plugin version.
     */
    private String version;
    /**
     * Plugin author.
     */
    private String author;
    /**
     * Plugin hard dependencies.
     */
    private Set<String> depends;

    public PluginDescription()
    {
    }
}

package net.md_5.bungee.api.plugin;

import java.util.HashSet;
import java.util.Set;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * POJO representing the plugin.yml file.
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PluginDescription
{

    /**
     * Friendly name of the plugin.
     */
    private String name;
    /**
     * Plugin main class. Needs to extend {@link Plugin}.
     */
    private String main;
    /**
     * Plugin version.
     */
    private String version;
    /**
     * Plugin author.
     */
    private String author;
    /**
     * Plugin hard dependencies.
     */
    private Set<String> depends = new HashSet<>();
}

Initialize depends set to an empty set to prevent a NPE when no depends given.