package ch.ethz.geco.bass.audio.gson;

import ch.ethz.geco.bass.audio.util.AudioTrackMetaData;
import com.google.gson.*;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo;

import java.lang.reflect.Type;
import java.util.Map;

/**
 * Serializes an AudioTrack to json.
 */
public class AudioTrackSerializer implements JsonSerializer<AudioTrack> {
    @Override
    public JsonElement serialize(AudioTrack src, Type typeOfSrc, JsonSerializationContext context) {
        AudioTrackInfo info = src.getInfo();

        // Get meta data
        AudioTrackMetaData metaData = (AudioTrackMetaData) src.getUserData();

        // Parse votes to json array
        JsonArray votes = new JsonArray();
        for (Map.Entry<String, Byte> entry : metaData.getVotes().entrySet()) {
            JsonObject vote = new JsonObject();
            vote.addProperty(entry.getKey(), entry.getValue());
            votes.add(vote);
        }

        JsonObject jsonTrack = new JsonObject();
        jsonTrack.addProperty("id", metaData.getTrackID());
        jsonTrack.addProperty("uri", info.uri);
        jsonTrack.addProperty("userID", metaData.getUserID());
        jsonTrack.addProperty("title", info.title);
        jsonTrack.add("votes", votes);
        jsonTrack.addProperty("length", info.length);
        jsonTrack.addProperty("position", src.getPosition());

        return jsonTrack;
    }
}

package ch.ethz.geco.bass.audio.gson;

import ch.ethz.geco.bass.audio.util.AudioTrackMetaData;
import com.google.gson.*;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo;

import java.lang.reflect.Type;
import java.util.Map;

/**
 * Serializes an AudioTrack to json.
 */
public class AudioTrackSerializer implements JsonSerializer<AudioTrack> {
    @Override
    public JsonElement serialize(AudioTrack src, Type typeOfSrc, JsonSerializationContext context) {
        AudioTrackInfo info = src.getInfo();

        // Get meta data
        AudioTrackMetaData metaData = (AudioTrackMetaData) src.getUserData();

        // Parse votes to json array
        JsonArray votes = new JsonArray();
        for (Map.Entry<String, Byte> entry : metaData.getVotes().entrySet()) {
            JsonObject vote = new JsonObject();
            vote.addProperty(entry.getKey(), entry.getValue());
            votes.add(vote);
        }

        JsonObject jsonTrack = new JsonObject();
        jsonTrack.addProperty("id", metaData.getTrackID());
        jsonTrack.addProperty("uri", info.uri);
        jsonTrack.addProperty("userID", metaData.getUserID());
        jsonTrack.addProperty("title", info.title);
        jsonTrack.add("voters", votes);
        jsonTrack.addProperty("votes", metaData.getVoteCount());
        jsonTrack.addProperty("length", info.length);
        jsonTrack.addProperty("position", src.getPosition());

        return jsonTrack;
    }
}

Send vote count to interface

Send vote count to interface


package fi.evident.apina.spring.java.model;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class JavaAnnotationTest {

    @Test
    public void toStringWithoutParameters() {
        JavaAnnotation annotation = new JavaAnnotation(new QualifiedName("foo.bar.Baz"));
        assertThat(annotation.toString(), is("@foo.bar.Baz"));
    }

    @Test
    public void toStringWithJustValue() {
        JavaAnnotation annotation = new JavaAnnotation(new QualifiedName("foo.bar.Baz"));
        annotation.setAttribute("value", 42);

        assertThat(annotation.toString(), is("@foo.bar.Baz(42)"));
    }

    @Test
    public void toStringWithNonValueAttribute() {
        JavaAnnotation annotation = new JavaAnnotation(new QualifiedName("foo.bar.Baz"));
        annotation.setAttribute("foo", 42);

        assertThat(annotation.toString(), is("@foo.bar.Baz(foo=42)"));
    }

    @Test
    public void toStringWithMultipleAttributes() {
        JavaAnnotation annotation = new JavaAnnotation(new QualifiedName("foo.bar.Baz"));
        annotation.setAttribute("value", 1);
        annotation.setAttribute("foo", 2);
        annotation.setAttribute("bar", 3);

        assertThat(annotation.toString(), is("@foo.bar.Baz(value=1, foo=2, bar=3)"));
    }
}

package fi.evident.apina.spring.java.model;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class JavaAnnotationTest {

    @Test
    public void toStringWithoutParameters() {
        JavaAnnotation annotation = newAnnotation("foo.bar.Baz");
        assertThat(annotation.toString(), is("@foo.bar.Baz"));
    }

    @Test
    public void toStringWithJustValue() {
        JavaAnnotation annotation = newAnnotation("foo.bar.Baz");
        annotation.setAttribute("value", 42);

        assertThat(annotation.toString(), is("@foo.bar.Baz(42)"));
    }

    @Test
    public void toStringWithNonValueAttribute() {
        JavaAnnotation annotation = newAnnotation("foo.bar.Baz");
        annotation.setAttribute("foo", 42);

        assertThat(annotation.toString(), is("@foo.bar.Baz(foo=42)"));
    }

    @Test
    public void toStringWithMultipleAttributes() {
        JavaAnnotation annotation = newAnnotation("foo.bar.Baz");
        annotation.setAttribute("value", 1);
        annotation.setAttribute("foo", 2);
        annotation.setAttribute("bar", 3);

        assertThat(annotation.toString(), is("@foo.bar.Baz(value=1, foo=2, bar=3)"));
    }

    private static JavaAnnotation newAnnotation(String name) {
        return new JavaAnnotation(new QualifiedName(name));
    }
}

Remove duplication in test code

Remove duplication in test code


/*
 * MIT Licence
 * Copyright (c) 2017 Simon Frankenberger
 *
 * Please see LICENCE.md for complete licence text.
 */
package eu.fraho.spring.example;

import eu.fraho.spring.securityJwt.CryptPasswordEncoder;
import eu.fraho.spring.securityJwt.config.CryptConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.io.IOException;
import java.security.Security;

@SpringBootApplication(scanBasePackages = {"eu.fraho.spring.example", "eu.fraho.spring.securityJwt"})
@Slf4j
public class RegularNoRefreshApplication {
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static void main(String[] args) throws IOException {
        SpringApplication.run(RegularNoRefreshApplication.class, args);
    }

    @Bean
    public PasswordEncoder passwordEncoder(final CryptConfiguration configuration) {
        return new CryptPasswordEncoder(configuration);
    }
}

/*
 * MIT Licence
 * Copyright (c) 2017 Simon Frankenberger
 *
 * Please see LICENCE.md for complete licence text.
 */
package eu.fraho.spring.example;

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.IOException;
import java.security.Security;

@SpringBootApplication(scanBasePackages = {"eu.fraho.spring.example", "eu.fraho.spring.securityJwt"})
@Slf4j
public class RegularNoRefreshApplication {
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static void main(String[] args) throws IOException {
        SpringApplication.run(RegularNoRefreshApplication.class, args);
    }
}

Remove not needed bean declaration

Remove not needed bean declaration


/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * 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.android.phone;

import com.android.internal.telephony.DebugService;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import java.io.FileDescriptor;
import java.io.PrintWriter;

/**
 * A debug service for telephony.
 */
public class TelephonyDebugService extends Service {
    private static String TAG = "TelephonyDebugService";
    private DebugService mDebugService = new DebugService();

    /** Constructor */
    public TelephonyDebugService() {
        Log.d(TAG, "TelephonyDebugService()");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
        enforceCallingOrSelfPermission(android.Manifest.permission.DUMP,
                                       "Requires DUMP");
        mDebugService.dump(fd, pw, args);
    }
}

/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * 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.android.phone;

import com.android.internal.telephony.DebugService;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import java.io.FileDescriptor;
import java.io.PrintWriter;

/**
 * A debug service for telephony.
 */
public class TelephonyDebugService extends Service {
    private static String TAG = "TelephonyDebugService";
    private DebugService mDebugService = new DebugService();

    /** Constructor */
    public TelephonyDebugService() {
        Log.d(TAG, "TelephonyDebugService()");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
        mDebugService.dump(fd, pw, args);
    }
}

Revert "enforce dump permission on dump()"

Stability blocker.

