/***
 *
 * Copyright 2014 Andrew Hall
 *
 * 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.statefulj.framework.core.model.impl;

import org.statefulj.framework.core.model.Factory;

public class FactoryImpl<T, CT> implements Factory<T, CT> {

	@Override
	public T create(Class<T> clazz, String event, CT context) {
		T newInstance = null;
		try {
			newInstance = clazz.newInstance();
		} catch(IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		}
		return newInstance;
	}

}

/***
 *
 * Copyright 2014 Andrew Hall
 *
 * 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.statefulj.framework.core.model.impl;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.statefulj.framework.core.model.Factory;

public class FactoryImpl<T, CT> implements Factory<T, CT> {

	@Override
	public T create(Class<T> clazz, String event, CT context) {
		try {
			Constructor<T> ctr = clazz.getDeclaredConstructor();
			ctr.setAccessible(true);
			return ctr.newInstance();
		} catch(IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (InvocationTargetException e) {
			throw new RuntimeException(e);
		} catch (SecurityException e) {
			throw new RuntimeException(e);
		} catch (NoSuchMethodException e) {
			throw new RuntimeException(clazz.getCanonicalName() + " does not have a default constructor");
		}
	}

}

Add in ability to instantiate non public default constructors


package com.sleekbyte.tailor.grammar;

import com.sleekbyte.tailor.Tailor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.*;

import static org.junit.Assert.assertEquals;

public class GrammarTest {

    protected static final String TEST_INPUT_DIR = "src/test/java/com/sleekbyte/tailor/grammar/";
    protected static final String NEWLINE_REGEX = "\\r?\\n";

    protected ByteArrayOutputStream errContent;
    protected ByteArrayOutputStream outContent;
    protected File[] swiftFiles;

    @Before
    public void setUp() {
        File curDir = new File(TEST_INPUT_DIR);
        swiftFiles = curDir.listFiles((File file, String name) -> name.endsWith(".swift"));
        outContent = new ByteArrayOutputStream();
        System.setOut(new PrintStream(outContent));
    }

    @After
    public void tearDown() {
        System.setOut(null);
    }

    @Test
    public void testRule() throws IOException {
        for ( File swiftFile: swiftFiles) {
            errContent = new ByteArrayOutputStream();
            System.setErr(new PrintStream(errContent));
            String[] command = { (TEST_INPUT_DIR + swiftFile.getName()) };
            Tailor.main(command);
            assertEquals(errContent.toString(), "");
            System.setErr(null);
        }
    }

}

package com.sleekbyte.tailor.grammar;

import com.sleekbyte.tailor.Tailor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;

import static org.junit.Assert.assertEquals;

public class GrammarTest {

    protected static final String TEST_INPUT_DIR = "src/test/java/com/sleekbyte/tailor/grammar/";

    protected ByteArrayOutputStream errContent;
    protected ByteArrayOutputStream outContent;
    protected File[] swiftFiles;

    @Before
    public void setUp() {
        File curDir = new File(TEST_INPUT_DIR);
        swiftFiles = curDir.listFiles((File file, String name) -> name.endsWith(".swift"));
        outContent = new ByteArrayOutputStream();
        System.setOut(new PrintStream(outContent));
    }

    @After
    public void tearDown() {
        System.setOut(null);
    }

    @Test
    public void testRule() {
        for (File swiftFile: swiftFiles) {
            errContent = new ByteArrayOutputStream();
            System.setErr(new PrintStream(errContent));
            String[] command = { (TEST_INPUT_DIR + swiftFile.getName()) };
            Tailor.main(command);
            assertEquals(errContent.toString(), "");
            System.setErr(null);
        }
    }

}

Adjust code style, remove constant and exception


package me.mattlogan.artiste.example;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {

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

package me.mattlogan.artiste.example;

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

public class MainActivity extends AppCompatActivity {

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

Use AppCompatActivity in example project


package org.inferred.cjp39.j8stages;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;

import org.junit.Test;

public class ExceptionClonerTest {

    private static final class MyUnfriendlyException extends Exception {
        private MyUnfriendlyException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    @Test
    public void clone_matches_original() {
        MyUnfriendlyException x =
                new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause"));
        MyUnfriendlyException clone = ExceptionCloner.clone(x);
        assertEquals(x.getMessage(), clone.getMessage());
        assertSame(x.getCause(), clone.getCause());
    }

    @Test
    public void modifying_clone_does_not_modify_original() {
        MyUnfriendlyException x =
                new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause"));
        MyUnfriendlyException clone = ExceptionCloner.clone(x);
        clone.addSuppressed(new RuntimeException("dormouse"));
        assertEquals(0, x.getSuppressed().length);
    }
}

package org.inferred.cjp39.j8stages;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;

import org.junit.Test;

public class ExceptionClonerTest {

    private static final class MyUnfriendlyException extends Exception {
        private MyUnfriendlyException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    @Test
    public void clone_matches_original() {
        MyUnfriendlyException x =
                new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause"));
        MyUnfriendlyException clone = ExceptionCloner.clone(x);
        assertEquals(x.getMessage(), clone.getMessage());
        assertSame(x.getCause(), clone.getCause());
    }

    @Test
    public void modifying_clone_does_not_modify_original() {
        MyUnfriendlyException x =
                new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause"));
        MyUnfriendlyException clone = ExceptionCloner.clone(x);
        clone.addSuppressed(new RuntimeException("dormouse"));
        assertEquals(0, x.getSuppressed().length);
    }

    @Test
    public void suppressed_array_not_aliased() {
        MyUnfriendlyException x =
                new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause"));
        x.addSuppressed(new RuntimeException("Help, help, I'm being repressed!"));
        MyUnfriendlyException clone = ExceptionCloner.clone(x);
        clone.addSuppressed(new RuntimeException("dormouse"));
        MyUnfriendlyException clone2 = ExceptionCloner.clone(clone);
        clone2.addSuppressed(new RuntimeException("in a teapot"));
        assertEquals(3, clone2.getSuppressed().length);
        assertEquals(2, clone.getSuppressed().length);
        assertEquals(1, x.getSuppressed().length);
    }
}

Add a test to ensure the list of suppressed exceptions in a Throwable is not accidentally aliased during the shallow copy.


package cs437.som.neighborhood;

import cs437.som.NeightborhoodWidthFunction;

/**
 * Hyperbolic neighborhood width strategy for self-organizing map.
 */
public class HyperbolicNeighborhoodWidthFunction implements NeightborhoodWidthFunction {
    private double expectedIterations;

    public void setExpectedIterations(int expectedIterations) {
        this.expectedIterations = expectedIterations;
    }

    public double neighborhoodWidth(int iteration) {
        return expectedIterations / (expectedIterations + iteration);
    }

    @Override
    public String toString() {
        return "HyperbolicNeighborhoodWidthFunction";
    }
}

package cs437.som.neighborhood;

import cs437.som.NeightborhoodWidthFunction;

/**
 * Hyperbolic neighborhood width strategy for self-organizing map.
 *
 * The exact behavior follows the formula:
 *      w_i / (t + t_max)
 *  where
 *      w_i   is the initial width of the neighborhood
 *      t     is the current iteration
 *      t_max is the maximum expected iteration
 */
public class HyperbolicNeighborhoodWidthFunction implements NeightborhoodWidthFunction {
    private double expectedIterations = 0.0;

    public void setExpectedIterations(int expectedIterations) {
        this.expectedIterations = expectedIterations;
    }

    public double neighborhoodWidth(int iteration) {
        return expectedIterations / (expectedIterations + iteration);
    }

    @Override
    public String toString() {
        return "HyperbolicNeighborhoodWidthFunction";
    }
}

Add formula comment to hyperbolic NW class.


package com.thoughtworks.acceptance;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.LookAndFeel;
import javax.swing.plaf.synth.SynthLookAndFeel;

public class SwingTest extends AbstractAcceptanceTest {

    // JTable is one of the nastiest components to serialize. If this works, we're in good shape :)

    public void testJTable() {
        // Note: JTable does not have a sensible .equals() method, so we compare the XML instead.
        JTable original = new JTable();
        String originalXml = xstream.toXML(original);

        JTable deserialized = (JTable) xstream.fromXML(originalXml);
        String deserializedXml = xstream.toXML(deserialized);

        assertEquals(originalXml, deserializedXml);
    }

    public void testDefaultListModel() {
        final DefaultListModel original = new DefaultListModel();
        final JList list = new JList();
        list.setModel(original);

        String originalXml = xstream.toXML(original);

        DefaultListModel deserialized = (DefaultListModel) xstream.fromXML(originalXml);
        String deserializedXml = xstream.toXML(deserialized);

        assertEquals(originalXml, deserializedXml);

        list.setModel(deserialized);
    }

    public void testSynthLookAndFeel() {
        LookAndFeel plaf = new SynthLookAndFeel();
        String originalXml = xstream.toXML(plaf);
        assertBothWays(plaf, originalXml);
    }
}

package com.thoughtworks.acceptance;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.LookAndFeel;
import javax.swing.plaf.metal.MetalLookAndFeel;

public class SwingTest extends AbstractAcceptanceTest {

    // JTable is one of the nastiest components to serialize. If this works, we're in good shape :)