java.lang.SecurityException: Requires DUMP: Neither user 1001 nor current process has android.permission.DUMP.
       at android.app.ContextImpl.enforce(ContextImpl.java:1893)
       at android.app.ContextImpl.enforceCallingOrSelfPermission(ContextImpl.java:1922)
       at android.content.ContextWrapper.enforceCallingOrSelfPermission(ContextWrapper.java:593)
       at com.android.phone.TelephonyDebugService.dump(TelephonyDebugService.java:50)
       at android.app.ActivityThread.handleDumpService(ActivityThread.java:2813)
       at android.app.ActivityThread.access$2300(ActivityThread.java:144)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1399)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:135)
       at android.app.ActivityThread.main(ActivityThread.java:5221)
       at java.lang.reflect.Method.invoke(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
This reverts commit 8e4dae587f8a4dd20b06c16e4f7fd3723ff56774.

Bug: 18090004
Change-Id: Id9a549971dbe7a5b4baeb7067967cd791541cf4a


package com.example;

import org.gradle.api.DefaultTask;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.ListProperty;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.PathSensitive;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.api.tasks.TaskAction;
import org.gradle.util.GFileUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.util.regex.Pattern;

/**
 * Verifies that the given readme file contains the desired patterns.
 */
public abstract class ReadmeVerificationTask extends DefaultTask {

    @PathSensitive(PathSensitivity.RELATIVE)
    @InputFile
    public abstract RegularFileProperty getReadme();

    @Internal
    public abstract ListProperty<String> getReadmePatterns();

    @TaskAction
    void verifyServiceReadme() throws IOException {
        String readmeContents = Files.readString(getReadme().getAsFile().get().toPath());
        for (String requiredSection : getReadmePatterns().get()) {
            Pattern pattern = Pattern.compile(requiredSection, Pattern.MULTILINE);
            if (!pattern.matcher(readmeContents).find()) {
                throw new RuntimeException("README should contain section: " + pattern.pattern());
            }
        }
    }
}

package com.example;

import org.gradle.api.DefaultTask;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.ListProperty;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.PathSensitive;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.api.tasks.TaskAction;
import org.gradle.util.GFileUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.util.regex.Pattern;

/**
 * Verifies that the given readme file contains the desired patterns.
 */
public abstract class ReadmeVerificationTask extends DefaultTask {

    @PathSensitive(PathSensitivity.RELATIVE)
    @InputFile
    public abstract RegularFileProperty getReadme();

    @Internal
    public abstract ListProperty<String> getReadmePatterns();

    @TaskAction
    void verifyServiceReadme() throws IOException {
        String readmeContents = new String (Files.readAllBytes(getReadme().getAsFile().get().toPath()));
        for (String requiredSection : getReadmePatterns().get()) {
            Pattern pattern = Pattern.compile(requiredSection, Pattern.MULTILINE);
            if (!pattern.matcher(readmeContents).find()) {
                throw new RuntimeException("README should contain section: " + pattern.pattern());
            }
        }
    }
}

Make precompiled script plugin sample backwards compatible with JDK8


package seedu.task.logic;

import java.util.logging.Logger;

import javafx.collections.ObservableList;
import seedu.task.commons.core.ComponentManager;
import seedu.task.commons.core.LogsCenter;
import seedu.task.logic.commands.Command;
import seedu.task.logic.commands.CommandResult;
import seedu.task.logic.commands.exceptions.CommandException;
import seedu.task.logic.parser.Parser;
import seedu.task.model.Model;
import seedu.task.model.task.ChatList;
import seedu.task.model.task.ReadOnlyTask;
import seedu.task.storage.Storage;

/**
 * The main LogicManager of the app.
 */
public class LogicManager extends ComponentManager implements Logic {
    private final Logger logger = LogsCenter.getLogger(LogicManager.class);

    private final Model model;
    private final Parser parser;

    public LogicManager(Model model, Storage storage) {
        this.model = model;
        this.parser = new Parser();
    }

    @Override
    public CommandResult execute(String commandText) throws CommandException {
        logger.info("----------------[USER COMMAND][" + commandText + "]");
        Command command = parser.parseCommand(commandText);
        command.setData(model);
        return command.execute();
    }

    @Override
    public ObservableList<ReadOnlyTask> getFilteredTaskList() {
        return model.getFilteredTaskList();
    }

    @Override
    public ChatList getChatList() {
        // TODO Auto-generated method stub
        return model.getChatList();
    }
}

package seedu.task.logic;

import java.util.logging.Logger;

import javafx.collections.ObservableList;
import seedu.task.commons.core.ComponentManager;
import seedu.task.commons.core.LogsCenter;
import seedu.task.logic.commands.Command;
import seedu.task.logic.commands.CommandResult;
import seedu.task.logic.commands.exceptions.CommandException;
import seedu.task.logic.parser.Parser;
import seedu.task.model.Model;
import seedu.task.model.task.Chat;
import seedu.task.model.task.ChatList;
import seedu.task.model.task.ReadOnlyTask;
import seedu.task.storage.Storage;

/**
 * The main LogicManager of the app.
 */
public class LogicManager extends ComponentManager implements Logic {
    private final Logger logger = LogsCenter.getLogger(LogicManager.class);

    private final Model model;
    private final Parser parser;

    public LogicManager(Model model, Storage storage) {
        this.model = model;
        this.parser = new Parser();
    }

    @Override
    public CommandResult execute(String commandText) throws CommandException {
        logger.info("----------------[USER COMMAND][" + commandText + "]");
        ChatList chatList = getChatList();
        chatList.add(new Chat(commandText));
        Command command = parser.parseCommand(commandText);
        command.setData(model);
        return command.execute();
    }

    @Override
    public ObservableList<ReadOnlyTask> getFilteredTaskList() {
        return model.getFilteredTaskList();
    }

    @Override
    public ChatList getChatList() {
        // TODO Auto-generated method stub
        return model.getChatList();
    }
}

Add user’s commands to chat

Add user’s commands to chat


package com.mikepenz.fastadapter.app;

import com.mikepenz.fastadapter.extensions.ExtensionsFactories;
import com.mikepenz.fastadapter.select.SelectExtensionFactory;

import androidx.multidex.MultiDexApplication;
import io.realm.Realm;
import io.realm.RealmConfiguration;

/**
 * Created by mikepenz on 04.07.16.
 */

public class CustomApplication extends MultiDexApplication {
    @Override
    public void onCreate() {
        super.onCreate();
        // The Realm file will be located in Context.getFilesDir() with name "default.realm"
        Realm.init(this);
        RealmConfiguration config = new RealmConfiguration.Builder().build();
        Realm.setDefaultConfiguration(config);

        ExtensionsFactories.INSTANCE.register(new SelectExtensionFactory());
    }
}

package com.mikepenz.fastadapter.app;

import com.mikepenz.fastadapter.expandable.ExpandableExtensionFactory;
import com.mikepenz.fastadapter.extensions.ExtensionsFactories;
import com.mikepenz.fastadapter.select.SelectExtensionFactory;

import androidx.multidex.MultiDexApplication;
import io.realm.Realm;
import io.realm.RealmConfiguration;

/**
 * Created by mikepenz on 04.07.16.
 */

public class CustomApplication extends MultiDexApplication {
    @Override
    public void onCreate() {
        super.onCreate();
        // The Realm file will be located in Context.getFilesDir() with name "default.realm"
        Realm.init(this);
        RealmConfiguration config = new RealmConfiguration.Builder().build();
        Realm.setDefaultConfiguration(config);

        ExtensionsFactories.INSTANCE.register(new SelectExtensionFactory());
        ExtensionsFactories.INSTANCE.register(new ExpandableExtensionFactory());
    }
}

Add expandable extension factory to application


package com.bbn.bue.common.evaluation;

import java.io.File;
import java.io.IOException;

/**
 * An object which records scoring events of objects where the expected (gold) item is of type {@link KeyT} and the
 * predicted (system) item is of type {@link TestT}.
 *
 * {@link #finish(File)} is expected to be called when there are no more items to inspect. What happens if more items
 * are observed after finishing is not defined by the interface contract.
 *
 * Implementations may silently take no action for some types of observations. For example, an F-score related observer
 * would take no action upon observation of a true negative. However, an implementation should raise an exception simply
 * because it is asked to observe an event for which it will take no action.
 *
 * @author Constantine Lignos
 */
public interface ScoringEventObserver<KeyT, TestT> {

  /**
   * Records a true positive event.
   */
  void observeTruePositive(KeyT gold, TestT predicted, double score);

  /**
   * Records a true negative event.
   */
  void observeTrueNegative(KeyT gold, TestT predicted, double score);

  /**
   * Records a false positive event.
   */
  void observeFalsePositive(TestT predicted, double score);

  /**
   * Records a false negative event.
   */
  void observeFalseNegative(KeyT gold, double score);

  /**
   * Performs any final tasks, using the specified output directory as the base for output.
   */
  void finish(File outputDirectory) throws IOException;
}

package com.bbn.bue.common.evaluation;

import java.io.File;
import java.io.IOException;

/**
 * An object which records scoring events of objects where the expected (gold) item is of type {@link KeyT} and the
 * predicted (system) item is of type {@link TestT}.
 *
 * {@link #finish(File)} is expected to be called when there are no more items to inspect. What happens if more items
 * are observed after finishing is not defined by the interface contract.
 *
 * Implementations may silently take no action for some types of observations. For example, an F-score related observer
 * would take no action upon observation of a true negative. However, an implementation should not raise an exception
 * simply because it is asked to observe an event for which it will take no action.
 *
 * @author Constantine Lignos
 */
public interface ScoringEventObserver<KeyT, TestT> {

  /**
   * Records a true positive event.
   */
  void observeTruePositive(KeyT gold, TestT predicted, double score);

  /**
   * Records a true negative event.
   */
  void observeTrueNegative(KeyT gold, TestT predicted, double score);

  /**
   * Records a false positive event.
   */
  void observeFalsePositive(TestT predicted, double score);

  /**
   * Records a false negative event.
   */
  void observeFalseNegative(KeyT gold, double score);

  /**
   * Performs any final tasks, using the specified output directory as the base for output.
   */
  void finish(File outputDirectory) throws IOException;
}

Add missing negation to documentation.

Add missing negation to documentation.


/*
 * Mutability Detector
 *
 * Copyright 2009 Graham Allan
 *
 * 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.mutabilitydetector.checkers;

import static org.mutabilitydetector.checkers.AccessModifierQuery.method;

import org.mutabilitydetector.MutabilityReason;
import org.objectweb.asm.FieldVisitor;

public class PublishedNonFinalFieldChecker extends AbstractMutabilityChecker {

	@Override
	public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
		if (method(access).isNotPrivate()){
			if (!method(access).isFinal()) {
				addResult("Field [" + name + "] is visible outwith this class, and is not declared final.",
						null, MutabilityReason.PUBLISHED_NON_FINAL_FIELD);
			}
		}
		return super.visitField(access, name, desc, signature, value);
	}
}

/*
 * Mutability Detector
 *
 * Copyright 2009 Graham Allan
 *
 * 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.mutabilitydetector.checkers;

import static org.mutabilitydetector.checkers.AccessModifierQuery.field;

import org.mutabilitydetector.MutabilityReason;
import org.objectweb.asm.FieldVisitor;

public class PublishedNonFinalFieldChecker extends AbstractMutabilityChecker {

	@Override
	public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
		if (field(access).isNotPrivate() && field(access).isNotFinal()) {
			addResult("Field [" + name + "] is visible outwith this class, and is not declared final.",
					null,
					MutabilityReason.PUBLISHED_NON_FINAL_FIELD);
		}
		return super.visitField(access, name, desc, signature, value);
	}
}

Make the access check code a bit more readable.

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


/*******************************************************************************
 * Copyright (c) 2017 Inria
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *  - Faiez Zalila <faiez.zalila@inria.fr>
 *******************************************************************************/
package org.eclipse.cmf.occi.core;
/**
 * Constants related to OCCI.
 *
 * @author Faiez Zalila - Inria
 */
public interface OCCICoreConstants
{
	/**
	 * OCCI core URI.
	 */
	public static final String OCCI_CORE_URI = "http://schemas.ogf.org/occi/core/";

	/**
	 * OCCI core scheme.
	 */
	public static final String OCCI_CORE_SCHEME = "http://schemas.ogf.org/occi/core#";

	/**
	 * OCCI Core entity term.
	 */
	public static final String OCCI_CORE_ENTITY_TERM = "entity";

	/**
	 * OCCI Core resource term.
	 */
	public static final String OCCI_CORE_RESOURCE_TERM = "resource";

	/**
	 * OCCI Core link term.
	 */
	public static final String OCCI_CORE_LINK_TERM = "link";
}

/*******************************************************************************
 * Copyright (c) 2016-17 Inria
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * - Philippe Merle <philippe.merle@inria.fr>
 * - Faiez Zalila <faiez.zalila@inria.fr>
 *******************************************************************************/
package org.eclipse.cmf.occi.core;

/**
 * Constants related to OCCI.
 *
 * @author Philippe Merle - Inria
 */
public interface OcciCoreConstants
{
	/**
	 * OCCI core URI.
	 */
	public static final String OCCI_CORE_URI = "http://schemas.ogf.org/occi/core";

	/**
	 * OCCI core scheme.
	 */
	public static final String OCCI_CORE_SCHEME = "http://schemas.ogf.org/occi/core#";

	/**
	 * OCCI Core entity term.
	 */
	public static final String OCCI_CORE_ENTITY_TERM = "entity";

	/**
	 * OCCI Core resource term.
	 */
	public static final String OCCI_CORE_RESOURCE_TERM = "resource";

	/**
	 * OCCI Core link term.
	 */
	public static final String OCCI_CORE_LINK_TERM = "link";
}

Reset OCCI_CORE_SCHEME to its previous value.


package org.jetbrains.idea.maven.dom;

import java.io.IOException;

/**
 * @author Sergey Evdokimov
 */
public class MavenDependencyCompletionTest extends MavenDomWithIndicesTestCase {

  public void testCompletion() throws IOException {
    createProjectPom("<groupId>test</groupId>" +
                     "<artifactId>project</artifactId>" +
                     "<version>1</version>" +

                     "<dependencies>" +
                     "  <dependency>" +
                     "    jun<caret>" +
                     "  </dependency>" +
                     "</dependencies>");

    assertCompletionVariantsInclude(myProjectPom, "junit:junit");
  }

}

package org.jetbrains.idea.maven.dom;

import com.intellij.codeInsight.completion.CompletionType;
import com.intellij.codeInsight.lookup.LookupElement;

import java.io.IOException;

/**
 * @author Sergey Evdokimov
 */
public class MavenDependencyCompletionTest extends MavenDomWithIndicesTestCase {

  public void testCompletion() throws IOException {
    createProjectPom("<groupId>test</groupId>" +
                     "<artifactId>project</artifactId>" +
                     "<version>1</version>" +

                     "<dependencies>" +
                     "  <dependency>" +
                     "    <caret>" +
                     "  </dependency>" +
                     "</dependencies>");

    assertCompletionVariantsInclude(myProjectPom, "junit:junit");
  }

  public void testInsertDependency() throws IOException {
    createProjectPom("<groupId>test</groupId>\n" +
                     "<artifactId>project</artifactId>\n" +
                     "<version>1</version>\n" +

                     "<dependencies>\n" +
                     "  <dependency>ju<caret></dependency>\n" +
                     "</dependencies>\n");

    configTest(myProjectPom);
    myFixture.complete(CompletionType.SMART);
    assertContain(myFixture.getLookupElementStrings(), "4.0", "3.8.2");

    myFixture.checkResult(createPomXml("<groupId>test</groupId>\n" +
                                       "<artifactId>project</artifactId>\n" +
                                       "<version>1</version>\n" +

                                       "<dependencies>\n" +
                                       "    <dependency>\n" +
                                       "        <groupId>junit</groupId>\n" +
                                       "        <artifactId>junit</artifactId>\n" +
                                       "        <version><caret></version>\n" +
                                       "    </dependency>\n" +
                                       "</dependencies>\n"));
  }

}

Add test for inserting maven dependency by smart completion


package monads;

import static org.junit.Assert.assertEquals;
import static monads.Stack.*;
import static monads.Pair.*;

import org.junit.Test;

public class StackTest {

	private static final Object A = new Object();
	private static final Object B = new Object();

	private Pair pair = pair(empty());

	@Test public void
	starts_empty() {
		assertEquals(empty(), pair.stack);
	}

	@Test(expected = Exception.class) public void
	forbids_pop_when_empty() {
		pop(pair.stack);
	}

	@Test public void
	pushes_and_pops_an_objects() {
		pair = push(pair.stack, A);

		pair = pop(pair.stack);
		assertEquals(A, pair.value);
		assertEquals(empty(), pair.stack);
	}

	@Test public void
	pops_objects_in_reverse_push_order() {
		pair = push(pair.stack, A);
		pair = push(pair.stack, B);

		pair = pop(pair.stack);
		assertEquals(B, pair.value);

		pair = pop(pair.stack);
		assertEquals(A, pair.value);

		assertEquals(empty(), pair.stack);
	}
}

package monads;

import static org.junit.Assert.assertEquals;
import static monads.Stack.*;
import static monads.Pair.*;

import org.junit.Test;

public class StackTest {

	private static final Object A = new Object();
	private static final Object B = new Object();

	private Pair pair = pair(empty());

	@Test public void
	starts_empty() {
		assertEquals(empty(), pair.stack);
	}

	@Test(expected = Exception.class) public void
	forbids_pop_when_empty() {
		pop(pair.stack);
	}

	private static interface StackFunction {
		Pair eval(Stack stack);
	}
	@Test public void
	pushes_and_pops_an_objects() {
		pair = new StackFunction() {
			public Pair eval(Stack stack) {
				return stack.push(stack, A);
			}
		}.eval(pair.stack);

		pair = pop(pair.stack);
		assertEquals(A, pair.value);
		assertEquals(empty(), pair.stack);
	}

	@Test public void
	pops_objects_in_reverse_push_order() {
		pair = push(pair.stack, A);
		pair = push(pair.stack, B);

		pair = pop(pair.stack);
		assertEquals(B, pair.value);

		pair = pop(pair.stack);
		assertEquals(A, pair.value);

		assertEquals(empty(), pair.stack);
	}
}

Isolate pops and pushes through function objects so that they can be manipulated

It gets really weird, but it will become clearer


package model.job.metadata;

import java.util.List;

import org.joda.time.DateTime;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonInclude(Include.NON_NULL)
public class ResourceMetadata {

	public String name;

	@JsonProperty("_id")
	public String resourceId;
	public String description;
	public String url;
	public String filePath;
	public String format;
	public String networks;
	public String qos;
	public String availability;
	public String tags;
	public String classType;
	@JsonIgnore
	public DateTime termDate;
	public Boolean clientCertRequired;
	public Boolean credentialsRequired;
	public Boolean preAuthRequired;
	public String contacts;
	public String method;
	public String requestMimeType;
	public String param;
	@JsonProperty("params")
	public List<String> params;
	public String responseMimeType;
	public String reason;

}

package model.job.metadata;

import java.util.List;

import org.joda.time.DateTime;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonInclude(Include.NON_NULL)
public class ResourceMetadata {

	public String name;

	public String id;
	public String description;
	public String url;
	public String filePath;
	public String format;
	public String networks;
	public String qos;
	public String availability;
	public String tags;
	public String classType;
	@JsonIgnore
	public DateTime termDate;
	public Boolean clientCertRequired;
	public Boolean credentialsRequired;
	public Boolean preAuthRequired;
	public String contacts;
	public String method;
	public String requestMimeType;
	public String param;
	@JsonProperty("params")
	public List<String> params;
	public String responseMimeType;
	public String reason;

}

Change from resourceId to id

Change from resourceId to id


package common.behaviour;

public interface FieldMethods {
    public void makeAMove();
}

package common.behaviour;

import common.domain.Field;

public interface FieldMethods {
    public void makeAMove(Field[] surroundingFields);
}

Change makeAMove signature for different types of field.


package com.jonasgerdes.schauburgr.network.image;

import com.jonasgerdes.schauburgr.model.Movie;

/**
 * Created by jonas on 07.03.2017.
 */

public class SchauburgImageUrlCreator implements ImageUrlCreator {

    private String mBaseUrl;

    public SchauburgImageUrlCreator(String baseUrl) {
        mBaseUrl = baseUrl;
    }

    @Override
    public String getPosterImageUrl(Movie movie) {
        return mBaseUrl + "generated/" + movie.getResourceId() + ".jpg";
    }
}

package com.jonasgerdes.schauburgr.network.image;

import android.util.Base64;

import com.jonasgerdes.schauburgr.model.Movie;

/**
 * Created by jonas on 07.03.2017.
 */

public class SchauburgImageUrlCreator implements ImageUrlCreator {

    private String mBaseUrl;

    public SchauburgImageUrlCreator(String baseUrl) {
        mBaseUrl = baseUrl;
    }

    @Override
    public String getPosterImageUrl(Movie movie) {
        //Encode title as Base64 and append it to url to prevent issue when same image is used for
        //different movie while still allowing image to be cached as long as used for same movie
        byte[] titleBytes = movie.getTitle().getBytes();
        String fingerprint = Base64.encodeToString(titleBytes, Base64.URL_SAFE | Base64.NO_PADDING);
        return mBaseUrl + "generated/" + movie.getResourceId() + ".jpg?f=" + fingerprint;
    }
}

Fix wrong posters beeing displayed

Fix wrong posters beeing displayed


package com.artemzin.qualitymatters.other;

import org.junit.Before;
import org.junit.Test;

import rx.functions.Action0;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;

public class DisposableSubscriptionTest {

    private Action0 disposeAction;
    private DisposableSubscription disposableSubscription;

    @Before
    public void beforeEachTest() {
        disposeAction = mock(Action0.class);
        disposableSubscription = new DisposableSubscription(disposeAction);
    }

    @Test
    public void unsubscribed_shouldReturnFalseByDefault() {
        assertThat(disposableSubscription.isUnsubscribed()).isFalse();
        verifyZeroInteractions(disposeAction);
    }

    @Test
    public void unsubscribe_shouldChangeValueOfIsUsubscribed() {
        disposableSubscription.unsubscribe();
        assertThat(disposableSubscription.isUnsubscribed()).isTrue();
    }

    @Test
    public void unsubscribe_shouldCallDisposableAction() {
        disposableSubscription.unsubscribe();
        verify(disposeAction).call();
    }
}

package com.artemzin.qualitymatters.other;

import org.junit.Before;
import org.junit.Test;

import rx.functions.Action0;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;

public class DisposableSubscriptionTest {

    private Action0 disposeAction;
    private DisposableSubscription disposableSubscription;

    @Before
    public void beforeEachTest() {
        disposeAction = mock(Action0.class);
        disposableSubscription = new DisposableSubscription(disposeAction);
    }

    @Test
    public void unsubscribed_shouldReturnFalseByDefault() {
        assertThat(disposableSubscription.isUnsubscribed()).isFalse();
        verifyZeroInteractions(disposeAction);
    }

    @Test
    public void unsubscribe_shouldChangeValueOfIsUsubscribed() {
        disposableSubscription.unsubscribe();
        assertThat(disposableSubscription.isUnsubscribed()).isTrue();
    }

    @Test
    public void unsubscribe_shouldCallDisposableAction() {
        disposableSubscription.unsubscribe();
        verify(disposeAction).call();
    }

    @Test
    public void unsubscribeTwice_shouldCallDisposableActionOnce() {
        disposableSubscription.unsubscribe();
        disposableSubscription.unsubscribe();
        verify(disposeAction).call();
    }
}

Test double call to DisposableSubscription.unsubscribe()


package de.bmoth.app;

/**
 * Created by jessy on 19.05.17.
 */
public class ReplController {
}

package de.bmoth.app;

import com.microsoft.z3.BoolExpr;
import com.microsoft.z3.Context;
import com.microsoft.z3.Model;
import com.microsoft.z3.Solver;
import de.bmoth.backend.FormulaToZ3Translator;
import de.bmoth.backend.SolutionFinder;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyCode;

import java.net.URL;
import java.util.ResourceBundle;
import java.util.Set;

public class ReplController implements Initializable {

    @FXML
    TextArea replText = new TextArea();

    private Context ctx;
    private Solver s;

    @Override
    public void initialize(URL fxmlFileLocation, ResourceBundle resources) {

        ctx = new Context();
        s = ctx.mkSolver();

        replText.setOnKeyPressed(keyEvent -> {
            if (keyEvent.getCode() == KeyCode.ENTER) {
                String[] predicate = replText.getText().split("\n");
                String solution = processPredicate(predicate[predicate.length-1]);
                replText.appendText(solution);
            }
        });
    }

    private String processPredicate(String predicate) {
        ctx = new Context();
        s = ctx.mkSolver();
        BoolExpr constraint = FormulaToZ3Translator.translatePredicate(predicate, ctx);
        SolutionFinder finder = new SolutionFinder(constraint, s, ctx);
        Set<Model> solutions = finder.findSolutions(1);
        if (solutions.size() == 0) {
            return "\nUNSATISFIABLE";
        } else {
            return "\n" + solutions.toString();
        }
    }
}

Read predicate and find one solution or return UNSATISFIABLE


/*
 * 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.catalina.webresources;

import java.io.File;

import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.WebResourceSet;

public class TestDirResourceSetInternal extends TestDirResourceSet {

    @Override
    public WebResourceRoot getWebResourceRoot() {
        File f = new File("test/");
        TesterWebResourceRoot root = new TesterWebResourceRoot();
        WebResourceSet webResourceSet =
                new DirResourceSet(new TesterWebResourceRoot(), "/",
                        f.getAbsolutePath(), "/webresources/dir1");
        root.setMainResources(webResourceSet);
        return root;
    }
}

/*
 * 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.catalina.webresources;

import java.io.File;

import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.WebResourceSet;

public class TestDirResourceSetInternal extends TestDirResourceSet {

    @Override
    public WebResourceRoot getWebResourceRoot() {
        File f = new File("test/");
        TesterWebResourceRoot root = new TesterWebResourceRoot();
        WebResourceSet webResourceSet =
                new DirResourceSet(root, "/", f.getAbsolutePath(), "/webresources/dir1");
        root.setMainResources(webResourceSet);
        return root;
    }
}

Test should only use a single root

Test should only use a single root

git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1704735 13f79535-47bb-0310-9956-ffa450edef68


package com.boundary.sdk.event;
import org.apache.camel.spring.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EventApplication
{
	private static Logger LOG = LoggerFactory.getLogger(EventApplication.class);

    private Main main;

    public static void main(String[] args) throws Exception
    {
    	EventApplication app = new EventApplication();
        app.boot();
    }

    private void boot() throws Exception
    {
        // create a Main instance
        main = new Main();

        // enable hangup support so you can press ctrl + c to terminate the JVM
        main.enableHangupSupport();

        // Get spring definition of the routes to start
        main.setApplicationContextUri("META-INF/event-application.xml");

        // run until you terminate the JVM
        LOG.info("Starting Camel. Use ctrl + c to terminate the JVM.\n");
        main.run();
    }
}

package com.boundary.sdk.event;
import org.apache.camel.spring.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EventApplication
{
	private static Logger LOG = LoggerFactory.getLogger(EventApplication.class);

    private Main main;

    public static void main(String[] args) throws Exception
    {
    	EventApplication app = new EventApplication();
        app.boot();
    }

    private void boot() throws Exception
    {
        // create a Main instance
        main = new Main();

        // enable hangup support so you can press ctrl + c to terminate the JVM
        main.enableHangupSupport();

        // Get spring definition of the routes to start
        main.setApplicationContextUri(System.getProperty("boundary.application.context.uri"));

        // run until you terminate the JVM
        LOG.info("Starting Camel. Use ctrl + c to terminate the JVM.\n");
        main.run();
    }
}

Modify main to pass in application context uri that points to the sprint file via a property


package me.deftware.client.framework.MC_OAuth;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class StaticOAuth {

	private static String token = "";

	static {
		Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				token = "";
			}
		}, 0, 5, TimeUnit.MINUTES);
	}

	/**
	 * Will always return a token
	 *
	 * @param callback
	 */
	public static void getToken(OAuthCodeHandler callback) {
		if (token.equals("")) {
			OAuth.oAuth((success, code, time) -> {
				token = code;
				callback.callback(token);
			});
		} else {
			callback.callback(token);
		}
	}

	@FunctionalInterface
	public static interface OAuthCodeHandler {

		public void callback(String code);

	}

}