    public void testJTable() {
        // Note: JTable does not have a sensible .equals() method, so we compare the XML instead.
        JTable original = new JTable();
        String originalXml = xstream.toXML(original);

        JTable deserialized = (JTable) xstream.fromXML(originalXml);
        String deserializedXml = xstream.toXML(deserialized);

        assertEquals(originalXml, deserializedXml);
    }

    public void testDefaultListModel() {
        final DefaultListModel original = new DefaultListModel();
        final JList list = new JList();
        list.setModel(original);

        String originalXml = xstream.toXML(original);

        DefaultListModel deserialized = (DefaultListModel) xstream.fromXML(originalXml);
        String deserializedXml = xstream.toXML(deserialized);

        assertEquals(originalXml, deserializedXml);

        list.setModel(deserialized);
    }

    public void testMetalLookAndFeel() {
        LookAndFeel plaf = new MetalLookAndFeel();
        String originalXml = xstream.toXML(plaf);
        assertBothWays(plaf, originalXml);
    }
}

Use L&F that is available on JDK 1.3

Use L&F that is available on JDK 1.3


package com.developi.wink.demo.api;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.ibm.commons.util.io.json.JsonJavaObject;
import com.ibm.domino.osgi.core.context.ContextInfo;

import lotus.domino.NotesException;
import lotus.domino.Session;

@Path("/test")
public class TestResource {

	@GET
	public Response test(){
		JsonJavaObject resp = new JsonJavaObject();

		try {
			resp.put("message", "Hello " + getUserSession().getEffectiveUserName());
			return Response.ok().type(MediaType.APPLICATION_JSON).entity(resp.toString()).build();
		} catch (NotesException e) {
			e.printStackTrace();
			return Response.serverError().build();
		}

	}

	private Session getUserSession() {
		return ContextInfo.getUserSession();
	}

}

package com.developi.wink.demo.api;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import com.ibm.domino.osgi.core.context.ContextInfo;

import lotus.domino.NotesException;
import lotus.domino.Session;

@Path("/test")
public class TestResource {

	@GET
	public Response test(){
		try {
			String userName = getUserSession().getEffectiveUserName();

			if("Anonymous".equals(userName)) {
				// If connected through a browser, this response will signal for authentication and redirected to the login form.
				// However, be careful with 40x responses. If session authentication is enabled for the server,
				// The consumer might receive the login form and 200-OK response. This would be a code-breaker.
				return Response.status(Status.UNAUTHORIZED).build();
			} else {
				String message = "<b>Hello " + userName + "</b>";
				return Response.ok().type(MediaType.TEXT_HTML).entity(message).build();
			}
		} catch (NotesException e) {
			e.printStackTrace();
			return Response.serverError().build();
		}

	}

	private Session getUserSession() {
		return ContextInfo.getUserSession();
	}

}

Add authentication and modify response type for /test


package org.wordpress.aztec.demo;

import android.support.test.espresso.ViewInteraction;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isChecked;
import static android.support.test.espresso.matcher.ViewMatchers.isNotChecked;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static org.wordpress.aztec.demo.TestUtils.enterHTML;

@LargeTest
@RunWith(AndroidJUnit4.class)
public class SimpleTextFormattingTests {

    @Rule
    public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);

    @Test
    public void testSimpleBoldFormatting() {
        enterHTML("<b>hello world</b>");

        ViewInteraction boldButton = onView(withId(R.id.format_bar_button_bold));
        boldButton.check(matches(isChecked()));
    }
}

package org.wordpress.aztec.demo;

import android.support.test.espresso.ViewInteraction;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isChecked;
import static android.support.test.espresso.matcher.ViewMatchers.isNotChecked;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static org.wordpress.aztec.demo.TestUtils.enterHTML;

@LargeTest
@RunWith(AndroidJUnit4.class)
public class SimpleTextFormattingTests {

    @Rule
    public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);

    @Test
    public void testSimpleBoldFormatting() {
        ViewInteraction boldButton = onView(withId(R.id.format_bar_button_bold));
        boldButton.check(matches(isNotChecked()));

        enterHTML("<b>hello world</b>");

        boldButton.check(matches(isChecked()));
    }
}

Add check for disabled format button at start of test


/*
 * 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.jackrabbit.oak.kernel;

import org.apache.jackrabbit.oak.NodeStoreFixture;
import org.apache.jackrabbit.oak.spi.state.NodeStore;

class AbstractKernelTest {

    protected NodeStore createNodeStore() {
        return NodeStoreFixture.MK_IMPL.createNodeStore();
    }
}

/*
 * 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.jackrabbit.oak.kernel;

import org.apache.jackrabbit.oak.NodeStoreFixture;
import org.apache.jackrabbit.oak.spi.state.NodeStore;

class AbstractKernelTest {

    protected NodeStore createNodeStore() {
        return NodeStoreFixture.SEGMENT_MK.createNodeStore();
    }
}

OAK-1847: Use SegmentMK for testing where possible

git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1596603 13f79535-47bb-0310-9956-ffa450edef68


package com.worldspotlightapp.android.ui;

import android.os.Bundle;
import android.util.Log;

import com.worldspotlightapp.android.R;
import com.worldspotlightapp.android.model.Organizer;

import java.util.Observable;

public class OrganizerDetailsActivity extends AbstractBaseActivityObserver {

    private static final String TAG = "OrganizerDetails";

    private String mOrganizerObjectId;

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

        // Get the organizer object id from the intent
        Bundle extras = getIntent().getExtras();
        if (extras == null || !extras.containsKey(Organizer.INTENT_KEY_OBJECT_ID)) {
            throw new IllegalArgumentException("You must pass the organizer object id through the intent");
        }

        mOrganizerObjectId = extras.getString(Organizer.INTENT_KEY_OBJECT_ID);
        Log.v(TAG, "The object id got from the intent is " + mOrganizerObjectId);
    }

    @Override
    protected void processDataIfExists() {
        // TODO: implement this
    }

    @Override
    public void update(Observable observable, Object data) {
        // TODO: implement this
    }
}

package com.worldspotlightapp.android.ui;

import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;

import com.worldspotlightapp.android.R;
import com.worldspotlightapp.android.model.Organizer;

import java.util.Observable;

public class OrganizerDetailsActivity extends AbstractBaseActivityObserver {

    private static final String TAG = "OrganizerDetails";

    private String mOrganizerObjectId;

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

        // Get the organizer object id from the intent
        Bundle extras = getIntent().getExtras();
        if (extras == null || !extras.containsKey(Organizer.INTENT_KEY_OBJECT_ID)) {
            throw new IllegalArgumentException("You must pass the organizer object id through the intent");
        }

        mOrganizerObjectId = extras.getString(Organizer.INTENT_KEY_OBJECT_ID);
        Log.v(TAG, "The object id got from the intent is " + mOrganizerObjectId);

        // Action bar
        mActionBar.setDisplayHomeAsUpEnabled(true);

    }

    @Override
    protected void processDataIfExists() {
        // TODO: implement this
    }

    @Override
    public void update(Observable observable, Object data) {
        // TODO: implement this
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                Log.v(TAG, "home button pressed");
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

Set back button for the organizer details activity


/*
 * Copyright 2012, Mysema Ltd
 *
 * 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.mysema.query.maven;

import javax.jdo.annotations.EmbeddedOnly;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.persistence.Embedded;

import com.mysema.query.codegen.GenericExporter;

/**
 * JDOExporterMojo calls the GenericExporter tool using the classpath of the module
 *
 * @goal jdo-export
 * @requiresDependencyResolution test
 * @author tiwe
 */
public class JDOExporterMojo extends AbstractExporterMojo {

    @Override
    protected void configure(GenericExporter exporter) {
        exporter.setEmbeddableAnnotation(EmbeddedOnly.class);
        exporter.setEmbeddedAnnotation(Embedded.class);
        exporter.setEntityAnnotation(PersistenceCapable.class);
        exporter.setSkipAnnotation(NotPersistent.class);
        exporter.setSupertypeAnnotation(null);
    }

}

/*
 * Copyright 2012, Mysema Ltd
 *
 * 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.mysema.query.maven;

import javax.jdo.annotations.EmbeddedOnly;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.persistence.Embedded;

import com.mysema.query.codegen.GenericExporter;

/**
 * JDOExporterMojo calls the GenericExporter tool using the classpath of the module
 *
 * @goal jdo-export
 * @requiresDependencyResolution test
 * @author tiwe
 */
public class JDOExporterMojo extends AbstractExporterMojo {

    @Override
    protected void configure(GenericExporter exporter) {
        exporter.setEmbeddableAnnotation(EmbeddedOnly.class);
        exporter.setEmbeddedAnnotation(Embedded.class);
        exporter.setEntityAnnotation(PersistenceCapable.class);
        exporter.setSkipAnnotation(NotPersistent.class);
    }

}

Fix NPE when exporting JDO using maven plugin


package org.atlasapi.application.auth;

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

import javax.servlet.http.HttpServletRequest;

import org.atlasapi.application.Application;
import org.atlasapi.application.ApplicationSources;
import org.atlasapi.application.ApplicationStore;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;

public class ApiKeySourcesFetcher implements ApplicationSourcesFetcher {

    public static final String API_KEY_QUERY_PARAMETER = "key";

    private final ApplicationStore reader;

    public ApiKeySourcesFetcher(ApplicationStore reader) {
        this.reader = checkNotNull(reader);
    }

    @Override
    public ImmutableSet<String> getParameterNames() {
        return ImmutableSet.of();
    }