package me.deftware.client.framework.MC_OAuth;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class StaticOAuth {

	private static String token = "";

	static {
		Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				token = "";
			}
		}, 0, 2, TimeUnit.MINUTES);
	}

	/**
	 * Will always return a token
	 *
	 * @param callback
	 */
	public static void getToken(OAuthCodeHandler callback) {
		if (token.equals("")) {
			OAuth.oAuth((success, code, time) -> {
				token = code;
				callback.callback(token);
			});
		} else {
			callback.callback(token);
		}
	}

	@FunctionalInterface
	public static interface OAuthCodeHandler {

		public void callback(String code);

	}

}

Reduce internal token expiration time

Reduce internal token expiration time


package edu.berkeley.eecs.cfc_tracker;

public final class Constants {
	public static String LONGITUDE = "longitude";
	public static String LATITUDE = "latitude";
	public static String ACCELERATOR_X = "ax";
	public static String ACCELERATOR_Y = "ay";
	public static String ACCELERATOR_Z = "az";
	public static String BATTERY_LEVEL = "battery_level";
	public static String ACTIVITY_TYPE = "activity_type";
	public static String ACTIVITY_CONFIDENCE = "activity_confidence";

	public static int TRIP_EDGE_THRESHOLD = 100; // meters

    public static final int MILLISECONDS = 1000; // used to make constants like 30 * MILLISECONDS
	public static final int THIRTY_SECONDS = 30 * MILLISECONDS; // 30 secs, keep it similar to GPS
	public static final int TWO_SECONDS = 2 * MILLISECONDS; // 2 secs, similar to Zheng 2010 paper
	public static final int SIXTY_SECONDS = 60 * MILLISECONDS; // 1 min, similar to smalldata mobility
    public static final long NANO2MS = 1000000;

    public static String[] sensors = {LONGITUDE,
									  LATITUDE,
									  ACCELERATOR_X,
									  ACCELERATOR_Y,
									  ACCELERATOR_Z,
									  BATTERY_LEVEL,
									  ACTIVITY_TYPE,
									  ACTIVITY_CONFIDENCE};
}

package edu.berkeley.eecs.cfc_tracker;

public final class Constants {
	public static String LONGITUDE = "longitude";
	public static String LATITUDE = "latitude";
	public static String ACCELERATOR_X = "ax";
	public static String ACCELERATOR_Y = "ay";
	public static String ACCELERATOR_Z = "az";
	public static String BATTERY_LEVEL = "battery_level";
	public static String ACTIVITY_TYPE = "activity_type";
	public static String ACTIVITY_CONFIDENCE = "activity_confidence";

	public static int TRIP_EDGE_THRESHOLD = 100; // meters

    public static final int MILLISECONDS = 1000; // used to make constants like 30 * MILLISECONDS
	public static final int THIRTY_SECONDS = 30 * MILLISECONDS; // 30 secs, keep it similar to GPS
	public static final int TEN_SECONDS = 10 * MILLISECONDS; // 10 secs, similar to sensys paper
	public static final int TWO_SECONDS = 2 * MILLISECONDS; // 2 secs, similar to Zheng 2010 paper
	public static final int SIXTY_SECONDS = 60 * MILLISECONDS; // 1 min, similar to smalldata mobility
    public static final long NANO2MS = 1000000;