    @Override
    public Optional<ApplicationSources> sourcesFor(HttpServletRequest request) throws InvalidApiKeyException  {
        String apiKey = request.getParameter(API_KEY_QUERY_PARAMETER);
        if (apiKey == null) {
            apiKey = request.getHeader(API_KEY_QUERY_PARAMETER);
        }
        if (apiKey != null) {
            Optional<Application> app = reader.applicationForKey(apiKey);
            if (!app.isPresent() || app.get().isRevoked()) {
                throw new InvalidApiKeyException(apiKey);
            }
            return Optional.of(app.get().getSources());
        }
        return Optional.absent();
    }
}

package org.atlasapi.application.auth;

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

import javax.servlet.http.HttpServletRequest;

import org.atlasapi.application.Application;
import org.atlasapi.application.ApplicationSources;
import org.atlasapi.application.ApplicationStore;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;

public class ApiKeySourcesFetcher implements ApplicationSourcesFetcher {

    public static final String API_KEY_QUERY_PARAMETER = "key";

    private final ApplicationStore reader;

    public ApiKeySourcesFetcher(ApplicationStore reader) {
        this.reader = checkNotNull(reader);
    }

    @Override
    public ImmutableSet<String> getParameterNames() {
        return ImmutableSet.of(API_KEY_QUERY_PARAMETER);
    }

    @Override
    public Optional<ApplicationSources> sourcesFor(HttpServletRequest request) throws InvalidApiKeyException  {
        String apiKey = request.getParameter(API_KEY_QUERY_PARAMETER);
        if (apiKey == null) {
            apiKey = request.getHeader(API_KEY_QUERY_PARAMETER);
        }
        if (apiKey != null) {
            Optional<Application> app = reader.applicationForKey(apiKey);
            if (!app.isPresent() || app.get().isRevoked()) {
                throw new InvalidApiKeyException(apiKey);
            }
            return Optional.of(app.get().getSources());
        }
        return Optional.absent();
    }
}

Revert "api key deleted from the list of required parameters"


// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.sdk;

import java.util.List;

import org.chromium.sdk.util.MethodIsBlockingException;

/**
 * An object that represents a scope in JavaScript.
 */
public interface JsScope {

  enum Type {
    GLOBAL,
    LOCAL,
    WITH,
    CLOSURE,
    CATCH,
    UNKNOWN
  }

  /**
   * @return type of the scope
   */
  Type getType();

  /**
   * @return optional subtype when type is {@link Type#WITH} and null otherwise
   */
  WithScope asWithScope();

  /**
   * @return the variables known in this scope, in lexicographical order
   * @throws MethodIsBlockingException because it may need to load value from remote
   */
  List<? extends JsVariable> getVariables() throws MethodIsBlockingException;

  /**
   * Subtype that exposes the value of the 'with' statement expression (the value might be
   * already converted by ToObject).
   */
  interface WithScope extends JsScope {
    /**
     * @throws MethodIsBlockingException because it may need to load value from remote
     */
    JsValue getWithArgument() throws MethodIsBlockingException;
  }
}

// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.sdk;

import java.util.List;

import org.chromium.sdk.util.MethodIsBlockingException;

/**
 * An object that represents a scope in JavaScript.
 * TODO: consider adding object getter for both with and global scopes.
 */
public interface JsScope {

  enum Type {
    GLOBAL,
    LOCAL,
    WITH,
    CLOSURE,
    CATCH,
    UNKNOWN
  }

  /**
   * @return type of the scope
   */
  Type getType();

  /**
   * @return optional subtype when type is {@link Type#WITH} and null otherwise
   */
  WithScope asWithScope();

  /**
   * @return the variables known in this scope, in lexicographical order
   * @throws MethodIsBlockingException because it may need to load value from remote
   */
  List<? extends JsVariable> getVariables() throws MethodIsBlockingException;

  /**
   * Subtype that exposes the value of the 'with' statement expression (the value might be
   * already converted by ToObject).
   */
  interface WithScope extends JsScope {
    /**
     * @throws MethodIsBlockingException because it may need to load value from remote
     */
    JsValue getWithArgument() throws MethodIsBlockingException;
  }
}

Add 'watch property descriptor' action

Add 'watch property descriptor' action

Review URL: https://chromiumcodereview.appspot.com/9391018

git-svn-id: 1dc80909446f7a7ee3e21dd4d1b8517df524e9ee@927 fc8a088e-31da-11de-8fef-1f5ae417a2df


package com.farm.environment.configuration;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = {
        "com.farm.processes",
        "com.farm.rest"
})
public class BeansConfiguration {

}

package com.farm.environment.configuration;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = {
        "com.farm.database.processes",
        "com.farm.rest"
})
public class BeansConfiguration {

}

Correct componets path to scan

Correct componets path to scan


package com.codahale.metrics.jvm;

import com.codahale.metrics.Gauge;
import org.junit.Test;

import java.lang.management.ClassLoadingMXBean;

import static org.fest.assertions.api.Assertions.assertThat;

public class ClassLoadingGaugeSetTest {

    private final ClassLoadingMXBean cl = new ClassLoadingMXBean() {
        @Override
        public long getTotalLoadedClassCount() {
            return 2;
        }

        @Override
        public int getLoadedClassCount() {
            return 3;
        }

        @Override
        public long getUnloadedClassCount() {
            return 1;
        }

        @Override
        public boolean isVerbose() {
            return false;
        }

        @Override
        public void setVerbose(boolean value) {

        }
    };

    private final ClassLoadingGaugeSet gauges = new ClassLoadingGaugeSet(cl);

    @Test
    public void loadedGauge() throws Exception {
        final Gauge gauge = (Gauge) gauges.getMetrics().get("loaded");
        assertThat(gauge.getValue()).isEqualTo(2L);
    }

    @Test
    public void unLoadedGauge() throws Exception {
        final Gauge gauge = (Gauge) gauges.getMetrics().get("unloaded");
        assertThat(gauge.getValue()).isEqualTo(1L);
    }

}

package com.codahale.metrics.jvm;

import com.codahale.metrics.Gauge;
import org.junit.Before;
import org.junit.Test;

import java.lang.management.ClassLoadingMXBean;

import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ClassLoadingGaugeSetTest {

    private final ClassLoadingMXBean cl = mock(ClassLoadingMXBean.class);
    private final ClassLoadingGaugeSet gauges = new ClassLoadingGaugeSet(cl);

    @Before
    public void setUp() throws Exception {
        when(cl.getTotalLoadedClassCount()).thenReturn(2L);
        when(cl.getUnloadedClassCount()).thenReturn(1L);
    }

    @Test
    public void loadedGauge() throws Exception {
        final Gauge gauge = (Gauge) gauges.getMetrics().get("loaded");
        assertThat(gauge.getValue()).isEqualTo(2L);
    }

    @Test
    public void unLoadedGauge() throws Exception {
        final Gauge gauge = (Gauge) gauges.getMetrics().get("unloaded");
        assertThat(gauge.getValue()).isEqualTo(1L);
    }

}

Switch to a mocking way of testing.

Switch to a mocking way of testing.


package com.github.chrisblutz.trinity.libraries.compiling;

/**
 * @author Christopher Lutz
 */
public class CompileException extends RuntimeException {

    public CompileException(String file, long line, String message) {

        super("Compilation error on line " + line + " in " + file + ".");
        setStackTrace(new StackTraceElement[]{});
    }
}

package com.github.chrisblutz.trinity.libraries.compiling;

/**
 * @author Christopher Lutz
 */
public class CompileException extends RuntimeException {

    public CompileException(String file, long line, String message) {

        super("Compilation error on line " + line + " in " + file + ": " + message);
        setStackTrace(new StackTraceElement[]{});
    }
}

Use message in library compilation errors


package musician101.common.java.minecraft.sponge.command;

import org.spongepowered.api.text.Text.Literal;
import org.spongepowered.api.text.Texts;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;

import javax.annotation.Nonnull;
import java.util.Arrays;

public class SpongeHelpCommand extends AbstractSpongeCommand
{
    private final AbstractSpongeCommand mainCommand;

    public SpongeHelpCommand(AbstractSpongeCommand mainCommand, CommandSource source)
    {
        super("help", "Display help info for " + mainCommand.getUsage(source), Arrays.asList(new SpongeCommandArgument(((Literal) mainCommand.getUsage(source)).getContent()), new SpongeCommandArgument("help")), 1, "", false, null, null);
        this.mainCommand = mainCommand;
    }

    @Nonnull
    @Override
    public CommandResult process(@Nonnull CommandSource source, @Nonnull String arguments) throws CommandException
    {
        source.sendMessage(Texts.of());
        source.sendMessage(mainCommand.getUsage(source));
        mainCommand.getSubCommands().forEach(command -> source.sendMessage(command.getHelp(source).get()));
        return CommandResult.success();
    }
}

package musician101.common.java.minecraft.sponge.command;

import org.spongepowered.api.text.Text.Literal;
import org.spongepowered.api.text.Texts;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;

import javax.annotation.Nonnull;
import java.util.Arrays;

public class SpongeHelpCommand extends AbstractSpongeCommand
{
    private final AbstractSpongeCommand mainCommand;