    public static String[] sensors = {LONGITUDE,
									  LATITUDE,
									  ACCELERATOR_X,
									  ACCELERATOR_Y,
									  ACCELERATOR_Z,
									  BATTERY_LEVEL,
									  ACTIVITY_TYPE,
									  ACTIVITY_CONFIDENCE};
}

Add a new constant for ten minutes, so that we can use it in the config


package won.matcher.service.common.event;

import won.matcher.service.common.mailbox.PriorityAtomEventMailbox;

/**
 * Indicates how this event was generated and associates that cause with a fixed
 * priority. Used in the {@link PriorityAtomEventMailbox}; lower priority values
 * means more important.
 */
public enum Cause {
    PUSHED(0), // we received a push about this Atom from a WoN node. React fast!
    MATCHED(3), // we found this Atom as a match to another one. React timely.
    SCHEDULED_FOR_REMATCH(5), // we decided it's time to re-match for this Atom. Should be handled before
                              // events generated in crawling
    CRAWLED(10), // we found this Atom during crawling. Handle when we have nothing else to do
    ;
    private int priority;

    private Cause(int prio) {
        this.priority = prio;
    }

    public int getPriority() {
        return priority;
    }

    public static int LOWEST_PRIORTY = Integer.MAX_VALUE;
}

package won.matcher.service.common.event;

import won.matcher.service.common.mailbox.PriorityAtomEventMailbox;

/**
 * Indicates how this event was generated and associates that cause with a fixed
 * priority. Used in the {@link PriorityAtomEventMailbox}; lower priority values
 * means more important.
 */
public enum Cause {
    PUSHED(0), // we received a push about this Atom from a WoN node. React fast!
    MATCHED(3), // we found this Atom as a match to another one. React timely.
    SCHEDULED_FOR_REMATCH(5), // we decided it's time to re-match for this Atom. Should be handled before
                              // events generated in crawling
    CRAWLED(10), // we found this Atom during crawling. Handle when we have nothing else to do
    MATCHED_OFFLINE(15), // this cause should only be used for HintEvents generated by offline matchers,
                         // (not for AtomEvents).
    ;
    private int priority;

    private Cause(int prio) {
        this.priority = prio;
    }

    public int getPriority() {
        return priority;
    }

    public static int LOWEST_PRIORTY = Integer.MAX_VALUE;
}

Add constant for hints generated during offline matching


package com.example.assignment1;

public class TravelExpense {

}

package com.example.assignment1;

import java.util.Calendar;
import java.util.Currency;
import java.util.GregorianCalendar;

public class TravelExpense {
    private Calendar date;
    private String description;
    private Category category;
    private float amount;
    private Currency currency;

    enum Category {
        AIR_FAIR, GROUND_TRANSPORT, VEHICLE_RENTAL, FUEL, PARKING, REGISTARTION, ACCOMMODATION, MEAL, OTHER
    };

    TravelExpense() {
        date = new GregorianCalendar();
        description = "";
        category = Category.OTHER;
        amount = 0;
        currency = CurrencyHandler.getLocalDefaultCurrency();
    }

    public Calendar getDate() {
        return date;
    }

    public String getDescription() {
        return description;
    }

    public Category getCategory() {
        return category;
    }

    public float getAmount() {
        return amount;
    }

    public Currency getCurrency() {
        return currency;
    }

}

Set up the expense class with all its needed members


package mjc.types;

/**
 * UnsupportedType represents an unsupported type.
 *
 * There are only two static instances of this type, one for void and one for
 * String[]. These types appear as the return type and parameter type of the main
 * method.
 *
 * Unsupported types are incompatible with all other types, including itself,
 * effectively preventing the programmer from calling the main method or
 * referencing its parameter without getting a type error.
 */
public class UnsupportedType extends Type {
    public final static Type Void = new UnsupportedType("void");
    public final static Type StringArray = new UnsupportedType("String[]");

    private final String name;

    private UnsupportedType(final String name) {
        this.name = name;
    }

    @Override
    public String getName() {
        return name;
    }
}

package mjc.types;

/**
 * UnsupportedType represents an unsupported type.
 *
 * There are only two static instances of this type, one for void and one for
 * String[]. These types appear as the return type and parameter type of the main
 * method.
 *
 * Unsupported types are incompatible with all other types, including itself,
 * effectively preventing the programmer from calling the main method or
 * referencing its parameter without getting a type error.
 */
public class UnsupportedType extends Type {
    public final static Type Void = new UnsupportedType("void");
    public final static Type StringArray = new UnsupportedType("String[]");

    private final String name;

    private UnsupportedType(final String name) {
        this.name = name;
    }

    @Override
    public String getName() {
        return name + " (unsupported)";
    }
}

Add " (unsupported)" in toString().

Add " (unsupported)" in toString().


package org.apereo.cas.web.report;

import org.springframework.cloud.bus.BusProperties;
import org.springframework.cloud.config.server.config.ConfigServerProperties;

import java.util.Map;

/**
 * This is {@link ControllerUtils}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
public final class ControllerUtils {
    private ControllerUtils() {
    }

    /**
     * Configure model map for config server cloud bus endpoints.
     *
     * @param busProperties          the bus properties
     * @param configServerProperties the config server properties
     * @param path                   the path
     * @param model                  the model
     */
    public static void configureModelMapForConfigServerCloudBusEndpoints(final BusProperties busProperties,
                                                                         final ConfigServerProperties configServerProperties,
                                                                         final String path,
                                                                         final Map model) {
        if (busProperties != null && busProperties.isEnabled()) {
            model.put("refreshEndpoint", path + configServerProperties.getPrefix() + "/cas/bus/refresh");
            model.put("refreshMethod", "GET");
        } else {
            model.put("refreshEndpoint", path + "/status/refresh");
            model.put("refreshMethod", "POST");
        }
    }
}

package org.apereo.cas.web.report;

import org.springframework.cloud.bus.BusProperties;
import org.springframework.cloud.config.server.config.ConfigServerProperties;

import java.util.Map;

/**
 * This is {@link ControllerUtils}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
final class ControllerUtils {
    private ControllerUtils() {
    }

    /**
     * Configure model map for config server cloud bus endpoints.
     *
     * @param busProperties          the bus properties
     * @param configServerProperties the config server properties
     * @param path                   the path
     * @param model                  the model
     */
    public static void configureModelMapForConfigServerCloudBusEndpoints(final BusProperties busProperties,
                                                                         final ConfigServerProperties configServerProperties,
                                                                         final String path,
                                                                         final Map model) {
        if (busProperties != null && busProperties.isEnabled()) {
            model.put("refreshEndpoint", path + configServerProperties.getPrefix() + "/cas/bus/refresh");
            model.put("refreshMethod", "GET");
        } else {
            model.put("refreshEndpoint", path + "/status/refresh");
            model.put("refreshMethod", "POST");
        }
    }
}

Clean up duplicate code in controllers

Clean up duplicate code in controllers


package manage.validations;

import org.everit.json.schema.FormatValidator;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Optional;

public class XMLFormatValidator implements FormatValidator {

    @Override
    public Optional<String> validate(String subject) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);
        try {
            factory.newDocumentBuilder().parse(new ByteArrayInputStream(subject.getBytes()));
        } catch (ParserConfigurationException | SAXException | IOException e) {
            return Optional.of(e.toString());
        }
        return Optional.empty();
    }

    @Override
    public String formatName() {
        return "xml";
    }

}

package manage.validations;

import org.everit.json.schema.FormatValidator;
import org.xml.sax.SAXException;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Optional;

public class XMLFormatValidator implements FormatValidator {

    private static final String FEATURE_DISABLE_DOCTYPE = "http://apache.org/xml/features/disallow-doctype-decl";

    @Override
    public Optional<String> validate(String subject) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);
        try {
            factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            factory.setFeature(FEATURE_DISABLE_DOCTYPE, true);
            factory.newDocumentBuilder().parse(new ByteArrayInputStream(subject.getBytes()));
        } catch (ParserConfigurationException | SAXException | IOException e) {
            return Optional.of(e.toString());
        }
        return Optional.empty();
    }

    @Override
    public String formatName() {
        return "xml";
    }

}

Resolve XXE vulnerability in XML validation


package com.netflix.discovery.providers;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.netflix.discovery.DefaultEurekaClientConfig;
import com.netflix.discovery.EurekaNamespace;