    public SpongeHelpCommand(AbstractSpongeCommand mainCommand, CommandSource source)
    {
        super("help", "Display help info for " + mainCommand.getUsage(source), Arrays.asList(new SpongeCommandArgument(((Literal) mainCommand.getUsage(source)).getContent()), new SpongeCommandArgument("help")), 1, "", false, null, null);
        this.mainCommand = mainCommand;
    }

    @Nonnull
    @Override
    public CommandResult process(@Nonnull CommandSource source, @Nonnull String arguments) throws CommandException
    {
        source.sendMessage(Texts.of(mainCommand.getUsage(source), mainCommand.getShortDescription(source)));
        mainCommand.getSubCommands().forEach(command -> source.sendMessage(command.getHelp(source).get()));
        return CommandResult.success();
    }
}

Add description to the help message.

Add description to the help message.


package org.nwapw.abacus.function;

import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.tree.TreeNode;

/**
 * A function that operates on parse tree nodes instead of on already simplified numbers.
 * Despite this, it returns a number, not a tree.
 */
public abstract class TreeValueFunction extends Applicable<TreeNode, NumberInterface> {

}

package org.nwapw.abacus.function;

import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.tree.Reducer;
import org.nwapw.abacus.tree.TreeNode;

/**
 * A function that operates on parse tree nodes instead of on already simplified numbers.
 * Despite this, it returns a number, not a tree.
 */
public abstract class TreeValueFunction extends Applicable<TreeNode, NumberInterface> {

    @Override
    protected NumberInterface applyInternal(TreeNode[] params) {
        return null;
    }

    @Override
    public NumberInterface apply(TreeNode... params) {
        return null;
    }

    /**
     * Applies the tree value functions to the given tree nodes,
     * using the given reducer.
     * @param reducer the reducer to use.
     * @param params the parameters to apply to.
     * @return the result of the application.
     */
    public abstract NumberInterface applyWithReducerInternal(Reducer<NumberInterface> reducer, TreeNode[] params);

    /**
     * Checks if the given parameters and reducer can be used
     * with this function, and if so, calls the function on them.
     * @param reducer the reducer to use.
     * @param params the parameters to apply to.
     * @return the result of the application, or null if the parameters are incompatible.
     */
    public NumberInterface applyWithReducer(Reducer<NumberInterface> reducer, TreeNode... params) {
        if(!matchesParams(params) || reducer == null) return null;
        return applyWithReducerInternal(reducer, params);
    }
}

Add the withReducer variants of the Applier functions.


package org.tylproject.vaadin.addon.utils;

import com.vaadin.addon.jpacontainer.EntityItem;
import com.vaadin.data.Item;
import com.vaadin.data.util.BeanItem;
import org.vaadin.viritin.DynaBeanItem;
import org.vaadin.viritin.ListContainer;

/**
 * Extracts bean from an Item, depending on the Container implementation
 */
public class DefaultBeanExtractor implements BeanExtractor {
    @Override
    public Object extract(Object itemId, Item item) throws IllegalArgumentException {

        final Class<?> itemClass = item.getClass();
        Object bean;

        if (ListContainer.DynaBeanItem.class.isAssignableFrom(itemClass)) {
            bean = itemId;
        } else
        if (isJPAContainer(itemClass)) {
            bean = ((EntityItem<?>)item).getEntity();
        } else
        if (BeanItem.class.isAssignableFrom(item.getClass())) {
            bean = ((BeanItem<?>) item).getBean();
        } else{
            throw new UnsupportedOperationException(
                    "Unknown item type: "+itemClass.getCanonicalName());
        }

        return bean;
    }

    protected boolean isJPAContainer(Class<?> itemClass) {
        try {
            return EntityItem.class.isAssignableFrom(itemClass);
        } catch (NoClassDefFoundError ex) { return false; }
    }

}

package org.tylproject.vaadin.addon.utils;

import com.vaadin.addon.jpacontainer.EntityItem;
import com.vaadin.data.Item;
import com.vaadin.data.util.BeanItem;
import org.vaadin.viritin.DynaBeanItem;
import org.vaadin.viritin.ListContainer;

/**
 * Extracts bean from an Item, depending on the Container implementation
 */
public class DefaultBeanExtractor implements BeanExtractor {
    @Override
    public Object extract(Object itemId, Item item) throws IllegalArgumentException {

        final Class<?> itemClass = item.getClass();
        Object bean;

        if (ListContainer.DynaBeanItem.class.isAssignableFrom(itemClass)
            || DynaBeanItem.class.isAssignableFrom(itemClass)) {
            bean = itemId;
        } else
        if (isJPAContainer(itemClass)) {
            bean = ((EntityItem<?>)item).getEntity();
        } else
        if (BeanItem.class.isAssignableFrom(item.getClass())) {
            bean = ((BeanItem<?>) item).getBean();
        } else{
            throw new UnsupportedOperationException(
                    "Unknown item type: "+itemClass.getCanonicalName());
        }

        return bean;
    }

    protected boolean isJPAContainer(Class<?> itemClass) {
        try {
            return EntityItem.class.isAssignableFrom(itemClass);
        } catch (NoClassDefFoundError ex) { return false; }
    }

}

Fix bug in BeanExtractor (DynaBeanItem was not recognized)