/**
 * This provider is necessary because the namespace is optional
 * @author elandau
 */
public class DefaultEurekaClientConfigProvider implements Provider<DefaultEurekaClientConfig> {

    @Inject(optional=true)
    @EurekaNamespace
    private String namespace;

    @Override
    public DefaultEurekaClientConfig get() {
        if (namespace == null)
            return new DefaultEurekaClientConfig();
        else
            return new DefaultEurekaClientConfig(namespace);
    }
}

package com.netflix.discovery.providers;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.netflix.discovery.DefaultEurekaClientConfig;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.EurekaNamespace;

/**
 * This provider is necessary because the namespace is optional
 * @author elandau
 */
public class DefaultEurekaClientConfigProvider implements Provider<EurekaClientConfig> {

    @Inject(optional=true)
    @EurekaNamespace
    private String namespace;

    @Override
    public EurekaClientConfig get() {
        if (namespace == null)
            return new DefaultEurekaClientConfig();
        else
            return new DefaultEurekaClientConfig(namespace);
    }
}

Fix wrong interface being provided

Fix wrong interface being provided


package com.provinggrounds.match3things.game;

/*
 * Represents a game grid. Contains a rectangular grid of numbers.
 * All numbers must be positive integers greater than 0, between 1 and numObjectTypes(both inclusive)
 */
public class Grid {
    int width;
    int height;
    /*
     * Represents number of unique object types
     */
    int numObjectTypes;
    int[][] gameGrid;

    /*
     * Width and height must always be provided to Grid - should not be constructed without initializing/passing in those values
     */
    @SuppressWarnings("unused")
    private Grid() {

    }

    Grid(int width, int height) {
	this.width = width;
	this.height = height;

	initGameGridArray();
    }

    /*
     * Creates grid, allocates storage
     */
    private void initGameGridArray() {
	gameGrid = new int[width][height];
    }

    /*
     * Initialize/fill game grid with random objects
     */
    private void fillGameGrid() {

    }
}

package com.provinggrounds.match3things.game;

/*
 * Represents a game grid. Contains a rectangular grid of numbers.
 * All numbers must be positive integers greater than 0, between 1 and numObjectTypes(both inclusive)
 */
public class Grid {
    int width;
    int height;
    /*
     * Represents number of unique object types
     */
    int numObjectTypes;
    int[][] gameGrid;

    /*
     * Width and height must always be provided to Grid - should not be constructed without initializing/passing in those values
     */
    @SuppressWarnings("unused")
    private Grid() {

    }

    Grid(int width, int height, int numObjectTypes) {
	this.width = width;
	this.height = height;
	this.numObjectTypes = numObjectTypes;

	initGameGridArray();
    }

    /*
     * Creates grid, allocates storage
     */
    private void initGameGridArray() {
	gameGrid = new int[width][height];
    }

    /*
     * Initialize/fill game grid with random objects
     */
    private void fillGameGrid() {

    }
}

Groid: Add numObjectTypes to constructor parameters


package info.u_team.u_team_test;

import net.minecraftforge.fml.common.Mod;

@Mod(TestMod.MODID)
public class TestMod {

	public static final String MODID = "uteamtest";

	public TestMod() {
		System.out.println("--------------------------------------- LOADING TEST MOD ---------------------------------------");
	}
}

package info.u_team.u_team_test;

import info.u_team.u_team_core.util.verify.JarSignVerifier;
import net.minecraftforge.fml.common.Mod;

@Mod(TestMod.MODID)
public class TestMod {

	public static final String MODID = "uteamtest";

	public TestMod() {
		JarSignVerifier.checkSigned(MODID);
		System.out.println("--------------------------------------- LOADING TEST MOD ---------------------------------------");
	}
}

Check signed jar on testmod

Check signed jar on testmod


/**
 * Copyright 2011 The PlayN 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 playn.android;

import android.graphics.Typeface;

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

import playn.core.AbstractFont;

class AndroidFont extends AbstractFont {

  public final Typeface typeface;

  public AndroidFont(String name, Style style, float size) {
    super(name, style, size);
    this.typeface = Typeface.create(name, TO_ANDROID_STYLE.get(style));
  }

  protected static final Map<Style,Integer> TO_ANDROID_STYLE = new HashMap<Style,Integer>();
  static {
    TO_ANDROID_STYLE.put(Style.PLAIN,       Typeface.NORMAL);
    TO_ANDROID_STYLE.put(Style.BOLD,        Typeface.BOLD);
    TO_ANDROID_STYLE.put(Style.ITALIC,      Typeface.ITALIC);
    TO_ANDROID_STYLE.put(Style.BOLD_ITALIC, Typeface.BOLD_ITALIC);
  }
}

/**
 * Copyright 2011 The PlayN 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 playn.android;

import android.graphics.Typeface;

import java.util.EnumMap;
import java.util.Map;

import playn.core.AbstractFont;

class AndroidFont extends AbstractFont {

  public final Typeface typeface;

  public AndroidFont(String name, Style style, float size) {
    super(name, style, size);
    this.typeface = Typeface.create(name, TO_ANDROID_STYLE.get(style));
  }

  protected static final Map<Style,Integer> TO_ANDROID_STYLE =
    new EnumMap<Style,Integer>(Style.class);
  static {
    TO_ANDROID_STYLE.put(Style.PLAIN,       Typeface.NORMAL);
    TO_ANDROID_STYLE.put(Style.BOLD,        Typeface.BOLD);
    TO_ANDROID_STYLE.put(Style.ITALIC,      Typeface.ITALIC);
    TO_ANDROID_STYLE.put(Style.BOLD_ITALIC, Typeface.BOLD_ITALIC);
  }
}

Use an EnumMap rather than a HashMap.

Use an EnumMap rather than a HashMap.


package devopsdistilled.operp.client.items.exceptions;

public class ProductBrandPairExistsException extends Exception {

	private static final long serialVersionUID = -6474661245907152963L;

}

package devopsdistilled.operp.client.items.exceptions;

public class ProductBrandPairExistsException extends Exception {

	public ProductBrandPairExistsException(String message) {
		super(message);
	}

	private static final long serialVersionUID = -6474661245907152963L;

}

Change to Exception with message

Change to Exception with message

OPEN - task 66: Update Item functionalities implementation
http://github.com/DevOpsDistilled/OpERP/issues/issue/66


package com.google.sps.data;

/** User representing a location **/
public class User {

  private MapLocation geolocation;
  private int zipCode;

  /** Creates a user with a geolocation
  * @param geolocation lat/lng coordinate
  * @return User with geolocation
  **/
  public User(MapLocation geolocation) {
    this.geolocation = geolocation;
  }

  /** Creates a user with a zipcode
  * @param zipcode
  * @return User with zipCode
  **/
  public User(int zipCode) {
    this.zipCode = zipCode;
  }

  public MapLocation getGeolocation() {
    return geolocation;
  }

  public int getZipCode() {
    return zipCode;
  }
}

package com.google.sps.data;

/** User representing a location **/
public class User {

  private MapLocation geolocation;

  /** Creates a user with a geolocation
  * @param geolocation lat/lng coordinate
  * @return User with geolocation
  **/
  public User(MapLocation geolocation) {
    this.geolocation = geolocation;
  }

  /** Creates a user with a zipcode
  * @param zipcode
  * @return User with zipCode
  **/
  public User(int zipCode) {
    // TODO: Convert zipcode to MapLocation
  }

  public MapLocation getGeolocation() {
    return geolocation;
  }
}

Change to convert to geolocation

Change to convert to geolocation


package model.job.type;

import model.job.PiazzaJobType;
import model.job.metadata.ResourceMetadata;

public class IngestJob implements PiazzaJobType {
	public final String type = "ingest";
	public ResourceMetadata data;

	public IngestJob() {

	}

	public String getType() {
		return type;
	}
}

package model.job.type;

import model.job.PiazzaJobType;
import model.job.metadata.ResourceMetadata;

public class IngestJob implements PiazzaJobType {
	public final String type = "ingest";
	public ResourceMetadata data;

	public IngestJob() {

	}

	public String getType() {
		return type;
	}

	public ResourceMetadata getMetadata() {
		return data;
	}
}

Add appropriate accessor for Ingest Jobs


package org.folio.okapi.util;

import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import java.util.LinkedList;
import java.util.List;
import org.folio.okapi.common.ErrorType;
import org.folio.okapi.common.ExtendedAsyncResult;
import org.folio.okapi.common.Failure;
import org.folio.okapi.common.Success;

public class CompList<T> {

  List<Future> futures = new LinkedList<>();
  ErrorType errorType;

  public CompList(ErrorType type) {
    errorType = type;
  }

  public void add(Future f) {
    futures.add(f);
  }

  public <T> void all(T l, Handler<ExtendedAsyncResult<T>> fut) {
    CompositeFuture.all(futures).setHandler(res2 -> {
      if (res2.failed()) {
        fut.handle(new Failure<>(errorType, res2.cause()));
      } else {
        fut.handle(new Success<>(l));
      }
    });
  }

  public <T> void all(Handler<ExtendedAsyncResult<Void>> fut) {
    CompositeFuture.all(futures).setHandler(res2 -> {
      if (res2.failed()) {
        fut.handle(new Failure<>(errorType, res2.cause()));
      } else {
        fut.handle(new Success<>());
      }
    });
  }

}

package org.folio.okapi.util;

import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import java.util.LinkedList;
import java.util.List;
import org.folio.okapi.common.ErrorType;
import org.folio.okapi.common.ExtendedAsyncResult;
import org.folio.okapi.common.Failure;
import org.folio.okapi.common.Success;

public class CompList<T> {

  List<Future> futures = new LinkedList<>();
  ErrorType errorType;

  public CompList(ErrorType type) {
    errorType = type;
  }