/*
 * Copyright 2016 Crown Copyright
 *
 * 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 stroom.data.client.presenter;

public final class ColumnSizeConstants {

    public static final int CHECKBOX_COL = 16;
    public static final int ICON_COL = 20;
    public static final int SMALL_COL = 70;
    public static final int MEDIUM_COL = 100;
    public static final int BIG_COL = 400;
    public static final int DATE_COL = 160;

    private ColumnSizeConstants() {
        // Constants.
    }
}

/*
 * Copyright 2016 Crown Copyright
 *
 * 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 stroom.data.client.presenter;

public final class ColumnSizeConstants {

    public static final int CHECKBOX_COL = 16;
    public static final int ICON_COL = 23;
    public static final int SMALL_COL = 70;
    public static final int MEDIUM_COL = 100;
    public static final int BIG_COL = 400;
    public static final int DATE_COL = 160;

    private ColumnSizeConstants() {
        // Constants.
    }
}

Increase datagrid icon column width

Increase datagrid icon column width


package com.agricraft.agricore.templates;

import com.agricraft.agricore.core.AgriCore;
import com.google.gson.JsonObject;

public class AgriMutationTrigger {
    private final String id;
    private final boolean required;
    private final boolean guaranteed;
    private final JsonObject parameters;

    public AgriMutationTrigger() {
        this.id = "none";
        this.required = false;
        this.guaranteed = false;
        this.parameters = new JsonObject();
    }

    public AgriMutationTrigger(String id, boolean required, boolean guaranteed, JsonObject parameters) {
        this.id = id;
        this.required = required;
        this.guaranteed = guaranteed;
        this.parameters = parameters;
    }

    public String getId() {
        return this.id;
    }

    public boolean isRequired() {
        return this.required;
    }

    public boolean isGuaranteed() {
        return this.guaranteed;
    }

    public JsonObject getParameters() {
        return this.parameters;
    }

    public boolean validate() {
        boolean valid = AgriCore.getValidator().isValidMutationTrigger(this.getId(), this.getParameters());
        if(!valid) {
            AgriCore.getCoreLogger().info("Invalid Mutation trigger {0}: {1}", this.getId(), this.getParameters());
        }
        return valid;
    }
}

package com.agricraft.agricore.templates;

import com.agricraft.agricore.core.AgriCore;
import com.google.gson.JsonObject;

public class AgriMutationTrigger {
    private final String id;
    private final boolean required;
    private final double guaranteedChance;
    private final JsonObject parameters;

    public AgriMutationTrigger() {
        this.id = "none";
        this.required = false;
        this.guaranteedChance = 0;
        this.parameters = new JsonObject();
    }

    public AgriMutationTrigger(String id, boolean required, double guaranteedChance, JsonObject parameters) {
        this.id = id;
        this.required = required;
        this.guaranteedChance = guaranteedChance;
        this.parameters = parameters;
    }

    public String getId() {
        return this.id;
    }

    public boolean isRequired() {
        return this.required;
    }

    public double getGuaranteedChance() {
        return this.guaranteedChance;
    }

    public JsonObject getParameters() {
        return this.parameters;
    }

    public boolean validate() {
        if(!AgriCore.getValidator().isValidMutationTrigger(this.getId(), this.getParameters())) {
            AgriCore.getCoreLogger().info("Invalid Mutation trigger {0}: {1}", this.getId(), this.getParameters());
            return false;
        }
        if(this.getGuaranteedChance() < 0 || this.getGuaranteedChance() > 1) {
            AgriCore.getCoreLogger().info("Invalid Mutation trigger guaranteed probability: {1}, the value must be between 0 and 1 (both inclusive)", this.getId(), this.getParameters());
            return false;
        }
        return true;
    }
}

Make mutation trigger guarantee a probability


package com.kushkipagos.android.example;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.kushkipagos.android.Card;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.sendButton);

        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                TextView textField = (TextView) findViewById(R.id.txtEncryptedMessage);
                EditText nameText = (EditText) findViewById(R.id.nameText);
                EditText numberText = (EditText) findViewById(R.id.numberText);
                EditText monthText = (EditText) findViewById(R.id.monthText);
                EditText yearText = (EditText) findViewById(R.id.yearText);
                EditText cvvText = (EditText) findViewById(R.id.cvvText);
                Card card = new Card(nameText.getText().toString(), numberText.getText().toString(),
                        cvvText.getText().toString(), monthText.getText().toString(), yearText.getText().toString());
                textField.setText("");
                ExampleAsyncTask exampleAsyncTask = new ExampleAsyncTask(getApplicationContext(), card);
                exampleAsyncTask.execute();
            }
        });
    }
}

package com.kushkipagos.android.example;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.kushkipagos.android.Card;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.sendButton);

        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                EditText nameText = (EditText) findViewById(R.id.nameText);
                EditText numberText = (EditText) findViewById(R.id.numberText);
                EditText monthText = (EditText) findViewById(R.id.monthText);
                EditText yearText = (EditText) findViewById(R.id.yearText);
                EditText cvvText = (EditText) findViewById(R.id.cvvText);
                Card card = new Card(nameText.getText().toString(), numberText.getText().toString(),
                        cvvText.getText().toString(), monthText.getText().toString(), yearText.getText().toString());
                ExampleAsyncTask exampleAsyncTask = new ExampleAsyncTask(getApplicationContext(), card);
                exampleAsyncTask.execute();
            }
        });
    }
}

Remove references to deleted field

[KFE-203] Remove references to deleted field


package br.com.bloder.blormlib.validation.validations;

import android.widget.CheckBox;

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

public class Checked extends Validation {

    private CheckBox checkBox;

    @Override
    public Validate validate() {
        return new Validate() {
            @Override
            public boolean validate() {
               checkBox = (CheckBox) field;
               return checkBox.isChecked();
            }

            @Override
            public void onError() {
                checkBox.setError("This field can't be unchecked");
            }

            @Override public void onSuccess() {}
        };
    }
}

package br.com.bloder.blormlib.validation.validations;

import android.widget.CheckBox;

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

public class Checked extends Validation {

    private CheckBox checkBox;

    @Override
    public Validate validate() {
        return new Validate() {
            @Override
            public boolean validate() {
               checkBox = (CheckBox) field;
               return checkBox.isChecked();
            }

            @Override
            public void onError() {
                checkBox.setError("This field can't be unchecked");
            }

            @Override public void onSuccess() {
                checkBox.setError(null);
            }
        };
    }
}

Implement on success checked validation

Implement on success checked validation


package pylos.view;

import pylos.Pylos;
import pylos.model.Ball;

import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Sphere;

public class BallGraphics {
	Ball model;
	public final static float DIAMETER = 1.38f;
	public float x, y, z;
	Geometry geometry;

	public BallGraphics(Ball model) {
		this.model = model;
	}

	public void setPosition(float x, float y, float z) {
		this.x = x;
		this.y = y;
		this.z = z;
	}

	public void move() {
		geometry.move(x, y, z);
	}

	public void create() {
		Sphere s = new Sphere(50, 50, DIAMETER / 2);
		geometry = new Geometry("Ball #" + model.i + " (" + model.owner.side + ")", s);
		Material mat = new Material(Pylos.view.getAssetManager(), "Common/MatDefs/Misc/SolidColor.j3md");
		mat.setColor("Color", ColorRGBA.randomColor());
		geometry.setMaterial(mat);
	}
}

package pylos.view;

import pylos.Pylos;
import pylos.model.Ball;
import pylos.model.Model;

import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Sphere;

public class BallGraphics {
	Ball model;
	public final static float DIAMETER = 1.38f;
	public float x, y, z;
	Geometry geometry;

	public BallGraphics(Ball model) {
		this.model = model;
	}

	public void setPosition(float x, float y, float z) {
		this.x = x;
		this.y = y;
		this.z = z;
	}

	public void move() {
		geometry.move(x, y, z);
	}

	public void create() {
		Material mat;
		Sphere s = new Sphere(50, 50, DIAMETER / 2);
		geometry = new Geometry("Ball #" + model.i + " (" + model.owner.side + ")", s);
		if (model.owner == Model.player1) {
			mat = new Material(Pylos.view.getAssetManager(), "Common/MatDefs/Light/Lighting.j3md");
		} else {
			mat = new Material(Pylos.view.getAssetManager(), "Common/MatDefs/Light/Lighting.j3md");
			mat.setFloat("Shininess", 0.5f);
		}
		geometry.setMaterial(mat);
	}
}

Set new material for balls

Set new material for balls


/*
 * Kurento Commons MSControl: Simplified Media Control API for the Java Platform based on jsr309
 * Copyright (C) 2012  Tikal Technologies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.kurento.mscontrol.commons;

/**
 * This class is the entry point where a MediaSession can be obtained
 *
 */
public interface MediaSessionFactory {

	/**
	 * Creates a new mediaSession object
	 *
	 * @return New media session for a platform
	 * @throws MediaSessionException
	 */
	public MediaSession createMediaSession()
			throws MediaSessionException;

}

/*
 * Kurento Commons MSControl: Simplified Media Control API for the Java Platform based on jsr309
 * Copyright (C) 2012  Tikal Technologies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.kurento.mscontrol.commons;

import com.kurento.commons.config.Parameters;

/**
 * This class is the entry point where a MediaSession can be obtained
 *
 */
public interface MediaSessionFactory {

	/**
	 * Creates a new mediaSession object using the given configuration
	 * parameters. See platform documentation for further details about the
	 * parameters.
	 *
	 * @param parameters
	 *            The configuration of the MediaSession
	 * @return New media session for a platform
	 * @throws MediaSessionException
	 */
	public MediaSession createMediaSession(Parameters parameters)
			throws MediaSessionException;

}

Add paratemers to mediaSession factory method


package com.faforever.api.data.listeners;

import com.faforever.api.config.FafApiProperties;
import com.faforever.api.data.domain.Game;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import javax.persistence.PostLoad;

@Component
public class GameEnricher {

  private static FafApiProperties fafApiProperties;

  @Inject
  public void init(FafApiProperties fafApiProperties) {
    GameEnricher.fafApiProperties = fafApiProperties;
  }

  @PostLoad
  public void enrich(Game game) {
    game.setReplayUrl(String.format(fafApiProperties.getReplay().getDownloadUrlFormat(), game.getId()));
    game.setName(StringEscapeUtils.unescapeHtml4(game.getName()));
  }
}

package com.faforever.api.data.listeners;

import com.faforever.api.data.domain.Game;
import com.faforever.api.game.GameService;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import javax.persistence.PostLoad;

@Component
public class GameEnricher {

  private static GameService gameService;

  @Inject
  public void init(GameService gameService) {
    GameEnricher.gameService = gameService;
  }

  @PostLoad
  public void enrich(Game game) {
    game.setReplayUrl(gameService.getReplayDownloadUrl(game.getId()));
    game.setName(StringEscapeUtils.unescapeHtml4(game.getName()));
  }
}

Fix broken replay url in game entity

Fix broken replay url in game entity


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * 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.github.pedrovgs.problem78;

/**
 * Some integers returns the same instance if you apply autoboxing, you can check it with this
 * code and the related test.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class AutoBoxingTrick {

}

/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * 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.github.pedrovgs.problem78;

/**
 * Some integers returns the same instance if you apply autoboxing, you can check it with this
 * code and the related test.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class AutoBoxingTrick {

  public boolean compare(Integer n1, Integer n2) {
    return n1 == n2;
  }
}

Add solution to problem 78

Add solution to problem 78


package com.growthpush.cocos2dx;

import org.cocos2dx.lib.Cocos2dxGLSurfaceView;

import com.growthpush.bridge.ExternalFrameworkBridge;

public class Cocos2dxBridge extends ExternalFrameworkBridge {

	@Override
	protected void callbackExternalFramework(final String customFiled) {
		Cocos2dxGLSurfaceView.getInstance().queueEvent(new Runnable() {
			@Override
			public void run() {
				didOpenRemoteNotification(customFiled);
			}
		});
	}

	/*
	 * Remote notification callback method (JNI interface)
	 *
	 * @param json json string
	 */
	static native void didOpenRemoteNotification(String json);

}

package com.growthpush.cocos2dx;

import org.cocos2dx.lib.Cocos2dxGLSurfaceView;

import android.os.Handler;

import com.growthpush.GrowthPush;
import com.growthpush.bridge.ExternalFrameworkBridge;

public class Cocos2dxBridge extends ExternalFrameworkBridge {

	@Override
	protected void callbackExternalFramework(final String customFiled) {

		if (GrowthPush.getInstance().getApplicationId() == 0) {
			new Handler().post(new Runnable() {
				@Override
				public void run() {
					callbackExternalFramework(customFiled);
				}
			});
			return;
		}

		Cocos2dxGLSurfaceView.getInstance().queueEvent(new Runnable() {
			@Override
			public void run() {
				didOpenRemoteNotification(customFiled);
			}
		});

	}

	/*
	 * Remote notification callback method (JNI interface)
	 *
	 * @param json json string
	 */
	static native void didOpenRemoteNotification(String json);

}

Send callback custom field after Growth Push initialized instance


/*
 * Copyright 2011-2016 B2i Healthcare Pte Ltd, http://b2i.sg
 *
 * 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.b2international.snowowl.terminologyregistry.core.request;

/**
 * @since 4.7
 */
public class CodeSystemRequests {

	private final String repositoryId;

	public CodeSystemRequests(final String repositoryId) {
		this.repositoryId = checkNotNull(repositoryId, "repositoryId");
	}