  public void add(Future f) {
    futures.add(f);
  }

  public void all(T l, Handler<ExtendedAsyncResult<T>> fut) {
    CompositeFuture.all(futures).setHandler(res2 -> {
      if (res2.failed()) {
        fut.handle(new Failure<>(errorType, res2.cause()));
      } else {
        fut.handle(new Success<>(l));
      }
    });
  }

  public void all(Handler<ExtendedAsyncResult<Void>> fut) {
    CompositeFuture.all(futures).setHandler(res2 -> {
      if (res2.failed()) {
        fut.handle(new Failure<>(errorType, res2.cause()));
      } else {
        fut.handle(new Success<>());
      }
    });
  }

}

Remove redundant type in declaration

Remove redundant type in declaration


package com.pyknic.servicekit.encode;

import com.google.gson.Gson;
import com.pyknic.servicekit.Service;

import java.util.Map;

/**
 * An encoder that parses the result of a service to the json format.
 *

 * This class should not be instantiated directly but passed as a class
 * reference to the {@link Service} annotation to be instantiated
 * through reflection.
 *

 * This class is stateless and instances can therefore safely be shared.
 *
 * @author Emil Forslund
 */
public final class JsonEncoder implements Encoder {

    private final static String MIME = "application/x-json";

    @Override
    public <T> String apply(Map<String, Object> params, T response) {
        final Gson gson = new Gson();
        return gson.toJson(response);
    }

    @Override
    public String getMimeType() {
        return MIME;
    }

    public JsonEncoder() {}
}

package com.pyknic.servicekit.encode;

import com.google.gson.Gson;
import com.pyknic.servicekit.Service;

import java.util.Map;

/**
 * An encoder that parses the result of a service to the json format.
 *

 * This class should not be instantiated directly but passed as a class
 * reference to the {@link Service} annotation to be instantiated
 * through reflection.
 *

 * This class is stateless and instances can therefore safely be shared.
 *
 * @author Emil Forslund
 */
public final class JsonEncoder implements Encoder {

    private final static String MIME = "application/json";

    @Override
    public <T> String apply(Map<String, Object> params, T response) {
        final Gson gson = new Gson();
        return gson.toJson(response);
    }

    @Override
    public String getMimeType() {
        return MIME;
    }

    public JsonEncoder() {}
}

Change default encoding for json

Change default encoding for json


package dmillerw.lore.core.proxy;

import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import dmillerw.lore.LoreExpansion;
import dmillerw.lore.client.handler.ClientTickHandler;
import dmillerw.lore.core.handler.KeyHandler;
import net.minecraft.world.World;
import net.minecraftforge.common.config.Configuration;

import java.io.File;

/**
 * @author dmillerw
 */
public class ClientProxy extends CommonProxy {

	@Override
	public void preInit(FMLPreInitializationEvent event) {
		Configuration config = new Configuration(new File(LoreExpansion.configFolder, "config.cfg"));
		config.load();
		boolean preload = config.get(Configuration.CATEGORY_GENERAL, "preload", true, "Preload all lore sounds when the game starts. Will induce additional startup lag, but prevents lag during game.").getBoolean(true);
		config.save();

		FMLCommonHandler.instance().bus().register(KeyHandler.INSTANCE);
		if (preload) {
			FMLCommonHandler.instance().bus().register(new ClientTickHandler());
		}
	}

	@Override
	public World getClientWorld() {
		return FMLClientHandler.instance().getClient().theWorld;
	}

}

package dmillerw.lore.core.proxy;

import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import dmillerw.lore.LoreExpansion;
import dmillerw.lore.client.handler.ClientTickHandler;
import dmillerw.lore.core.handler.KeyHandler;
import net.minecraft.world.World;
import net.minecraftforge.common.config.Configuration;

import java.io.File;

/**
 * @author dmillerw
 */
public class ClientProxy extends CommonProxy {

	@Override
	public void preInit(FMLPreInitializationEvent event) {
		Configuration config = new Configuration(new File(LoreExpansion.configFolder, "config.cfg"));
		config.load();
		boolean preload = config.get(Configuration.CATEGORY_GENERAL, "preload", false, "Preload all lore sounds when the game starts. Will induce additional startup lag, but prevents lag during game.").getBoolean(false);
		config.save();

		FMLCommonHandler.instance().bus().register(KeyHandler.INSTANCE);
		if (preload) {
			FMLCommonHandler.instance().bus().register(new ClientTickHandler());
		}
	}

	@Override
	public World getClientWorld() {
		return FMLClientHandler.instance().getClient().theWorld;
	}

}

Set preload default to false

Set preload default to false


package yanagishima.provider;

import me.geso.tinyorm.TinyORM;

import javax.inject.Inject;
import javax.inject.Provider;
import java.sql.Connection;

public class TinyORMProvider implements Provider<TinyORM> {

	@Inject
	private Connection connection;

	@Override
	public TinyORM get() {
		TinyORM tinyORM =  new TinyORM(connection);
		tinyORM.setQueryTimeout(10);
		return tinyORM;
	}
}

package yanagishima.provider;

import me.geso.tinyorm.TinyORM;

import javax.inject.Inject;
import javax.inject.Provider;
import java.sql.Connection;

public class TinyORMProvider implements Provider<TinyORM> {

	@Inject
	private Connection connection;

	@Override
	public TinyORM get() {
		TinyORM tinyORM =  new TinyORM(connection);
		tinyORM.setQueryTimeout(30);
		return tinyORM;
	}
}

Increase timeout to avoid SQLITE_BUSY

Increase timeout to avoid SQLITE_BUSY


package hello.controllers;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import hello.configuration.Application;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@AutoConfigureMockMvc
public class RootControllerTest {

	@Autowired
	private MockMvc mvc;

	@Test
	public void getRoot() throws Exception {
		mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk());
	}

}

package hello.controllers;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import hello.configuration.Application;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@AutoConfigureMockMvc
public class RootControllerTest {

	@Autowired
	private MockMvc mvc;

	@Test
	public void getRoot() throws Exception {
		mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk());
	}

	@Test
	public void getJsonRoot() throws Exception {
		mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
				.andExpect(status().isNotFound());
	}

}

Add a test to show JSON at the root.

Add a test to show JSON at the root.


package org.pentaho.di.run.sortedmerge;

import junit.framework.TestCase;

import org.pentaho.di.core.Result;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.run.AllRunTests;
import org.pentaho.di.run.TimedTransRunner;

public class RunSortedMerge extends TestCase
{
    public void test_SORTED_MERGE_00()
    {
        System.out.println();
        System.out.println("SORTED MERGE");
        System.out.println("==================");
    }

    public void test_SORTED_MERGE_01_SIMPLE() throws Exception
    {
        TimedTransRunner timedTransRunner = new TimedTransRunner(
                "test/org/pentaho/di/run/sortedmerge/SortedMergeSimple.ktr",
                LogWriter.LOG_LEVEL_ERROR,
                AllRunTests.getOldTargetDatabase(),
                AllRunTests.getNewTargetDatabase(),
                1000000
            );
        timedTransRunner.runOldAndNew();

        be.ibridge.kettle.core.Result oldResult = timedTransRunner.getOldResult();
        assertTrue(oldResult.getNrErrors()==0);

        Result newResult = timedTransRunner.getNewResult();
        assertTrue(newResult.getNrErrors()==0);
    }
}

Update of sorted merge step test case

Update of sorted merge step test case

git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@4016 5fb7f6ec-07c1-534a-b4ca-9155e429e800


/*
 * Copyright (C) 2004 - 2014 Brian McCallister
 *
 * 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.skife.jdbi.v2;

import org.skife.jdbi.v2.tweak.Argument;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;

/**
 *
 */
class ObjectArgument implements Argument
{
    private final Object value;

    ObjectArgument(Object value)
    {
        this.value = value;
    }

    @Override
    public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException
    {
        if (value != null) {
            statement.setObject(position, value);
        }
        else {
            statement.setNull(position, Types.OTHER);
        }
    }

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

/*
 * Copyright (C) 2004 - 2014 Brian McCallister
 *
 * 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.skife.jdbi.v2;

import org.skife.jdbi.v2.tweak.Argument;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;

/**
 *
 */
class ObjectArgument implements Argument
{
    private final Object value;

    ObjectArgument(Object value)
    {
        this.value = value;
    }

    @Override
    public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException
    {
        if (value != null) {
            statement.setObject(position, value);
        }
        else {
            statement.setNull(position, Types.NULL);
        }
    }

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

Use Types.NULL for null objects

Use Types.NULL for null objects


package ethanjones.modularworld.networking.server;

import com.badlogic.gdx.net.Socket;
import ethanjones.modularworld.core.logging.Log;
import ethanjones.modularworld.networking.common.Networking;
import ethanjones.modularworld.networking.common.packet.Packet;
import ethanjones.modularworld.networking.common.socket.SocketMonitor;

import java.util.HashMap;

public class ServerNetworking extends Networking {

  private HashMap<Socket, SocketMonitor> sockets;
  private SocketMonitorServer serverSocketMonitor;

  public ServerNetworking(int port) {
    super(port);
  }

  public void start() {
    Log.info("Starting Server Networking");
    sockets = new HashMap<Socket, SocketMonitor>();
    serverSocketMonitor = new SocketMonitorServer(port);
    serverSocketMonitor.start();
  }

  @Override
  public void stop() {
    Log.info("Stopping Server Networking");
    serverSocketMonitor.dispose();
    for (SocketMonitor socketMonitor : sockets.values()) {
      socketMonitor.dispose();
    }
  }

  protected synchronized void accepted(Socket socket) {
    sockets.put(socket, new SocketMonitor(socket, this));
    Log.info("Successfully connected to " + socket.getRemoteAddress());
  }

  @Override
  public void received(Packet packet, SocketMonitor socketMonitor) {

  }

  @Override
  public void disconnected(SocketMonitor socketMonitor, Exception e) {
    super.disconnected(socketMonitor, e);
    sockets.remove(socketMonitor.getSocket());
  }
}

package ethanjones.modularworld.networking.server;

import com.badlogic.gdx.net.Socket;
import com.badlogic.gdx.utils.Array;
import ethanjones.modularworld.core.logging.Log;
import ethanjones.modularworld.networking.common.Networking;
import ethanjones.modularworld.networking.common.packet.Packet;
import ethanjones.modularworld.networking.common.socket.SocketMonitor;

public class ServerNetworking extends Networking {

  private Array<SocketMonitor> sockets;
  private SocketMonitorServer serverSocketMonitor;

  public ServerNetworking(int port) {
    super(port);
  }

  public void start() {
    Log.info("Starting Server Networking");
    sockets = new Array<SocketMonitor>();
    serverSocketMonitor = new SocketMonitorServer(port);
    serverSocketMonitor.start();
  }

  @Override
  public void stop() {
    Log.info("Stopping Server Networking");
    serverSocketMonitor.dispose();
    for (SocketMonitor socketMonitor : sockets) {
      socketMonitor.dispose();
    }
  }

  protected synchronized void accepted(Socket socket) {
    sockets.add(new SocketMonitor(socket, this));
    Log.info("Successfully connected to " + socket.getRemoteAddress());
  }

  @Override
  public void received(Packet packet, SocketMonitor socketMonitor) {

  }

  @Override
  public void disconnected(SocketMonitor socketMonitor, Exception e) {
    super.disconnected(socketMonitor, e);
    sockets.removeValue(socketMonitor, true);
  }
}

Use array instead of hashmap in Server Networking


package me.devsaki.hentoid.parsers;

import android.webkit.URLUtil;

import java.util.List;

import me.devsaki.hentoid.database.domains.Content;
import me.devsaki.hentoid.database.domains.ImageFile;
import timber.log.Timber;

public abstract class BaseParser implements ImageListParser {

    private int currentStep;
    private int maxSteps;

    protected abstract List<String> parseImages(Content content) throws Exception;

    public List<ImageFile> parseImageList(Content content) throws Exception {
        String readerUrl = content.getReaderUrl();

        if (!URLUtil.isValidUrl(readerUrl)) {
            throw new Exception("Invalid gallery URL : " + readerUrl);
        }
        Timber.d("Gallery URL: %s", readerUrl);

        List<String> imgUrls = parseImages(content);
        List<ImageFile> images = ParseHelper.urlsToImageFiles(imgUrls);

        Timber.d("%s", images);

        return images;
    }

    void progressStart(int maxSteps) {
        currentStep = 0;
        this.maxSteps = maxSteps;
        ParseHelper.signalProgress(currentStep, maxSteps);
    }

    void progressPlus() {
        ParseHelper.signalProgress(++currentStep, maxSteps);
    }

    void progressComplete() {
        ParseHelper.signalProgress(maxSteps, maxSteps);
    }
}

package me.devsaki.hentoid.parsers;

import android.webkit.URLUtil;

import java.util.List;

import me.devsaki.hentoid.database.domains.Content;
import me.devsaki.hentoid.database.domains.ImageFile;
import timber.log.Timber;

public abstract class BaseParser implements ImageListParser {

    private int currentStep;
    private int maxSteps;

    protected abstract List<String> parseImages(Content content) throws Exception;

    public List<ImageFile> parseImageList(Content content) throws Exception {
        String readerUrl = content.getReaderUrl();

        if (!URLUtil.isValidUrl(readerUrl))
            throw new IllegalArgumentException("Invalid gallery URL : " + readerUrl);

        Timber.d("Gallery URL: %s", readerUrl);

        List<String> imgUrls = parseImages(content);
        List<ImageFile> images = ParseHelper.urlsToImageFiles(imgUrls);

        Timber.d("%s", images);

        return images;
    }

    void progressStart(int maxSteps) {
        currentStep = 0;
        this.maxSteps = maxSteps;
        ParseHelper.signalProgress(currentStep, maxSteps);
    }

    void progressPlus() {
        ParseHelper.signalProgress(++currentStep, maxSteps);
    }

    void progressComplete() {
        ParseHelper.signalProgress(maxSteps, maxSteps);
    }
}

Throw a specific exception instead of a generic one


package me.jacobcrofts.simplestructureloader.commands;

import java.io.IOException;

import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.json.simple.parser.ParseException;

import me.jacobcrofts.simplestructureloader.api.StructureAPI;
import me.jacobcrofts.simplestructureloader.util.Selection;

public class CmdPasteStructure implements CommandExecutor {

	@Override
	public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {

		if (sender instanceof Player) {
			Selection selection;
			try {
				selection = new Selection(StructureAPI.readFromFile("plugins/structures/" + args[0] + ".json"));
				StructureAPI.placeStructure(selection, ((Player) sender).getLocation());
			} catch (IOException | ParseException e) {
				e.printStackTrace();
			}
			return true;
		}

		return false;
	}

}

package me.jacobcrofts.simplestructureloader.commands;

import java.io.IOException;

import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.json.simple.parser.ParseException;

import me.jacobcrofts.simplestructureloader.api.StructureAPI;
import me.jacobcrofts.simplestructureloader.util.Selection;

public class CmdPasteStructure implements CommandExecutor {

	@Override
	public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {

		if (sender instanceof Player) {
			Player player = (Player) sender;
			if (player.getGameMode() == GameMode.CREATIVE && player.isOp()) {
				Selection selection;
				try {
					selection = new Selection(StructureAPI.readFromFile("plugins/structures/" + args[0] + ".json"));
					StructureAPI.placeStructure(selection, player.getLocation());
				} catch (IOException | ParseException e) {
					e.printStackTrace();
				}
			} else {
				player.sendMessage(ChatColor.RED + "You do not have permission to execute this command.");
			}
			return true;
		} else {
			sender.sendMessage("Only players may perform this command.");
		}

		return false;
	}

}

Add feature: error handling for paste command


/*
 * Copyright (C) 2012 Brian Muramatsu
 *
 * 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.btmura.android.reddit.app;

import com.btmura.android.reddit.R;

import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.view.Menu;

public class DebugFragment extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        addPreferencesFromResource(R.xml.debug_preferences);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        // TODO: Figure out how to move this somehow to SettingsActivity.
        menu.findItem(R.id.menu_add_account).setVisible(false);
    }
}

/*
 * Copyright (C) 2012 Brian Muramatsu
 *
 * 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.btmura.android.reddit.app;

import android.os.Bundle;
import android.preference.PreferenceFragment;

import com.btmura.android.reddit.R;

public class DebugFragment extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        addPreferencesFromResource(R.xml.debug_preferences);
    }
}

Fix issue where add account would not appear


package seedu.doist.commons.core;

/**
 * Container for user visible messages.
 */
public class Messages {
    public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command";
    public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s";
    public static final String MESSAGE_INVALID_TASK_DISPLAYED_INDEX = "The task index provided is invalid";
    public static final String MESSAGE_TASKS_LISTED_OVERVIEW = "%1$d tasks listed!";
    public static final String MESSAGE_TASKS_SORTED_OVERVIEW = "Tasks sorted by %1$s!";
}

package seedu.doist.commons.core;

/**
 * Container for user visible messages.
 */
public class Messages {
    public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command";
    public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s";
    public static final String MESSAGE_INVALID_TASK_DISPLAYED_INDEX = "The task index provided is invalid";
    public static final String MESSAGE_TASKS_LISTED_OVERVIEW = "%1$d tasks listed!";
    public static final String MESSAGE_TASKS_SORTED_OVERVIEW = "Tasks sorted by %1$s!";
    public static final String MESSAGE_INVALID_DATES = "Incorrect dates used";
}

Add message for Invalid dates

Add message for Invalid dates


package io.quarkus.kubernetes.client.runtime;

import javax.annotation.PreDestroy;
import javax.enterprise.inject.Produces;
import javax.inject.Singleton;

import org.jboss.logging.Logger;

import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.quarkus.arc.DefaultBean;

@Singleton
public class KubernetesClientProducer {

    private static final Logger LOGGER = Logger.getLogger(KubernetesClientProducer.class);

    private KubernetesClient client;

    @DefaultBean
    @Singleton
    @Produces
    public Config config(KubernetesClientBuildConfig buildConfig) {
        return KubernetesClientUtils.createConfig(buildConfig);
    }

    @DefaultBean
    @Singleton
    @Produces
    public KubernetesClient kubernetesClient(Config config) {
        client = new DefaultKubernetesClient(config);
        return client;
    }

    @PreDestroy
    public void destroy() {
        if (client != null) {
            LOGGER.info("Closing Kubernetes client");
            client.close();
        }
    }
}

package io.quarkus.kubernetes.client.runtime;

import javax.annotation.PreDestroy;
import javax.enterprise.inject.Produces;
import javax.inject.Singleton;

import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.quarkus.arc.DefaultBean;

@Singleton
public class KubernetesClientProducer {

    private KubernetesClient client;

    @DefaultBean
    @Singleton
    @Produces
    public Config config(KubernetesClientBuildConfig buildConfig) {
        return KubernetesClientUtils.createConfig(buildConfig);
    }

    @DefaultBean
    @Singleton
    @Produces
    public KubernetesClient kubernetesClient(Config config) {
        client = new DefaultKubernetesClient(config);
        return client;
    }

    @PreDestroy
    public void destroy() {
        if (client != null) {
            client.close();
        }
    }
}

Drop log entry when closing the Kubernetes client

If we start logging something for every client we close, shutdown will
be far too verbose.