	public CodeSystemCreateRequestBuilder prepareNewCodeSystem() {
		return new CodeSystemCreateRequestBuilder(repositoryId);
	}

	public static CodeSystemUpdateRequestBuilder prepareUpdateCodeSystem(final String uniqueId) {
		return new CodeSystemUpdateRequestBuilder(uniqueId);
	}

	public static CodeSystemGetRequestBuilder prepareGetCodeSystem() {
		return new CodeSystemGetRequestBuilder();
	}

	public static CodeSystemSearchRequestBuilder prepareSearchCodeSystem() {
		return new CodeSystemSearchRequestBuilder();
	}

	public static CodeSystemVersionSearchRequestBuilder prepareSearchCodeSystemVersion() {
		return new CodeSystemVersionSearchRequestBuilder();
	}

	public String getRepositoryId() {
		return repositoryId;
	}
}

/*
 * Copyright 2011-2016 B2i Healthcare Pte Ltd, http://b2i.sg
 *
 * 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.b2international.snowowl.terminologyregistry.core.request;

/**
 * @since 4.7
 */
public class CodeSystemRequests {

	private CodeSystemRequests() {}

	public static CodeSystemCreateRequestBuilder prepareNewCodeSystem() {
		return new CodeSystemCreateRequestBuilder();
	}

	public static CodeSystemUpdateRequestBuilder prepareUpdateCodeSystem(final String uniqueId) {
		return new CodeSystemUpdateRequestBuilder(uniqueId);
	}

	public static CodeSystemGetRequestBuilder prepareGetCodeSystem() {
		return new CodeSystemGetRequestBuilder();
	}

	public static CodeSystemSearchRequestBuilder prepareSearchCodeSystem() {
		return new CodeSystemSearchRequestBuilder();
	}

	public static CodeSystemVersionSearchRequestBuilder prepareSearchCodeSystemVersion() {
		return new CodeSystemVersionSearchRequestBuilder();
	}
}

[core] Make all methods in CodeSytemRequests static


package com.github.athi.athifx.gui.menu.item;

import com.github.athi.athifx.gui.font_awesome.FontAwesome;
import com.github.athi.athifx.gui.menu.group.Group;

/**
 * Created by Athi
 */
public interface Item<GROUP extends Enum<?> & Group> {

    long id();

    String caption();

    FontAwesome icon();

    /**
     * @return - returns the menu group in witch the item will be set - can be null
     * If the group is null it means that the view wont be added to the menu.
     */
    GROUP group();

    default String itemId() {
        return id() + "_" + caption();
    }
}

package com.github.athi.athifx.gui.menu.item;

import com.github.athi.athifx.gui.font_awesome.FontAwesome;
import com.github.athi.athifx.gui.menu.group.Group;

/**
 * Created by Athi
 */
public interface Item<GROUP extends Enum<?> & Group> {

    long id();

    String caption();

    FontAwesome icon();

    /**
     * @return - returns the menu group in witch the item will be set - can be null
     * If the group is null it means that the view wont be added to the menu.
     */
    GROUP group();

    default String itemId() {
        return String.valueOf(id() + "_" + caption()).replaceAll(" ", "");
    }
}

Support for itemId with spaces.

Support for itemId with spaces.


package language;

import java.util.EnumSet;

/**
 * {@code Difficulty} is an enumeration of properties which define how objects
 * of {@link Word} are formatted and also provides for "difficulty" properties
 * for use in a word game.
 *
 * <p> The properties defined in this class are designed to be
 * implementation-dependant and have no values stored to them other than their
 * names.
 *
 * @author Oliver Abdulrahim
 */
public enum Difficulty {

// Difficulty properties

    /**
     * Defines a {@code Word} with easy difficulty.
     */
    EASY,

    /**
     * Defines a {@code Word} with medium difficulty.
     */
    MEDIUM,

    /**
     * Defines a {@code Word} with hard difficulty.
     */
    HARD,

    /**
     * Defines a {@code Word} with default difficultly.
     */
    DEFAULT;

    /**
     * Provides for a set of all properties enumerated in this class.
     */
    public static final EnumSet<Difficulty> ALL = // Pryda 10 VOL III is out
            EnumSet.allOf(Difficulty.class);

}

package language;

import java.util.EnumSet;
import java.util.Set;

/**
 * {@code Difficulty} is an enumeration of properties which define how objects
 * of {@link Word} are formatted and also provides for "difficulty" properties
 * for use in a word game.
 *
 * <p> The properties defined in this class are designed to be
 * implementation-dependant and have no values stored to them other than their
 * names.
 *
 * @author Oliver Abdulrahim
 */
public enum Difficulty {

    /**
     * Defines a {@code Word} with easy difficulty.
     */
    EASY,

    /**
     * Defines a {@code Word} with medium difficulty.
     */
    MEDIUM,

    /**
     * Defines a {@code Word} with hard difficulty.
     */
    HARD,

    /**
     * Defines a {@code Word} with default difficultly.
     */
    DEFAULT;

    /**
     * Provides for a set of all properties enumerated in this class.
     */
    public static final Set<Difficulty> ALL = // Pryda 10 VOL III is out
            EnumSet.allOf(Difficulty.class);

}

Change EnumSet to Set for better polymorphism.


package me.rkfg.xmpp.bot.plugins.game.event;

import me.rkfg.xmpp.bot.plugins.game.IGameObject;
import me.rkfg.xmpp.bot.plugins.game.effect.IAttachDetachEffect;
import me.rkfg.xmpp.bot.plugins.game.effect.SleepEffect;
import me.rkfg.xmpp.bot.plugins.game.effect.SleepEffect.SleepType;
import me.rkfg.xmpp.bot.plugins.game.misc.TypedAttribute;

public class SetSleepEvent extends AbstractEvent {

    public static final String TYPE = "setsleep";

    public static final TypedAttribute<SleepType> SLEEP_ATTR = TypedAttribute.of("sleeptype");

    public SetSleepEvent(SleepType type, IGameObject source) {
        super(TYPE, source);
        setAttribute(SLEEP_ATTR, type);
        setAttribute(COMMENT, "Персонаж выбирает стратегию сна: " + type.getLocalized());
    }

    @Override
    public void apply() {
        getAttribute(SLEEP_ATTR).ifPresent(st -> {
            ((IAttachDetachEffect) target).attachEffect(new SleepEffect(st, source));
            super.apply();
        });
    }

}

package me.rkfg.xmpp.bot.plugins.game.event;

import me.rkfg.xmpp.bot.plugins.game.IGameObject;
import me.rkfg.xmpp.bot.plugins.game.effect.SleepEffect;
import me.rkfg.xmpp.bot.plugins.game.effect.SleepEffect.SleepType;
import me.rkfg.xmpp.bot.plugins.game.misc.TypedAttribute;

public class SetSleepEvent extends AbstractEvent {

    public static final String TYPE = "setsleep";

    public static final TypedAttribute<SleepType> SLEEP_ATTR = TypedAttribute.of("sleeptype");

    public SetSleepEvent(SleepType type, IGameObject source) {
        super(TYPE, source);
        setAttribute(SLEEP_ATTR, type);
        setAttribute(COMMENT, "Персонаж выбирает стратегию сна: " + type.getLocalized());
    }

    @Override
    public void apply() {
        getAttribute(SLEEP_ATTR).ifPresent(st -> {
            target.enqueueAttachEffect(new SleepEffect(st, source));
            super.apply();
        });
    }

}

Add sleep effect via event

Add sleep effect via event


package ru.spbau.bluecharm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;

public class CallsNotifier extends BroadcastReceiver {
	public static final String TAG = "CALLS_NOTIFIER";

	@Override
	public void onReceive(Context context, Intent intent) {
		IBinder binder = peekService(context, new Intent(context, BlueCharmService.class));
		if (binder != null) {
			Messenger messenger = new Messenger(binder);
			Message msg = Message.obtain(null, BlueCharmService.MSG_NOTIFY_LISTENERS, 0, 0);
			Bundle bundle = new Bundle();
			bundle.putString(null, intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
			msg.setData(bundle);
			try {
				messenger.send(msg);
			} catch (RemoteException e) {
				Log.e(TAG, e.getLocalizedMessage());
			}
		} else {
			Log.d(TAG, "BlueCharmService isn't running");
		}
	}
}

package ru.spbau.bluecharm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;

public class CallsNotifier extends BroadcastReceiver {
	public static final String TAG = "CALLS_NOTIFIER";

	@Override
	public void onReceive(Context context, Intent intent) {
		IBinder binder = peekService(context, new Intent(context, BlueCharmService.class));
		if (binder != null) {
			Log.d(TAG, "Intent received: " + intent.getStringExtra(TelephonyManager.EXTRA_STATE));
			if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) {
				Messenger messenger = new Messenger(binder);
				Message msg = Message.obtain(null, BlueCharmService.MSG_NOTIFY_LISTENERS, 0, 0);
				Bundle bundle = new Bundle();
				bundle.putString(null, "Call: " + intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
				msg.setData(bundle);
				try {
					messenger.send(msg);
				} catch (RemoteException e) {
					Log.e(TAG, e.getLocalizedMessage());
				}
			}
		} else {
			Log.d(TAG, "BlueCharmService isn't running");
		}
	}
}

Call prefix in a notification

Call prefix in a notification


package com.creatubbles.api.repository;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.creatubbles.api.model.AuthToken;
import com.creatubbles.api.response.ResponseCallback;

/**
 * @author Matthew Platek on 11.02.2016.
 */
public interface OAuthRepository {

    void authorize(ResponseCallback<AuthToken> callback);

    void authorize(String login, String password, ResponseCallback<AuthToken> callback);

    void setClientId(String clientId);

    void setClientSecret(String clientSecret);

    /**
     * Method used to retrieve an access token for one of current user's managed creators without their password.
     *
     * @param currentToken current user's access token
     * @param targetUserId the user for which to obtain an access token
     * @param groupId      (optional) limits further user switching to the given group
     */
    void switchUser(@NonNull AuthToken currentToken, @NonNull String targetUserId, @Nullable String groupId, ResponseCallback<AuthToken> callback);
}

package com.creatubbles.api.repository;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.creatubbles.api.model.AuthToken;
import com.creatubbles.api.response.ResponseCallback;

/**
 * @author Matthew Platek on 11.02.2016.
 */
public interface OAuthRepository {

    /**
     * Method used to obtain Application only access token.
     * This token will give you access to publicly available information and actions.
     * Use this type of access token if you want to retrieve content independent from any users.
     */
    void authorize(ResponseCallback<AuthToken> callback);

    /**
     * Method used to obtain User access token. User access tokens extend your access rights to allow your
     * application to also access content and actions which have restricted visibility and are available
     * for the user the access token was issued for. The user access token basically allows you to retrieve
     * content and execute actions on behalf of the user the token was issued for.
     */
    void authorize(String login, String password, ResponseCallback<AuthToken> callback);

    void setClientId(String clientId);

    void setClientSecret(String clientSecret);

    /**
     * Method used to retrieve an access token for one of current user's managed creators without their password.
     *
     * @param currentToken current user's access token
     * @param targetUserId the user for which to obtain an access token
     * @param groupId      (optional) limits further user switching to the given group
     */
    void switchUser(@NonNull AuthToken currentToken, @NonNull String targetUserId, @Nullable String groupId, ResponseCallback<AuthToken> callback);
}

Add JavaDoc to authorization methods

Add JavaDoc to authorization methods


package com.cloudant.sync.query;

/**
 * Created by tomblench on 28/09/2016.
 */

public class FieldSort {

    public final String field;
    public final Direction sort;

    public FieldSort(String field) {
        this.field = field;
        this.sort = Direction.ASCENDING;
    }

    public FieldSort(String field, Direction sort) {
        this.field = field;
        this.sort = sort;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        FieldSort fieldSort = (FieldSort) o;

        if (!field.equals(fieldSort.field)) {
            return false;
        }
        return sort == fieldSort.sort;

    }

    @Override
    public int hashCode() {
        int result = field.hashCode();
        result = 31 * result + sort.hashCode();
        return result;
    }

    @Override
    public String toString() {
        return "FieldSort{" +
                "field='" + field + '\'' +
                ", sort=" + sort +
                '}';
    }

    public enum Direction {
        ASCENDING,
        DESCENDING
    };

}

/*
 * Copyright (C) 2016 IBM Corp. All rights reserved.
 *
 * 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.cloudant.sync.query;

/**
 * Created by tomblench on 28/09/2016.
 */

public class FieldSort {

    public final String field;
    public final Direction sort;

    public FieldSort(String field) {
        this(field, Direction.ASCENDING);
    }

    public FieldSort(String field, Direction sort) {
        this.field = field;
        this.sort = sort;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        FieldSort fieldSort = (FieldSort) o;

        if (!field.equals(fieldSort.field)) {
            return false;
        }
        return sort == fieldSort.sort;

    }

    @Override
    public int hashCode() {
        int result = field.hashCode();
        result = 31 * result + sort.hashCode();
        return result;
    }

    @Override
    public String toString() {
        return "FieldSort{" +
                "field='" + field + '\'' +
                ", sort=" + sort +
                '}';
    }

    public enum Direction {
        ASCENDING,
        DESCENDING
    };

}

Implement feedback from rhys' comments

Implement feedback from rhys' comments


package org.synyx.urlaubsverwaltung.person.basedata;

import org.springframework.data.jpa.repository.JpaRepository;

interface PersonBasedataRepository extends JpaRepository<PersonBasedataEntity, Integer> {
}

package org.synyx.urlaubsverwaltung.person.basedata;

import org.springframework.data.repository.CrudRepository;

interface PersonBasedataRepository extends CrudRepository<PersonBasedataEntity, Integer> {
}

Replace with crud repository interface

Replace with crud repository interface


package protocolsupport.protocol.utils.spoofedata;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

import com.destroystokyo.paper.event.player.PlayerHandshakeEvent;

public class SpoofedDataParser {

	private static final List<Function<String, SpoofedData>> parsers = new ArrayList<>();

	static {
		if (isPaperHandshakeEvent()) {
			parsers.add(new PaperSpoofedDataParser());
		}
		parsers.add(new BungeeCordSpoofedDataParser());
	}

	public static SpoofedData tryParse(String data) {
		for (Function<String, SpoofedData> parser : parsers) {
			try {
				SpoofedData result = parser.apply(data);
				if (result != null) {
					return result;
				}
			} catch (Exception e) {
			}
		}
		return null;
	}

	private static boolean isPaperHandshakeEvent() {
		try {
			Class.forName(PlayerHandshakeEvent.class.getName());
			return true;
		} catch (ClassNotFoundException e) {
			return false;
		}
	}

}

package protocolsupport.protocol.utils.spoofedata;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

import com.destroystokyo.paper.event.player.PlayerHandshakeEvent;

public class SpoofedDataParser {

	private static final List<Function<String, SpoofedData>> parsers = new ArrayList<>();

	static {
		if (isPaperHandshakeEvent()) {
			parsers.add(new PaperSpoofedDataParser());
		}
		parsers.add(new BungeeCordSpoofedDataParser());
	}

	public static SpoofedData tryParse(String data) {
		for (Function<String, SpoofedData> parser : parsers) {
			try {
				SpoofedData result = parser.apply(data);
				if (result != null) {
					return result;
				}
			} catch (Exception e) {
			}
		}
		return null;
	}

	private static boolean isPaperHandshakeEvent() {
		try {
			Class.forName(PlayerHandshakeEvent.class.getName());
			return true;
		} catch (Throwable e) {
			return false;
		}
	}

}

Fix spoofed data parser init

Fix spoofed data parser init


package org.springframework.roo.addon.web.flow;

import org.springframework.roo.shell.CliAvailabilityIndicator;
import org.springframework.roo.shell.CliCommand;
import org.springframework.roo.shell.CliOption;
import org.springframework.roo.shell.CommandMarker;
import org.springframework.roo.support.lifecycle.ScopeDevelopmentShell;
import org.springframework.roo.support.util.Assert;

/**
 * Commands for the 'install web flow' add-on to be used by the ROO shell.
 *
 * @author Stefan Schmidt
 * @since 1.0
 *
 */
@ScopeDevelopmentShell
public class WebFlowCommands implements CommandMarker {

	private WebFlowOperations webFlowOperations;

	public WebFlowCommands(WebFlowOperations webFlowOperations) {
		Assert.notNull(webFlowOperations, "Jms operations required");
		this.webFlowOperations = webFlowOperations;
	}

	/**
	 * @return true if the "install web flow" command is available at this moment
	 */
	@CliAvailabilityIndicator("install web flow")
	public boolean isInstallWebFlowAvailable() {
		return webFlowOperations.isInstallWebFlowAvailable();
	}

	@CliCommand(value="install web flow", help="Install Spring Web Flow configuration artifacts into your project")
	public void installWebFlow(
			@CliOption(key={"flowName"}, mandatory=false, help="The name your web flow") String flowName) {
		webFlowOperations.installWebFlow(flowName);
	}
}

package org.springframework.roo.addon.web.flow;

import org.springframework.roo.shell.CliAvailabilityIndicator;
import org.springframework.roo.shell.CliCommand;
import org.springframework.roo.shell.CliOption;
import org.springframework.roo.shell.CommandMarker;
import org.springframework.roo.support.lifecycle.ScopeDevelopmentShell;
import org.springframework.roo.support.util.Assert;

/**
 * Commands for the 'install web flow' add-on to be used by the ROO shell.
 *
 * @author Stefan Schmidt
 * @since 1.0
 *
 */
@ScopeDevelopmentShell
public class WebFlowCommands implements CommandMarker {

	private WebFlowOperations webFlowOperations;

	public WebFlowCommands(WebFlowOperations webFlowOperations) {
		Assert.notNull(webFlowOperations, "Jms operations required");
		this.webFlowOperations = webFlowOperations;
	}

	/**
	 * @return true if the "install web flow" command is available at this moment
	 */
	@CliAvailabilityIndicator("install web flow")
	public boolean isInstallWebFlowAvailable() {
		return webFlowOperations.isInstallWebFlowAvailable();
	}

	@CliCommand(value="install web flow", help="Install Spring Web Flow configuration artifacts into your project")
	public void installWebFlow(
			@CliOption(key={"flowName"}, mandatory=false, help="The name for your web flow") String flowName) {
		webFlowOperations.installWebFlow(flowName);
	}
}

Create Spring Web Flow add-on

ROO-17: Create Spring Web Flow add-on


package fi.metacity.klmobi;

import com.googlecode.androidannotations.annotations.EApplication;

import android.app.Application;

@EApplication
public class MHApp extends Application {

	private String mToken = "";
	private Address mStartAddress;
	private Address mEndAddress;

	public String getToken() {
		return mToken;
	}

	public void setToken(String token) {
		mToken = token;
	}

	public Address getStartAddress() {
		return mStartAddress;
	}

	public void setStartAddress(Address address) {
		mStartAddress = address;
	}

	public Address getEndAddress() {
		return mEndAddress;
	}

	public void setEndAddress(Address address) {
		mEndAddress = address;
	}
}

package fi.metacity.klmobi;

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

import android.app.Application;

import com.googlecode.androidannotations.annotations.EApplication;

@EApplication
public class MHApp extends Application {

	private String mToken = "";
	private Address mStartAddress;
	private Address mEndAddress;

	private List<Route> mRoutes = new ArrayList<Route>();
	private String mDetailsXmlRequest = "";

	public String getToken() {
		return mToken;
	}

	public void setToken(String token) {
		mToken = token;
	}

	public Address getStartAddress() {
		return mStartAddress;
	}

	public void setStartAddress(Address address) {
		mStartAddress = address;
	}

	public Address getEndAddress() {
		return mEndAddress;
	}

	public void setEndAddress(Address address) {
		mEndAddress = address;
	}

	public List<Route> getRoutes() {
		return mRoutes;
	}

	public String getDetailsXmlRequest() {
		return mDetailsXmlRequest;
	}

	public void setDetailsXmlString(String xmlRequest) {
		mDetailsXmlRequest = xmlRequest;
	}
}

Add route list and xmlResponse

Add route list and xmlResponse


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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.jboss.jdeparser;

import static org.jboss.jdeparser.Tokens.*;

import java.io.IOException;

/**
 * @author David M. Lloyd
 */
class KeywordExprJStatement extends KeywordJStatement {

    private final JExpr expr;

    KeywordExprJStatement(final $KW keyword, final JExpr expr) {
        super(keyword);
        this.expr = expr;
    }

    JExpr getExpression() {
        return expr;
    }

    public void write(final SourceFileWriter writer) throws IOException {
        writeComments(writer);
        writer.write(getKeyword());
        writer.write(expr);
        writer.write($PUNCT.SEMI);
    }
}

/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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.jboss.jdeparser;

import static org.jboss.jdeparser.Tokens.*;

import java.io.IOException;

/**
 * @author David M. Lloyd
 */
class KeywordExprJStatement extends KeywordJStatement {

    private final JExpr expr;

    KeywordExprJStatement(final $KW keyword, final JExpr expr) {
        super(keyword);
        this.expr = expr;
    }

    JExpr getExpression() {
        return expr;
    }

    public void write(final SourceFileWriter writer) throws IOException {
        writeComments(writer);
        writer.write(getKeyword());
        writer.sp();
        writer.write(expr);
        writer.write($PUNCT.SEMI);
    }
}

Include a space after a return if an expression is used.


package DependencyRandomNumber;

import java.util.Random;

import com.continuuity.api.flow.flowlet.SourceFlowlet;
import com.continuuity.api.flow.flowlet.OutputCollector;
import com.continuuity.api.flow.flowlet.StreamsConfigurator;
import com.continuuity.api.flow.flowlet.Tuple;
import com.continuuity.api.flow.flowlet.TupleSchema;
import com.continuuity.api.flow.flowlet.builders.TupleBuilder;
import com.continuuity.api.flow.flowlet.builders.TupleSchemaBuilder;

public class RandomNumberSource extends SourceFlowlet {

  private Random random;

  @Override
  public void configure(StreamsConfigurator configurator) {
    TupleSchema out = new TupleSchemaBuilder().
        add("randomNumber", Long.class).
        create();
    configurator.getDefaultTupleOutputStream().setSchema(out);
  }

  @Override
  public void initialize() {
    super.initialize();
    this.random = new Random();
  }

  @Override
  public void generate(OutputCollector outputCollector) {
    long randomNumber = Math.abs(this.random.nextLong());
    Tuple randomNumberTuple = new TupleBuilder()
        .set("randomNumber", randomNumber)
        .create();
    outputCollector.add(randomNumberTuple);
  }
}

package DependencyRandomNumber;

import java.util.Random;

import com.continuuity.api.flow.flowlet.FlowletSpecifier;
import com.continuuity.api.flow.flowlet.SourceFlowlet;
import com.continuuity.api.flow.flowlet.OutputCollector;
import com.continuuity.api.flow.flowlet.Tuple;
import com.continuuity.api.flow.flowlet.TupleSchema;
import com.continuuity.api.flow.flowlet.builders.TupleBuilder;
import com.continuuity.api.flow.flowlet.builders.TupleSchemaBuilder;

public class RandomNumberSource extends SourceFlowlet {

  private Random random;

  @Override
  public void configure(FlowletSpecifier specifier) {
    TupleSchema out = new TupleSchemaBuilder().
        add("randomNumber", Long.class).
        create();
    specifier.getDefaultFlowletOutput().setSchema(out);
  }

  @Override
  public void initialize() {
    super.initialize();
    this.random = new Random();
  }

  @Override
  public void generate(OutputCollector outputCollector) {
    long randomNumber = Math.abs(this.random.nextLong());
    Tuple randomNumberTuple = new TupleBuilder()
        .set("randomNumber", randomNumber)
        .create();
    outputCollector.add(randomNumberTuple);
  }
}

Fix call to old flowlet API in example

Fix call to old flowlet API in example


package me.echeung.cdflabs.utils;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import me.echeung.cdflabs.R;

public class DividerItemDecoration extends RecyclerView.ItemDecoration {
    private Drawable mDivider;

    public DividerItemDecoration(Context context) {
        this.mDivider = ContextCompat.getDrawable(context, R.drawable.line_divider);
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();

        // Avoid last item and footer
        final int childCount = parent.getChildCount() - 2;
        if (childCount > 0) {
            for (int i = 0; i < childCount; i++) {
                final View child = parent.getChildAt(i);

                final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

                final int top = child.getBottom() + params.bottomMargin;
                final int bottom = top + mDivider.getIntrinsicHeight();

                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(c);
            }
        }
    }
}

package me.echeung.cdflabs.utils;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import me.echeung.cdflabs.R;

public class DividerItemDecoration extends RecyclerView.ItemDecoration {
    private Drawable mDivider;
    private int mPaddingLeft;

    public DividerItemDecoration(Context context) {
        this.mDivider = ContextCompat.getDrawable(context, R.drawable.line_divider);

        this.mPaddingLeft = 2 * (int) context.getResources().getDimension(R.dimen.regular_margin)
            + (int) context.getResources().getDimension(R.dimen.free_size);
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        final int left = parent.getPaddingLeft() + this.mPaddingLeft;
        final int right = parent.getWidth() - parent.getPaddingRight();

        // Avoid last item and footer
        final int childCount = parent.getChildCount() - 2;
        if (childCount > 0) {
            for (int i = 0; i < childCount; i++) {
                final View child = parent.getChildAt(i);

                final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

                final int top = child.getBottom() + params.bottomMargin;
                final int bottom = top + mDivider.getIntrinsicHeight();

                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(c);
            }
        }
    }
}

Add left padding to item decoration

Add left padding to item decoration


/*
 * Title: COP3404Project3Code
 * Author: Matthew Boyette
 * Date: 3/27/2015
 *
 * This program serves as the entry-point for Projects 3 & 4.
 * See SICXE_AssemblerProgram.java for the implementation.
 */

import api.util.sicxe.SICXE_AssemblerProgram;
import api.util.stdlib.StdOut;

public class COP3404Project3Code
{
	public static final void main(final String[] args)
	{
		SICXE_AssemblerProgram[] programs = new SICXE_AssemblerProgram[args.length];

		// Read in files as command-line arguments.
		if (args.length > 0)
		{
			for (int i = 0; i < args.length; i++)
			{
				programs[i] = new SICXE_AssemblerProgram(args[i]);
			}
		}
		else
		{
			StdOut.print("Usage:\n\n\tCOP3404Project3Code [File1] [File2] [File#] ...\n\n" +
				"Example:\n\n\tCOP3404Project3Code input test.txt source.asm\n\n");
		}
	}
}

/*
 * Title: COP3404Project3Code
 * Author: Matthew Boyette
 * Date: 3/27/2015
 *
 * This program serves as the entry-point for Projects 3 & 4.
 * See SICXE_AssemblerProgram.java for the implementation.
 */

import api.util.sicxe.SICXE_AssemblerProgram;
import api.util.stdlib.StdIn;
import api.util.stdlib.StdOut;

public class COP3404Project3Code
{
	public static final void main(final String[] args)
	{
		SICXE_AssemblerProgram[] programs = new SICXE_AssemblerProgram[Math.max(1, args.length)];

		// Read in file names given as command-line arguments.
		if (args.length > 0)
		{
			for (int i = 0; i < args.length; i++)
			{
				programs[i] = new SICXE_AssemblerProgram(args[i]);
			}
		}
		// Prompt the user for a file name if not given one.
		else
		{
			StdOut.print("Enter source file name: ");
			String fileName = StdIn.readString();

			if (fileName != null)
			{
				if (!fileName.isEmpty())
				{
					programs[0] = new SICXE_AssemblerProgram(fileName);
				}
			}
		}
	}
}

Allow Program To Prompt For File If Not Given One