/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * 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.jetbrains.python.validation;

import com.intellij.psi.MultiplePsiFilesPerDocumentFileViewProvider;
import com.intellij.psi.PsiFile;
import com.jetbrains.python.inspections.PythonVisitorFilter;
import org.jetbrains.annotations.NotNull;

/**
 * @author vlan
 */
public class PyMultiplePsiFilesVisitorFilter implements PythonVisitorFilter {
  @Override
  public boolean isSupported(@NotNull Class visitorClass, @NotNull PsiFile file) {
    if (visitorClass == StringLiteralQuotesAnnotator.class &&
        file.getViewProvider() instanceof MultiplePsiFilesPerDocumentFileViewProvider) {
      return false;
    }
    return true;
  }
}

Disable StringLiteralQuotesAnnotator for multi-PSI files (PY-11658)

Python string literals may be split by other (template) languages in
multi-PSI files resulting in string literals that have unmatched
quotes.


package tehnut.lib.mc.util;

import net.minecraft.util.math.AxisAlignedBB;

public class BoundHelper {

    public static AxisAlignedBB rotate(AxisAlignedBB bounds, AxisRotation rot) {
        return new AxisAlignedBB(
                rot.getX(bounds.minX, bounds.minZ), bounds.minY, rot.getX(bounds.maxX, bounds.maxZ),
                rot.getZ(bounds.minX, bounds.minZ), bounds.maxY, rot.getZ(bounds.maxX, bounds.maxZ)
        );
    }

    public enum AxisRotation {
        NONE(1, 0, 0, 1),
        CLOCKWISE_90(0, 1, -1, 0),
        OPPOSITE(-1, 0, 0, -1),
        COUNTERCLOCKWISE_90(0, -1, 1, 0);

        private final double xx, xz, zx, zz;

        AxisRotation(double xx, double xz, double zx, double zz) {
            this.xx = xx; this.xz = xz;
            this.zx = zx; this.zz = zz;
        }

        public final double getX(double x, double z) {
            return x * xx + z * xz;
        }

        public final double getZ(double x, double z) {
            return x * zx + z * zz;
        }
    }
}

Add utility for rotating AABBs

Add utility for rotating AABBs

Thanks paul.


package fr.esiea.windmeal.controller.exception.handler;

import fr.esiea.windmeal.model.exception.RestException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.logging.Logger;

/**
 * Copyright (c) 2013 ESIEA M. Labusquiere D. Déïs
 *

 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *

 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
@ControllerAdvice
public class ExceptionHandlerCtrl extends ResponseEntityExceptionHandler {

	private final static Logger LOGGER = Logger.getLogger("ExceptionHandlerCtrl");

	@ExceptionHandler(value = {RestException.class})
	protected ResponseEntity<Object> handleException(RestException ex, WebRequest request) {
		LOGGER.info("An exception was catch by spring mvc :" + ex.getClass() + " : " + ex.getMessage());
		Object model = ex.getModel();
		return new ResponseEntity<Object>(model, HttpStatus.valueOf(ex.getStatus()));
	}
}

Add an exception handler to Spring Mvc (handling only RestException


package org.biojava.nbio.phylo;

import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix;
import org.forester.phylogeny.Phylogeny;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Test for the evaluation of distance trees.
 *
 * @author Aleix Lafita
 *
 */
public class TestDistanceTreeEvaluator {

	@Test
	public void testErrorFree() throws Exception {

		// Create a perfect additive distance matrix
		BasicSymmetricalDistanceMatrix DM = new BasicSymmetricalDistanceMatrix(3);

		// dAB = 0.8, dBC = 0.4, dAC = 0.8
		for (int i = 0; i < 3; i++){
			char id = (char) ('A' + i);
			DM.setIdentifier(i, id + "");
			for (int j = i; j < 3; j++){
				if (i == j){
					DM.setValue(i, j, 0.0);
				}
				else if (i == 0) {
					DM.setValue(i, j, 0.8);
					DM.setValue(j, i, 0.8);
				} else {
					DM.setValue(i, j, 0.4);
					DM.setValue(j, i, 0.4);
				}
			}
		}

		BasicSymmetricalDistanceMatrix cloneDM = ForesterWrapper.cloneDM(DM);

		//Calculate error free tree and get the cv
		Phylogeny tree = TreeConstructor.distanceTree(cloneDM, TreeConstructorType.NJ);
		double cv = DistanceTreeEvaluator.evaluate(tree, DM);

		// Assert error free
		assertEquals(0.0, cv, 0.001);

	}
}

Create a Test for the distance tree evaluation


package org.xcolab.view.pages.contestmanagement.beans;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;

import java.io.Serializable;

public class BatchRegisterBean implements Serializable {

    private static final String EMAIL_REGEX =
            "(?:[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-zA-Z0-9-]*[a-zA-Z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";

    @NotBlank
    private String firstName;

    @NotBlank
    private String lastName;

    @Email(regexp = EMAIL_REGEX)
    @NotBlank
    private String email;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

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

    @Override
    public String toString() {
        return "BatchRegisterBean [firstName='" + firstName + "', lastName='" + lastName
                + "', email='" + email + "']";
    }

}

Add Bean for batch register on admin tab


// Copyright 2014 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.android_webview.test;

import android.test.suitebuilder.annotation.SmallTest;

import org.chromium.android_webview.AwContents;
import org.chromium.base.test.util.Feature;

/**
 * TestSuite for EME key systems.
 */
public class KeySystemTest extends AwTestBase {

    private TestAwContentsClient mContentsClient = new TestAwContentsClient();
    private AwContents mAwContents;

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        final AwTestContainerView testContainerView =
                createAwTestContainerViewOnMainSync(mContentsClient);
        mAwContents = testContainerView.getAwContents();
        enableJavaScriptOnUiThread(mAwContents);

        loadDataSync(mAwContents, mContentsClient.getOnPageFinishedHelper(),
            getKeySystemTestPage(), "text/html", false);
    }

    private String getKeySystemTestPage() {
        return "<html> <script>" +
                "function isKeySystemSupported(keySystem) {" +
                    "var video = document.createElement('video');" +
                    "return video.canPlayType('video/mp4', keySystem);" +
                "}" +
                "</script> </html>";
    }

    private String IsKeySystemSupported(String keySystem) throws Exception {
        return executeJavaScriptAndWaitForResult(mAwContents, mContentsClient,
                  "isKeySystemSupported('" + keySystem + "')");
    }

    @Feature({"AndroidWebView"})
    @SmallTest
    public void testSupportClearKeySystem() throws Throwable {
        assertEquals("\"maybe\"", IsKeySystemSupported("webkit-org.w3.clearkey"));
    }

    @Feature({"AndroidWebView"})
    @SmallTest
    public void testSupportWidevineKeySystem() throws Throwable {
        assertEquals("\"maybe\"", IsKeySystemSupported("com.widevine.alpha"));
    }

    @Feature({"AndroidWebView"})
    @SmallTest
    public void testNotSupportFooKeySystem() throws Throwable {
        assertEquals("\"\"", IsKeySystemSupported("com.foo.keysystem"));
    }
}

aw: Add EME key system tests in android_webview_instrumentation_tests.

Review URL: https://codereview.chromium.org/328713002

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@276932 0039d316-1c4b-4281-b951-d872f2087c98


// Copyright 2014 The Bazel Authors. 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.google.devtools.build.lib.events;

/**
 * Interface for reporting events during the build. It extends the {@link EventHandler} by also
 * allowing posting arbitrary objects on the event bus.
 */
public interface ExtendedEventHandler extends EventHandler {

  /** Interface for declaring events that can be posted via the extended event handler */
  public interface Postable {}

  /** Report arbitrary information over the evnt bus. */
  void post(Postable obj);
}

Add interface for extended reporting of events

Not in all situation, having an EventHandler allows detailed enough
reporting on events during the build. Therefore add a new interface
that additionally allows posting arbitrary objects on the event bus.

--
Change-Id: I6ff3eebcad5f36b52c38d3f7ac20df8af2706821
Reviewed-on: https://cr.bazel.build/8793
PiperOrigin-RevId: 148078891
MOS_MIGRATED_REVID=148078891


package com.googlecode.jslint4java.cli;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

import org.junit.Test;

import com.beust.jcommander.ParameterException;

public class CharsetConverterTest {

    private static final String UNKNOWN_CHARSET_NAME = "bob";
    private final CharsetConverter cc = new CharsetConverter();

    @Test
    public void testConvert() throws Exception {
        assertThat(cc.convert("UTF-8"), is(Charset.forName("UTF-8")));
    }

    @Test(expected = ParameterException.class)
    public void testIllegalCharsetName() throws Exception {
        cc.convert("!@#$%^&*(");
    }

    @Test(expected = ParameterException.class)
    public void testUnknownCharset() throws Exception {
        // We only want to run this test if we can guarantee that the charset _doesn't_ exist in the
        // system first. Otherwise, we'll just have to ignore this test.
        try {
            Charset.forName(UNKNOWN_CHARSET_NAME);
        } catch (UnsupportedCharsetException e) {
            // We're good to run the test.
            cc.convert(UNKNOWN_CHARSET_NAME);
        }
    }

}

Add a test for CharsetConverter.

Add a test for CharsetConverter.


package com.growthbeat.model;

import static org.junit.Assert.fail;

import org.junit.Test;

import com.growthbeat.BaseTest;
import com.growthbeat.GrowthbeatException;

public class ResourceTest extends BaseTest {

	@Test
	public void findById() {
		// Service credential is required.
		try {
			Resource resource = Resource.findById("Resource:Growthbeat", testCredential.getId());
			fail();
		} catch (GrowthbeatException e) {
		}
	}

	@Test
	public void create() {
		// Service credential is required.
		try {
			Resource resource = Resource.create("Resource:Growthbeat", "XXX", testCredential.getId());
			fail();
		} catch (GrowthbeatException e) {
		}
	}

	@Test
	public void deleteById() {
		// Service credential is required.
		try {
			Resource.deleteById("Resource:Growthbeat:XXX", testCredential.getId());
			fail();
		} catch (GrowthbeatException e) {
		}
	}

}

Add test of Resource model

Add test of Resource model


package com.reactnativenavigation.controllers;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.reactnativenavigation.NavigationApplication;

public abstract class SplashActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        NavigationApplication.instance.startReactContext();
        //TODO show fancy splash
        View view = new View(this);
        view.setBackgroundColor(Color.WHITE);
        setContentView(view);
    }
}

package com.reactnativenavigation.controllers;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.reactnativenavigation.NavigationApplication;

public abstract class SplashActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        NavigationApplication.instance.startReactContext();
        setSplashLayout();
    }

    private void setSplashLayout() {
        final int splashLayout = getSplashLayout();
        if (splashLayout > 0) {
            setContentView(splashLayout);
        } else {
            setDefaultSplashLayout();
        }
    }

    private void setDefaultSplashLayout() {
        View view = new View(this);
        view.setBackgroundColor(Color.WHITE);
        setContentView(view);
    }

    /**
     *
     * @return -1 if you don't need a splash layout
     */
    public abstract @LayoutRes int getSplashLayout();
}

Add option to set custom splash layout

Add option to set custom splash layout


package peergos.shared.user;

import java.nio.file.*;

/** This class stores locations of the different components of a user's profile
 *
 *  Each component is a separate file and can thus be shared or made public individually.
 */
public class ProfilePaths {

    public static final Path ROOT = Paths.get(".profile");
    private static final Path PHOTO = ROOT.resolve("photo");
    public static final Path PHOTO_HIGH_RES = PHOTO.resolve("highres");
    public static final Path BIO = ROOT.resolve("bio");
    public static final Path STATUS = ROOT.resolve("status");
    public static final Path FIRSTNAME = ROOT.resolve("firstname");
    public static final Path LASTNAME = ROOT.resolve("lastname");
    public static final Path PHONE = ROOT.resolve("phone");
    public static final Path EMAIL = ROOT.resolve("email");
    public static final Path WEBROOT = ROOT.resolve("webroot"); // The path in Peergos to this users web root

}

Set out structure for private profile

Set out structure for private profile


package flyway.paikkis;

import fi.nls.oskari.domain.map.view.Bundle;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.map.view.AppSetupServiceMybatisImpl;
import fi.nls.oskari.map.view.ViewService;
import fi.nls.oskari.util.FlywayHelper;
import org.flywaydb.core.api.migration.jdbc.JdbcMigration;
import org.json.JSONArray;
import org.json.JSONObject;

import java.sql.Connection;
import java.util.List;

/**
 * Replaces transport based wfs plugin with vector implementation
 */
public class V2_36__use_wfs_vector_layer_plugin implements JdbcMigration {

    private static final Logger LOG = LogFactory.getLogger(V2_36__use_wfs_vector_layer_plugin.class);
    private static final String BUNDLE_NAME = "mapfull";
    private static final String WFS_TRANSPORT_PLUGIN_ID = "Oskari.mapframework.bundle.mapwfs2.plugin.WfsLayerPlugin";
    private static final String WFS_VECTOR_PLUGIN_ID = "Oskari.wfsvector.WfsVectorLayerPlugin";

    private ViewService viewService;

    public void migrate(Connection connection) throws Exception {
        viewService = new AppSetupServiceMybatisImpl();
        List<Long> viewIds = FlywayHelper.getViewIdsForTypes(connection, "DEFAULT", "USER", "PUBLISHED");
        for (long id : viewIds) {
            updateView(connection, id);
        }
    }

    private void updateView (Connection connection, long viewId) throws Exception {
        Bundle mapfull = FlywayHelper.getBundleFromView(connection, BUNDLE_NAME, viewId);
        JSONObject config = mapfull.getConfigJSON();
        if (config == null) {
            return;
        }
        JSONArray plugins = config.optJSONArray("plugins");
        if (plugins == null) {
            return;
        }
        for (int i = 0; i < plugins.length(); i++) {
            JSONObject plugin = plugins.getJSONObject(i);
            String id = plugin.optString("id");
            if (id == null || !id.equals(WFS_TRANSPORT_PLUGIN_ID)) {
                continue;
            }
            plugin.put("id", WFS_VECTOR_PLUGIN_ID);
        }
        mapfull.setConfig(config.toString());
        viewService.updateBundleSettingsForView(viewId, mapfull);
    }
}

Migrate to mvt and vector based wfs plugin


package org.realityforge.replicant.example.server.service.tyrelll.replicate;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.interceptor.InterceptorBinding;

@Inherited
@Target( { ElementType.TYPE, ElementType.METHOD } )
@Retention( RetentionPolicy.RUNTIME )
@InterceptorBinding
public @interface Replicate
{
}

Add annotation used to mark EJBs that will have changes automagically replicated out


package com.github.sparkcaller.variantdiscovery;

import com.github.sparkcaller.BaseGATKProgram;
import com.github.sparkcaller.Utils;

public class RecalibrateVariants extends BaseGATKProgram {

    public RecalibrateVariants(String pathToReference, String extraArgs) {
        super("VariantRecalibrator", extraArgs);
        setReference(pathToReference);
    }

    public void recalibrateVariants(String pathToVcf) throws Exception {
        addArgument("-input", pathToVcf);
        addArgument("-recalFile", Utils.removeExtenstion(pathToVcf, "vcf") + "-recal.recal");
        addArgument("-tranchesFile", Utils.removeExtenstion(pathToVcf, "vcf") + "-tranches.tranches");

        executeProgram();
   }
}

[Genomics]: Create the class which will be used to obtain the targets which
requires variant recalibration.

Currently this is done sequentially, as I've yet to find a good way of
splitting the VCF files by chromosome.


/*******************************************************************************
 * 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.wink.common.internal.registry;

import java.lang.reflect.Field;
import java.util.concurrent.ConcurrentHashMap;

import junit.framework.TestCase;

import org.apache.wink.common.internal.application.ApplicationValidator;
import org.apache.wink.common.internal.lifecycle.LifecycleManagersRegistry;

public class ProvidersRegistryTest extends TestCase {

    /**
     * Tests that the providersCache object is and remains instanceof ConcurrentHashMap.
     *
     * ProvidersRegistry.MediaTypeMap uses type ConcurrentHashMap on the providersCache object to provide some lock protection on
     * the map when providers are dynamically added.  However, lock protection is already built into the ProvidersRegistry methods:
     * getContextResolver(), getMessageBodyReader(), and getMessageBodyWriter().
     *
     * However, the second protection (in the ProvidersRegistry methods) is for the cache itself which could be written to by two
     * different threads even if they both were getting a single MessageBodyReader (i.e. a cache value may be dropped and then two
     * threads come back later and try to write a new cache value).  Due to some weird HashMap properties, this can blow up in
     * weird ways.
     *
     * Thus, we need to ensure the providersCache continues to be instantiated with ConcurrentHashMap.
     */
    public void testProtectionModel() throws Exception {

        // I need the instantiated object providersCache in the abstract private nested class MediaTypeMap, so here we go!
        ProvidersRegistry providersRegistry = new ProvidersRegistry(new LifecycleManagersRegistry(), new ApplicationValidator());
        Field field = providersRegistry.getClass().getDeclaredField("messageBodyReaders");
        field.setAccessible(true);
        Object messageBodyReaders = field.get(providersRegistry);
        System.out.println(messageBodyReaders.getClass().getSuperclass().getName());
        Field field2 = messageBodyReaders.getClass().getSuperclass().getDeclaredField("providersCache");
        field2.setAccessible(true);
        Object providersCache = field2.get(messageBodyReaders);

        assertTrue(providersCache instanceof ConcurrentHashMap);
    }

    // TODO:  perhaps future tests should be added to actually exercise the providersCache code, but it would be an involved,
    // multi-threaded test that dynamically adds providers at just the right time to ensure no problems with
    // concurrent writes.

}

Test to ensure map types in ProvidersRegistry

Thanks Mike Rheinheimer for the contribution.

See [WINK-179]

git-svn-id: 00d204a5454029cb4c4f043d44e9809460a5ea01@815588 13f79535-47bb-0310-9956-ffa450edef68


/*
 * Copyright (C) 2011, Neticoa SAS France - Tous droits réservés.
 * Author(s) : Franck Bonin, Neticoa SAS France
 *
 * 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.codehaus.mojo;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.project.MavenProject;

/**
 * Add more source directories to the POM.
 *
 * @goal addsource
 * @phase initialize
 * @author Franck Bonin
 * @version $Id$
 * @since 0.0.5
 * @threadSafe
 */
public class AddSourceMojo extends AbstractMojo
{
    /**
     * directory were sources are
     *
     * @parameter
     * @since 0.0.4
     */
    private List sourceDirs = new ArrayList();

    /**
     * @parameter expression="${project}"
     * @required
     * @readonly
     * @since 0.0.5
     */
    private MavenProject project;

    public void execute()
    {
        getLog().info( "Cxx Maven Plugin AddSource " );
        Iterator it = sourceDirs.iterator();
        while(it.hasNext())
        {
            File source = new File( (String) it.next() );
            this.project.addCompileSourceRoot( source.getAbsolutePath() );
            getLog().info( "Source directory: \"" + source.getAbsolutePath() + "\" added to Maven Project." );
        }
    }
}

Revert "Revert "tracks multiple source dirs inside maven configuration with new goal addsource""

This reverts commit 2e51de58e3459e6ef193797b7386dbe18d1f709c.


package net.kencochrane.raven.sentrystub.unmarshaller;

import net.kencochrane.raven.sentrystub.event.Event;

import java.io.InputStream;

public interface Unmarshaller {
    Event unmarshall(InputStream source);
}

Create unmarshaller to extract an event from a stream


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

package org.openmhealth.shimmer.common.service;

import org.openmhealth.shimmer.common.domain.DataPointSearchCriteria;
import org.openmhealth.shimmer.common.domain.DataPointSearchResult;
import org.springframework.stereotype.Service;

/**
 * An implementation that assumes data points can be retrieved from third-parties by making requests to specific API
 * endpoints.
 *
 * @author Emerson Farrugia
 */
@Service
public class DataPointSearchServiceImpl implements DataPointSearchService {

    @Override
    public DataPointSearchResult findDataPoints(DataPointSearchCriteria criteria) {

        // TODO implement me
        return new DataPointSearchResult();
    }
}

Add a bare data point search service implementation


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

package com.google.gerrit.extensions.events;

import com.google.gerrit.extensions.annotations.ExtensionPoint;

import java.util.Properties;

/**
 * Notified whenever the garbage collector has run successfully on a project.
 */
@ExtensionPoint
public interface GarbageCollectorListener {
  public interface Event {
    /** @return The name of the project that has been garbage collected. */
    String getProjectName();

    /**
     * Properties describing the result of the garbage collection performed by
     * JGit
     *
     * @see org.eclipse.jgit.api.GarbageCollectCommand#call()
     */
    Properties getStatistics();
  }

  void onGarbageCollected(Event event);
}

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

package com.google.gerrit.extensions.events;

import com.google.gerrit.extensions.annotations.ExtensionPoint;

import java.util.Properties;

/**
 * Notified whenever the garbage collector has run successfully on a project.
 */
@ExtensionPoint
public interface GarbageCollectorListener {
  public interface Event {
    /** @return The name of the project that has been garbage collected. */
    String getProjectName();

    /**
     * Properties describing the result of the garbage collection performed by
     * JGit
     *
     * @see GarbageCollectCommand
     */
    Properties getStatistics();
  }

  void onGarbageCollected(Event event);
}

Fix @see to external class in api to allow compilation with Java 8

The recently added GarbageCollectorListener came with a @see to a JGit
class. While Java 7 did not error out on that, Java 8 does:

  [...]/events/GarbageCollectorListener.java:34: error: reference not found
     * @see org.eclipse.jgit.api.GarbageCollectCommand#call()
            ^

As Java 8's javadoc currently (1.8.0_45) even complains when adding a
“-link”, we work around the issue by transforming the @see to the
classname into a @see with a full <a/>.

Change-Id: I1c061d5219b4fe8818d3fca8a56b4a433aa557d4


package org.yakindu.sct.generator.core;

import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.xtext.generator.JavaIoFileSystemAccess;
import org.yakindu.sct.model.sgen.GeneratorEntry;

import com.google.inject.Inject;
import com.google.inject.Injector;

/**
 *  @author oliver bohl
 *
 */

public abstract class AbstractSGenGenerator implements ISCTGenerator {

	@Inject protected IWorkspaceRoot root;
	@Inject protected JavaIoFileSystemAccess fsa;
	@Inject protected Injector injector;

	protected abstract void generateContent(GeneratorEntry entry,
			JavaIoFileSystemAccess fsa, String targetProjectPath);

	public void generate(GeneratorEntry entry) {
		// Does actually nothing
		// generateInternal(entry);
	}

//	private void generateInternal(GeneratorEntry entry) {
//
//
//		 String targetProject = GeneratorUtils.getTargetProject(entry).toString();
//		 targetProject = targetProject.substring(1);
//
//		 IProject targetProjectRoot = root.getProject(targetProject);
//
//		 if(targetProjectRoot.exists() && targetProjectRoot.isOpen()){
//		 String targetFolder =
//		 GeneratorUtils.getTargetFolder(entry).toString();
//		 fsa.setOutputPath(IFileSystemAccess.DEFAULT_OUTPUT, targetFolder);
//
//		 String targetProjectPath = targetProject.replaceAll("\\.", "/");
//		 generateContent(entry, fsa, targetProjectPath);
//		 }
//	}

}

[YAKHMI-870] SCTUnit: Create abstract SGenGenerator for SCTUnit
-extracted same code from Generators to AbstractSCTUnitGenerator


/*******************************************************************************
 * Copyright (c) 2014 Codenvy, S.A.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Codenvy, S.A. - initial API and implementation
 *******************************************************************************/
package com.codenvy.ide.editor.codemirror.client.jso.hints;

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

/**
 * Callback for asynchronous completion proposal retrieval.
 */
public class CMHintCallback extends JavaScriptObject {

    protected CMHintCallback() {}

    public static final native CMHintCallback create(HintCallbackFunction callbackFun) /*-{
        return $entry(function(data) {
            callbackFun.@com.codenvy.ide.editor.codemirror.client.jso.hints.CMHintCallback.HintCallbackFunction::callback(Lcom/codenvy/ide/editor/codemirror/client/jso/hints/CMHintResultsOverlay;)(data);
        });
    }-*/;

    public final native void call(CMHintResultsOverlay data) /*-{
        this(data);
    }-*/;

    public interface HintCallbackFunction {
        void callback(CMHintResultsOverlay data);
    }
}

Add a callback for async proposals computation


/*
 * Copyright (c) 2016 Henry Addo
 *
 * 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.addhen.raiburari.processor.test;

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

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

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

/**
 * @author Henry Addo
 */
public class UserEntityTransformerTest {

    private UserEntityTransformer mUserEntityTransformer;

    private UserEntity mUserEntity;

    @Before
    public void setUp() {
        mUserEntityTransformer = new UserEntityTransformer();
        assertNotNull(mUserEntityTransformer);
        mUserEntity = new UserEntity("Foo Bar");
    }

    @Test
    public void testShouldTransformSingleEntity() {
        User user = mUserEntityTransformer.transform(mUserEntity);
        assertFields(user);
    }

    @Test
    public void testShouldTransformCollectionEntity() {
        List<User> users = mUserEntityTransformer
                .transform(Arrays.asList(mUserEntity, mUserEntity));
        assertNotNull(users);
        assertEquals(2, users.size());
        assertFields(users.get(0));
    }

    private void assertFields(User user) {
        assertNotNull(user);
        assertEquals("Foo Bar", user.fullName);
    }
}

Add test for transforming collection of entities


package net.imagej.ops.geom.geom3d.mesh;

import net.imagej.ops.Contingent;
import net.imagej.ops.Ops;
import net.imagej.ops.special.function.AbstractUnaryFunctionOp;

import org.scijava.plugin.Plugin;

/**
 * Generic implementation of {@code geom.smallestBoundingBox}.
 *
 * This paper looks promising: http://clb.demon.fi/minobb/minobb.html
 * c++ implementation:
 * https://github.com/juj/MathGeoLib/blob/master/src/Geometry/OBB.cpp (Licensed
 * under the Apache License, Version 2.0) example:
 * http://clb.demon.fi/minobb/test/ModelView.html
 *
 * @author Tim-Oliver Buchholz, University of Konstanz
 */
@Plugin(type = Ops.Geometric.SmallestEnclosingBoundingBox.class, label = "Geometric (3D): Smallest OBB")
public class DefaultSmallestOrientedBoundingBox extends AbstractUnaryFunctionOp<Mesh, Mesh>
		implements Contingent, Ops.Geometric.SmallestEnclosingBoundingBox {

	@Override
	public Mesh calculate(Mesh input) {
		return null;
	}

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

}

Add smallest oriented bounding box.

Add smallest oriented bounding box.


package reborncore.mixin.implementations.asmInjector;

import org.apache.logging.log4j.LogManager;
import reborncore.mixin.MixinManager;
import reborncore.mixin.implementations.prebaker.MixinPrebaker;

/**
 * Used by asm injector to load mixins into a jar at build time
 */
public class ASMInjectorSetupClass {

	public static void main(){
		MixinManager.logger = LogManager.getLogger();
		MixinManager.logger.info("Loading mixin manager");
		MixinManager.logger.info("Using dummy remapper");
		MixinManager.mixinRemaper = new MixinPrebaker.DummyRemapper();
		MixinManager.load();
	}

}

Add basic setup class for ASM Injector

Add basic setup class for ASM Injector


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

package com.jacksonandroidnetworking;

import android.app.Application;
import android.test.ApplicationTestCase;

import com.androidnetworking.AndroidNetworking;

import org.junit.Rule;

import okhttp3.mockwebserver.MockWebServer;

/**
 * Created by amitshekhar on 13/05/17.
 */

public class JacksonPostObjectApiTest extends ApplicationTestCase<Application> {

    @Rule
    public final MockWebServer server = new MockWebServer();

    public JacksonPostObjectApiTest() {
        super(Application.class);
    }

    @Override
    public void setUp() throws Exception {
        super.setUp();
        createApplication();
        AndroidNetworking.setParserFactory(new JacksonParserFactory());
    }

}

Prepare for Jackson POST Test

Prepare for Jackson POST Test


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

package griffon.core.i18n;

import griffon.util.ConfigReader;
import griffon.util.Environment;
import griffon.util.GriffonApplicationUtils;
import griffon.util.Metadata;
import groovy.lang.Script;
import groovy.util.ConfigObject;

import java.net.URL;
import java.util.*;

import static griffon.util.ConfigUtils.getConfigValue;

/**
 * @author Andres Almiray
 * @since 1.1.0
 */
public class GroovyScriptResourceBundle extends ResourceBundle {
    private final ConfigObject config;
    private final List<String> keys = new ArrayList<String>();

    public GroovyScriptResourceBundle(URL location) {
        this(null, location);
    }

    public GroovyScriptResourceBundle(Script script) {
        this(null, script);
    }

    public GroovyScriptResourceBundle(String script) {
        this(null, script);
    }

    public GroovyScriptResourceBundle(Class scriptClass) {
        this(null, scriptClass);
    }

    public GroovyScriptResourceBundle(ConfigReader reader, URL location) {
        this(resolveConfigReader(reader).parse(location));
    }

    public GroovyScriptResourceBundle(ConfigReader reader, Script script) {
        this(resolveConfigReader(reader).parse(script));
    }

    public GroovyScriptResourceBundle(ConfigReader reader, String script) {
        this(resolveConfigReader(reader).parse(script));
    }

    public GroovyScriptResourceBundle(ConfigReader reader, Class scriptClass) {
        this(resolveConfigReader(reader).parse(scriptClass));
    }

    private static ConfigReader resolveConfigReader(ConfigReader reader) {
        if (null != reader) return reader;
        reader = new ConfigReader();
        reader.registerConditionalBlock("environments", Environment.getCurrent().getName());
        reader.registerConditionalBlock("projects", Metadata.getCurrent().getApplicationName());
        reader.registerConditionalBlock("platforms", GriffonApplicationUtils.getFullPlatform());
        return reader;
    }

    private GroovyScriptResourceBundle(ConfigObject config) {
        this.config = config;
        keys.addAll(this.config.flatten(new LinkedHashMap()).keySet());
    }

    protected Object handleGetObject(String key) {
        Object value = getConfigValue(config, key, null);
        return null == value ? null : String.valueOf(value);
    }

    public Enumeration<String> getKeys() {
        final Iterator<String> keysIterator = keys.iterator();
        return new Enumeration<String>() {
            public boolean hasMoreElements() {
                return keysIterator.hasNext();
            }

            public String nextElement() {
                return keysIterator.next();
            }
        };
    }
}

Add a ConfigObject backed ResourceBundle implementation


package uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.transformer.completablevalue;

import uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.model.BasicOntology;
import uk.ac.ebi.quickgo.rest.model.CompletableValue;
import uk.ac.ebi.quickgo.rest.search.request.FilterRequest;
import uk.ac.ebi.quickgo.rest.search.request.converter.ConvertedFilter;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.nullValue;
import static uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.transformer.OntologyNameInjectorTestHelper
        .TEST_GO_ID;
import static uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.transformer.OntologyNameInjectorTestHelper
        .basicOntology;
import static uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.transformer.OntologyNameInjectorTestHelper
        .buildFilterRequestSuccessfully;
import static uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.transformer.OntologyNameInjectorTestHelper
        .injectValueSuccessfully;

/**
 * Created 11/04/17
 * @author Edd
 */
@RunWith(MockitoJUnitRunner.class)
public class OntologyNameInjectorTest {
    private OntologyNameInjector nameInjector;
    private CompletableValue completableValue;

    @Before
    public void setUp() {
        nameInjector = new OntologyNameInjector();
        completableValue = new CompletableValue(TEST_GO_ID);
    }

    @Test
    public void injectorIdIsGoName() {
        assertThat(nameInjector.getId(), is("goName"));
    }

    @Test
    public void responseValueIsInjectedToAnnotation() {
        ConvertedFilter<BasicOntology> stubConvertedFilter = new ConvertedFilter<>(basicOntology);
        assertThat(completableValue.value, is(nullValue()));

        nameInjector.injectValueFromResponse(stubConvertedFilter, completableValue);

        injectValueSuccessfully(completableValue.value);
    }

    @Test
    public void correctFilterRequestIsBuilt() {
        FilterRequest filterRequest = nameInjector.buildFilterRequest(completableValue);

        buildFilterRequestSuccessfully(filterRequest, nameInjector);
    }
}

Test the CompletableValue version of the ontology injector.


/*
 */
package org.datadryad.rest.storage.resolvers;

import org.datadryad.rest.storage.rdbms.DatabaseOrganizationStorageImpl;
import com.sun.jersey.spi.inject.SingletonTypeInjectableProvider;
import java.io.File;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
import org.datadryad.rest.storage.AbstractOrganizationStorage;
import org.datadryad.rest.storage.json.OrganizationJSONStorageImpl;

/**
 *
 * @author Dan Leehr <dan.leehr@nescent.org>
 */
@Provider
public class OrganizationStorageResolver extends SingletonTypeInjectableProvider<Context, AbstractOrganizationStorage> {
    private static final String PATH = "/tmp/dryad_rest";
    public OrganizationStorageResolver() {
        super(AbstractOrganizationStorage.class, new OrganizationJSONStorageImpl(new File(PATH)));
        File directory = new File(PATH);
        if(!directory.exists()) {
            directory.mkdir();
        }
    }
}

/*
 */
package org.datadryad.rest.storage.resolvers;

import org.datadryad.rest.storage.rdbms.DatabaseOrganizationStorageImpl;
import com.sun.jersey.spi.inject.SingletonTypeInjectableProvider;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
import org.datadryad.rest.storage.AbstractOrganizationStorage;

/**
 *
 * @author Dan Leehr <dan.leehr@nescent.org>
 */
@Provider
public class OrganizationStorageResolver extends SingletonTypeInjectableProvider<Context, AbstractOrganizationStorage> {
    public OrganizationStorageResolver() {
        super(AbstractOrganizationStorage.class, new DatabaseOrganizationStorageImpl("/opt/dryad/config/dspace.cfg"));
    }
}

Revert "Switched organization storage back to JSON"

This reverts commit 0a1fcfbea514419bd72bfda0c37cd57479e1b491.


/*-
 * Copyright (c) 2012 Diamond Light Source Ltd.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */

package org.eclipse.dawnsci.analysis.api.fitting.functions;

/**
 * A unimodal function (i.e. has one peak)
 */
public interface IPeak extends IFunction {

	/**
	 * Returns the peak position for that peak
	 *
	 * @return peak position
	 */
	public double getPosition();

	/**
	 * Returns the full width half maximum of a peak
	 *
	 * @return FWHM
	 */
	public double getFWHM();

	/**
	 * Returns the area under the peak
	 *
	 * @return area under peak
	 */
	public double getArea();

	/**
	 * @return the height of the peak ( y at getPosition() )
	 */
	public double getHeight();

}

Move interface to API plugin

Move interface to API plugin


/*
 * Copyright  1999-2004 The Apache Software Foundation.
 *
 *  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.apache.xml.security.signature;

import org.w3c.dom.Node;

/**
 * An interface to tell to the c14n if a node is included or not in the output
 * @author raul
 *
 */
public interface NodeFilter {
	/**
	 * Tells if a node must be outputed in c14n.
	 * @param n
	 * @return true if node must be outputed, false otherwise.
	 */
	public boolean isNodeInclude(Node n);

}

Refactor the way we handle c14n of nodesets

git-svn-id: c5bb8e2b15dc16fd1aec0e5653c08870c9ddec7d@351347 13f79535-47bb-0310-9956-ffa450edef68


package study.hard.javalib.nativelib;

import static org.junit.Assert.*;

import org.junit.Test;

import study.hard.javalib.entity.User;

public class CallByReferenceVSCallByValueTest {

	private void foo(User user) {
		System.out.println("A user in the foo: " + user.getName());
		assertEquals("James", user.getName());

		user = new User("Tomas", 31);
		System.out.println("A User in the foo: " + user.getName());
		assertEquals("Tomas", user.getName());
	}

	private void bar(User user) {
		System.out.println("A user in the bar: " + user.getName());
		user.setName("Tomas");
		System.out.println("A User in the bar: " + user.getName());
	}

	@Test
	public void test1() {
		User user = new User("James", 29);

		System.out.println("user: " + user.getName());
		foo(user);
		System.out.println("user: " + user.getName());
	}

	@Test
	public void test2() {
		User user = new User("James", 29);

		System.out.println("user: " + user.getName());
		bar(user);
		System.out.println("user: " + user.getName());
	}

}

Add test case that compares 'call by reference vs. call by value'.


package org.jetbrains.plugins.groovy.springloaded;

import com.intellij.debugger.PositionManager;
import com.intellij.debugger.PositionManagerFactory;
import com.intellij.debugger.engine.DebugProcess;

/**
 * Factory for position manager to debug classes reloaded by com.springsource.springloaded
 * @author Sergey Evdokimov
 */
public class SpringLoadedPositionManagerFactory extends PositionManagerFactory {

  @Override
  public PositionManager createPositionManager(final DebugProcess process) {
    try {
      if (process.getVirtualMachineProxy().classesByName("com.springsource.loaded.agent.SpringLoadedAgent").size() > 0
          || process.getVirtualMachineProxy().classesByName("org.springsource.loaded.agent.SpringLoadedAgent").size() > 0) {
        return new SpringLoadedPositionManager(process);
      }
    }
    catch (Exception ignored) {
      // Some problem with virtual machine.
    }

    return null;
  }
}

package org.jetbrains.plugins.groovy.springloaded;

import com.intellij.debugger.PositionManager;
import com.intellij.debugger.PositionManagerFactory;
import com.intellij.debugger.engine.DebugProcess;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.psi.JavaPsiFacade;

/**
 * Factory for position manager to debug classes reloaded by com.springsource.springloaded
 * @author Sergey Evdokimov
 */
public class SpringLoadedPositionManagerFactory extends PositionManagerFactory {

  @Override
  public PositionManager createPositionManager(final DebugProcess process) {
    AccessToken accessToken = ApplicationManager.getApplication().acquireReadActionLock();
    try {
      JavaPsiFacade facade = JavaPsiFacade.getInstance(process.getProject());
      if (facade.findPackage("com.springsource.loaded") != null || facade.findPackage("org.springsource.loaded") != null) {
        return new SpringLoadedPositionManager(process);
      }
    }
    finally {
      accessToken.finish();
    }

    try {
      // Check spring loaded for remote process
      if (process.getVirtualMachineProxy().classesByName("com.springsource.loaded.agent.SpringLoadedAgent").size() > 0
          || process.getVirtualMachineProxy().classesByName("org.springsource.loaded.agent.SpringLoadedAgent").size() > 0) {
        return new SpringLoadedPositionManager(process);
      }
    }
    catch (Exception ignored) {
      // Some problem with virtual machine.
    }

    return null;
  }
}

Support spring loaded for remote process.


/*
* 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.plugins.document.util;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

import org.junit.Test;

public class UTF8EncoderTest {

    private static char[] SURROGATE_PAIR = Character.toChars(0x1f4a9);

    @Test
    public void encodeValid() throws IOException {

        // a a-umlaut euro plane-1-char
        String test = "a \u00E4 \u20ac " + new String(SURROGATE_PAIR);

        byte[] withStringClass = test.getBytes(StandardCharsets.UTF_8);
        byte[] withUtilsClass = UTF8Encoder.encodeAsByteArray(test);
        assertArrayEquals(withStringClass, withUtilsClass);
        assertEquals(test, new String(withUtilsClass, StandardCharsets.UTF_8));
    }

    @Test
    public void encodeInValid() {

        // a a-umlaut euro plane-1-char, second char in surrogate pair missing
        String test = "a \u00E4 \u20ac " + SURROGATE_PAIR[0];

        try {
            UTF8Encoder.encodeAsByteArray(test);
            fail("expected encoding to fail");
        } catch (IOException expected) {
            // expected
        }
    }

    @Test
    public void encodeMultiThreaded() throws InterruptedException {

        int tc = 20;

        Thread[] threads = new Thread[tc];

        for (int i = 0; i < tc; i++) {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    // encode and decode 100 random UUID strings
                    for (int j = 0; j < 100; j++) {
                        String test = UUID.randomUUID().toString();
                        String roundtripped = null;
                        try {
                            byte[] bytes = UTF8Encoder.encodeAsByteArray(test);
                            roundtripped = new String(bytes, StandardCharsets.UTF_8);
                        } catch (IOException exignored) {
                        }
                        assertEquals(test, roundtripped);
                    }

                }
            });
        }
        for (int i = 0; i < tc; i++) {
            threads[i].start();
        }
        for (int i = 0; i < tc; i++) {
            threads[i].join();
        }
    }
}

OAK-7268: Create charset encoding utility that detects malformed input

(add test coverage)

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


package org.jboss.shamrock.jpa.runtime.graal.caffeine;

import com.oracle.svm.core.annotate.Alias;
import com.oracle.svm.core.annotate.RecomputeFieldValue;
import com.oracle.svm.core.annotate.TargetClass;

@TargetClass(className = "com.github.benmanes.caffeine.cache.UnsafeRefArrayAccess")
public final class CaffeineReplacements {

    @Alias
    @RecomputeFieldValue(kind = RecomputeFieldValue.Kind.ArrayIndexShift, declClass = Object[].class)
    public static int REF_ELEMENT_SHIFT;

}

Fix the segfault happening when write buffering is enabled


/*
 * Copyright 2018-present Open Networking Foundation
 *
 * 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.onosproject.openstacknetworking.cli;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.google.common.collect.Lists;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.openstacknetworking.api.OpenstackRouterService;
import org.openstack4j.model.network.RouterInterface;
import org.openstack4j.openstack.networking.domain.NeutronRouter;

import java.util.List;

import static org.onosproject.openstacknetworking.util.OpenstackNetworkingUtil.modelEntityToJson;
import static org.onosproject.openstacknetworking.util.OpenstackNetworkingUtil.prettyJson;

/**
 * Lists Openstack router interfaces.
 */
@Service
@Command(scope = "onos", name = "openstack-router-interfaces",
        description = "Lists all OpenStack routers interfaces")
public class OpenstackRouterInterfaceListCommand extends AbstractShellCommand {
    private static final String FORMAT = "%-40s%-40s%-40s%-40s%-40s";

    private final OpenstackRouterService routerService =
            AbstractShellCommand.get(OpenstackRouterService.class);

    @Override
    protected void doExecute() {
        List<RouterInterface> routerInterfaces =
                Lists.newArrayList(routerService.routerInterfaces());

        if (outputJson()) {
            print("%s", json(routerInterfaces));
        } else {
            print(FORMAT, "ID", "RouterName", "SubnetID", "PortID", "TenantID");
            for (RouterInterface routerInterface: routerInterfaces) {
                print(FORMAT, routerInterface.getId(),
                        routerService.router(routerInterface.getId()),
                        routerInterface.getSubnetId(),
                        routerInterface.getPortId(),
                        routerInterface.getTenantId());
            }
        }
    }

    private String json(List<RouterInterface> routerInterfaces) {
        ObjectMapper mapper = new ObjectMapper();
        ArrayNode result = mapper.createArrayNode();
        for (RouterInterface routerInterface: routerInterfaces) {
            result.add(modelEntityToJson(routerInterface, NeutronRouter.class));
        }
        return prettyJson(mapper, result.toString());
    }
}

Add a CLI to list up openstack router interfaces

Change-Id: I4569c36f773079385f776d50178a321876c8800d


package net.engin33r.luaspigot.lua;

import net.engin33r.luaspigot.lua.type.LuaEvent;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;

import java.util.Arrays;

import static org.luaj.vm2.LuaValue.NIL;

/**
 * Utility class for creating Varargs from arrays.
 */
public class VarargBuilder {
    public static Varargs build(LuaValue... values) {
        return new Varargs() {
            @Override
            public LuaValue arg(int i) {
                return values.length < i ? NIL : values[i-1];
            }

            @Override
            public int narg() {
                return values.length;
            }

            @Override
            public LuaValue arg1() {
                return arg(0);
            }

            @Override
            public Varargs subargs(int start) {
                return VarargBuilder.build(Arrays
                        .copyOfRange(values, start, values.length-1));
            }
        };
    }
}

Add utility class for creating Varargs values


package com.boundary.sdk;

import java.io.File;

import org.apache.camel.Exchange;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Before;
import org.junit.Test;

/**
 *
 * @version $Revision$
 */
public class RawEventToBoundaryEvent extends CamelTestSupport {

    @Produce(uri = TEST_IN)
    private ProducerTemplate producerTemplate;

	private static final String TEST_IN="direct:in";

	@Before
    public void setUp() throws Exception {
        super.setUp();
    }

    @Override
    protected RouteBuilder[] createRouteBuilders() throws Exception {
    	RouteBuilder[] routes = new RouteBuilder[2];

    	// Create the Boundary Event Route
		BoundaryEventRoute boundary = new BoundaryEventRoute();
		// Configure our properties

		routes[0] = boundary;

		routes[1] = new RouteBuilder(){
            @Override
            public void configure() throws Exception {
                from(TEST_IN)
                .marshal().serialization()
                .to(BoundaryRouteBuilder.DEFAULT_EVENT_TO_URI);
            }
        };

        return routes;
    }

    @Test
    public void testDefaultEvent() throws Exception {
    	RawEvent event = RawEvent.getDefaultEvent();

    	producerTemplate.sendBody(event);

        Thread.sleep(2000);
    }

}

Add JUnit test for validating RawEvents to Boundary


package org.twig.functional;

import org.junit.Assert;
import org.junit.Test;
import org.twig.Environment;
import org.twig.exception.TwigException;
import org.twig.loader.HashMapLoader;

import java.util.HashMap;

public class RenderFunctionsTests extends FunctionalTests {
    @Test
    public void canRenderContextObjectMethods() throws TwigException {
        TestClass foo = new TestClass();
        HashMap<String, String> templates = new HashMap<>();
        templates.put("foo.twig", "{{ foo.getSomething() }}");
        setupEnvironment(templates);

        Assert.assertEquals("Method return vale should be rendered", "foo", environment.render("foo.twig"));
    }

    private class TestClass {
        public String getSomething() {
            return "foo";
        }
    }
}

Add test for rendering object methods

Add test for rendering object methods


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

package org.springframework.test.context.env;

import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.*;

/**
 * Integration tests for {@link TestPropertySource @TestPropertySource} support with
 * inlined properties that overrides properties files.
 *
 * @author Sam Brannen
 * @since 4.3
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TestPropertySource(locations = "explicit.properties", properties = "explicit = inlined")
public class InlinedPropertiesOverridePropertiesFilesTestPropertySourceTests {

	@Autowired
	Environment env;

	@Value("${explicit}")
	String explicit;

	@Test
	public void inlinedPropertyOverridesValueFromPropertiesFile() {
		assertEquals("inlined", env.getProperty("explicit"));
		assertEquals("inlined", this.explicit);
	}

	@Configuration
	static class Config {

		@Bean
		public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
			return new PropertySourcesPlaceholderConfigurer();
		}
	}

}

Verify inlined props override files in @TestPropertySource

This commit introduces a test to demonstrate that inlined properties
override properties loaded from Properties files in
@TestPropertySource.

Issue: SPR-14068


/*******************************************************************************
 * Copyright (c) 1998, 2007 Oracle. All rights reserved.
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0, which accompanies this distribution
 * and is available at http://www.eclipse.org/legal/epl-v10.html.
 *
 * Contributors:
 *     Oracle - initial API and implementation from Oracle TopLink
 ******************************************************************************/
package org.eclipse.persistence.testing.sdo.helper.xmlhelper.threadsafety;

import junit.framework.Test;
import junit.framework.TestSuite;

public class SDOXMLHelperThreadSafetyTestSuite {

	public SDOXMLHelperThreadSafetyTestSuite() {
    }

    public static void main(String[] args) {
        junit.textui.TestRunner.run(suite());
    }

    public static Test suite() {
        TestSuite suite = new TestSuite("All XMLHelper Thread Safety Tests");

        suite.addTest(new TestSuite(SDOXMLHelperThreadSafetyTestCases.class));

        return suite;
    }

}

Test suite for thread safety tests

Test suite for thread safety tests


package org.hibernate.collection.internal;

import java.util.ArrayList;

/**
 * This is how we tell GWT to serialize the hibernate class PersistentBag.
 * We don't need the real implementation in the UI, and since we only use
 * the List interface, the transformation to ArrayList is valid.
 */
public class PersistentBag extends ArrayList {

}

Allow GWT to work with Hibernate

webadmin: Allow GWT to work with Hibernate

Hibernate collections serialization is not supported by GWT.
This patch provides serialization techniques to some commonly
user Hibernate collections, so that objects can be serialized
to the browser.

Change-Id: I54f2b14a54d3e90c3e27746b024e2260131bc13d
Signed-off-by: c5542eaf646591383f6b59a9b598fa7b32c0cb99@redhat.com <c5542eaf646591383f6b59a9b598fa7b32c0cb99@redhat.com>


/*-
 * Copyright (c) 2014 Mikolaj Izdebski
 *
 * 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.lbzip2.impl;

import static org.junit.Assert.assertEquals;
import static org.lbzip2.impl.Utils.insertion_sort;

import java.util.Arrays;
import java.util.Random;

import org.junit.Test;

/**
 * @author Mikolaj Izdebski
 */
public class UtilsTest
{
    private final Random r = new Random( 7541 );

    @Test
    public void testInsertionSort()
    {
        for ( int nRep = 0; nRep < 1000; nRep++ )
        {
            int n = 50 + r.nextInt( 100 );
            long[] A = new long[n];
            for ( int i = 0; i < n; i++ )
                A[i] = r.nextLong();

            long[] B = new long[n];
            System.arraycopy( A, 0, B, 0, n );
            Arrays.sort( B );

            insertion_sort( A, 0, n );

            for ( int i = 0; i < n; i++ )
                assertEquals( B[n - i - 1], A[i] );
        }
    }
}

Add unit test for insertion sort

Add unit test for insertion sort


/*
 * (C) Copyright 2018 Boni Garcia (http://bonigarcia.github.io/)
 *
 * 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 io.github.bonigarcia.wdm.test;

import static org.junit.Assert.assertTrue;

import java.net.MalformedURLException;
import java.net.URL;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

/**
 * Test with Android device.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.0.0
 */
public class AndroidTest {

    private WebDriver driver;

    @Before
    public void setupTest() throws MalformedURLException {
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("platformName", "android");
        capabilities.setCapability("browserName", "browser");
        capabilities.setCapability("deviceName", "Samsung Galaxy S6");
        driver = new RemoteWebDriver(new URL("http://172.17.0.1:4444/wd/hub"),
                capabilities);
    }

    @After
    public void teardown() {
        if (driver != null) {
            driver.quit();
        }
    }

    @Test
    public void test() {
        driver.get("https://en.wikipedia.org/wiki/Main_Page");
        assertTrue(
                driver.getTitle().equals("Wikipedia, the free encyclopedia"));
    }

}

Include test for Android device using RemoteWebDriver


package com.skraylabs.poker.model;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.Test;

public class CardTest {

  @Test
  public void testGetRank() {
    // Set up
    Card card = new Card(Rank.Ace, Suit.Clubs);
    // Exercise
    Rank rank = card.getRank();
    // Verify
    Rank expectedRank = Rank.Ace;
    assertThat(rank, equalTo(expectedRank));
  }

  @Test
  public void testGetSuit() {
    // Set up
    Card card = new Card(Rank.Eight, Suit.Diamonds);
    // Exercise
    Suit suit = card.getSuit();
    // Verify
    Suit expectedSuit = Suit.Diamonds;
    assertThat(suit, equalTo(expectedSuit));
  }

}

Add some tests for Card class.

Add some tests for Card class.


package org.micromanager.nativegui;

import javax.swing.JFileChooser;
import java.io.File;

public class NativeGUI {
  public static String runMDABrowser(String startDirectory) {
         JFileChooser fc = new JFileChooser();
         fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
         fc.setSelectedFile(new File(startDirectory));
         int retVal = fc.showOpenDialog(null);
         if (retVal == JFileChooser.APPROVE_OPTION) {
            return fc.getSelectedFile().getAbsolutePath();
         } else {
            return "";
        }
  }

}

Put this file back in, needed in Windows.

git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@5030 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd


package liquibase.sqlgenerator.core;

import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import liquibase.database.Database;
import liquibase.database.core.MySQLDatabase;
import liquibase.database.typeconversion.TypeConverterFactory;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.statement.core.InsertOrUpdateStatement;

/**
 *
 * @author Carles
 */
public class InsertOrUpdateGeneratorMySQL extends InsertOrUpdateGenerator {
    @Override
    public boolean supports(InsertOrUpdateStatement statement, Database database) {
         return database instanceof MySQLDatabase;
    }

    @Override
    protected String getInsertStatement(InsertOrUpdateStatement insertOrUpdateStatement, Database database, SqlGeneratorChain sqlGeneratorChain) {
        StringBuffer sql = new StringBuffer(super.getInsertStatement(insertOrUpdateStatement, database, sqlGeneratorChain));
        String updateSql = super.getUpdateStatement(insertOrUpdateStatement, database, "", sqlGeneratorChain);

        sql.deleteCharAt(sql.lastIndexOf(";"));
        sql.append("ON DUPLICATE KEY UPDATE ");
        String[] pkFields=insertOrUpdateStatement.getPrimaryKey().split(",");
        HashSet<String> hashPkFields = new HashSet<String>(Arrays.asList(pkFields));
        for(String columnKey:insertOrUpdateStatement.getColumnValues().keySet())
        {
            if (!hashPkFields.contains(columnKey)) {
                sql.append(columnKey).append(" = ");
                sql.append(convertToString(insertOrUpdateStatement.getColumnValue(columnKey),database));
                sql.append(",");
            }
        }
        sql.deleteCharAt(sql.lastIndexOf(","));

        System.out.println("SQL :" + sql.toString());

        return sql.toString();
    }

    @Override
    protected String getUpdateStatement(InsertOrUpdateStatement insertOrUpdateStatement, Database database, String whereClause, SqlGeneratorChain sqlGeneratorChain) {
        return "";
    }

    @Override
    protected String getRecordCheck(InsertOrUpdateStatement insertOrUpdateStatement, Database database, String whereClause) {
        return "";
    }

    @Override
    protected String getElse(Database database) {
        return "";
    }

    private String convertToString(Object newValue, Database database) {
        String sqlString;
        if (newValue == null || newValue.toString().equals("") || newValue.toString().equalsIgnoreCase("NULL")) {
            sqlString = "NULL";
        } else if (newValue instanceof String && database.shouldQuoteValue(((String) newValue))) {
            sqlString = "'" + database.escapeStringForDatabase(newValue.toString()) + "'";
        } else if (newValue instanceof Date) {
            sqlString = database.getDateLiteral(((Date) newValue));
        } else if (newValue instanceof Boolean) {
            if (((Boolean) newValue)) {
                sqlString = TypeConverterFactory.getInstance().findTypeConverter(database).getBooleanType().getTrueBooleanValue();
            } else {
                sqlString = TypeConverterFactory.getInstance().findTypeConverter(database).getBooleanType().getFalseBooleanValue();
            }
        } else {
            sqlString = newValue.toString();
        }
        return sqlString;
    }
}

Support to loadUpdateDate for MySQL using "INSERT .... ON DUPLICATE KEY UPDATE" syntax.

git-svn-id: a91d99a4c51940524e539abe295d6ea473345dd2@1572 e6edf6fb-f266-4316-afb4-e53d95876a76


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

package org.openmhealth.schema.domain.omh;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;

/**
 * A unit of a signal-to-noise ratio.
 *
 * @author Emerson Farrugia
 * @version 1.0
 * @see geoposition
 */
public enum SignalToNoiseRatioUnit implements Unit {

    DECIBEL("dB");

    private String schemaValue;
    private static final Map<String, SignalToNoiseRatioUnit> constantsBySchemaValue = new HashMap<>();

    static {
        for (SignalToNoiseRatioUnit constant : values()) {
            constantsBySchemaValue.put(constant.getSchemaValue(), constant);
        }
    }

    SignalToNoiseRatioUnit(String schemaValue) {
        this.schemaValue = schemaValue;
    }

    @Override
    @JsonValue
    public String getSchemaValue() {
        return this.schemaValue;
    }

    @Nullable
    @JsonCreator
    public static SignalToNoiseRatioUnit findBySchemaValue(String schemaValue) {
        return constantsBySchemaValue.get(schemaValue);
    }
}

Add an enum for SNR units

Add an enum for SNR units


package org.realityforge.arez.doc.examples.observables;

import org.realityforge.arez.Observable;

public class ObservableExample
{
  private Observable<Integer> _valueObservable;
  private int _value;

  public int getValue()
  {
    _valueObservable.reportObserved();
    return _value;
  }

  public void setValue( final int value )
  {
    if ( value != _value )
    {
      _value = value;
      _valueObservable.reportChanged();
    }
  }
}

Add java code referenced in documentation


package org.apache.aries.subsystem.core.internal;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

import java.net.MalformedURLException;

import org.junit.Test;

public class LocationTest {
	@Test
	public void testAnyLocationString() {
		String locationStr = "anyLocation";
		try {
			Location location = new Location(locationStr);
			assertNull("Wrong symbolic name", location.getSymbolicName());
			assertEquals("Wrong value", locationStr, location.getValue());
			assertNull("Wrong version", location.getVersion());
			try {
				location.open();
				fail("Opening a location that does not represent a URL should fail");
			}
			catch (MalformedURLException e) {
				// Okay
			}
			catch (Throwable t) {
				t.printStackTrace();
				fail("Wrong exception");
			}
		}
		catch (Throwable t) {
			t.printStackTrace();
			fail("Any location string must be supported");
		}
	}
}

Test support for any location string.

Test support for any location string.

git-svn-id: f3027bd689517dd712b868b0d3f5f59c3162b83d@1397359 13f79535-47bb-0310-9956-ffa450edef68


package com.shunix.scavenger.log;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;

/**
 * This class represent a crash
 * Created by shunix on 15-2-2.
 */
public class Crash {
    protected Throwable mException;
    protected Context mContext;
    private StringBuilder mBuilder;

    public Crash(Throwable throwable, Context context) {
        this.mException = throwable;
        this.mContext = context;
    }

    @Override
    public String toString() {
        if (mBuilder != null) {
            return mBuilder.toString();
        }
        mBuilder = new StringBuilder();
        mBuilder.append(getPackageInfo());
        mBuilder.append(getDeviceInfo());
        if (mException != null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                mException.printStackTrace(new PrintStream(baos));
                mBuilder.append(new String(baos.toByteArray()));
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (baos != null) {
                    try {
                        baos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return mBuilder.toString();
    }

    protected String getPackageInfo() {
        String packageInfoString = "";
        if (mContext == null) {
            return "";
        }
        PackageManager packageManager = mContext.getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder
                    .append("Package Name: ")
                    .append(packageInfo.packageName)
                    .append(" Package Version Name: ")
                    .append(packageInfo.versionName)
                    .append(" Package Version Code: ")
                    .append(packageInfo.versionCode)
                    .append("\n");
            packageInfoString = stringBuilder.toString();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return packageInfoString;
    }

    protected String getDeviceInfo() {
        if (mContext == null) {
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder
                .append("Device Model: ")
                .append(Build.MODEL)
                .append(" Android Version: ")
                .append(Build.VERSION.RELEASE)
                .append("\n");
        return stringBuilder.toString();
    }
}

Add a class to represent crash

Add a class to represent crash


/*
 * ServeStream: A HTTP stream browser/player for Android
 * Copyright 2010 William Seemann
 *
 * 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 net.sourceforge.servestream.transport;

public class ProtocolFactory {

	public static final String HTTP_HINT = "hostname/path";
	public static final String HTTPS_HINT = "hostname/path";

	/**
	 * Default constructor
	 */
	public ProtocolFactory() {

	}

	/**
	 * Returns a hint for the protocol passed in
	 *
	 * @param protocol The protocol
	 * @return String The hint for the protocol
	 */
	public static String getProtocolHint(String protocol) {
		if (protocol.equals("http")) {
			return HTTP_HINT;
		} else if (protocol.equals("https")) {
			return HTTPS_HINT;
		} else {
			return null;
		}
	}

	/**
	 *
	 *
	 * @param scheme
	 * @return String Protocol
	 */
	public static String getProtocol(String scheme) {
		if (scheme.equals("http")) {
			return "http://";
		} else if (scheme.equals("https")) {
			return "https://";
		} else {
			return null;
		}
	}

}

Add class for protocol spinner

Add class for protocol spinner

git-svn-id: 617ad4860dbc5b8a793a5b07e81e5b5684aade50@38 b8d320ad-ce4d-463a-8333-51e6c77ad906


package learn_to_code.java_api.net.local_multiple_times_one_connection;

import learn_to_code.java_api.net.local_one_time_one_connection.SimpleNetworkProtocol;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * This server will open port 10000 on your machine (Can be changed obviously), accept a SINGLE connection but do not shutdown
 * after the first connection ends. If multiple clients try to connect simultaneously, they will be blocked,
 * because a client connection cannot proceed unless the server makes a call to accept() method
 * <br>
 * The communication is defined by {@link SimpleNetworkProtocol} class
 * Client can be {@link learn_to_code.java_api.net.local_one_time_one_connection.SingleConnectionLocalClient}
 */
public class SingleConnectionNoShutdownLocalServer {
    public static void main(String[] args) throws IOException {

        try (ServerSocket serverSocket = new ServerSocket(10000)) {
            while (true) {

                /* This call will block, until first user finishes his requests, after this,
                 * server will return to waiting state and wait for another user.
                 * The only way to shutdown this server is to kill JVM where it is running.
                 * Most of the time, you'll need to implement a better way to shutdown server
                 * something like polling on server-shutdown signal once in a while
                 */
                createAndKeepConnection(serverSocket);

            }
        }
    }

    private static void createAndKeepConnection(ServerSocket serverSocket) {
        try (
                Socket clientSocket = serverSocket.accept();
                PrintWriter toClient =
                        new PrintWriter(clientSocket.getOutputStream(), true);
                BufferedReader fromClient = new BufferedReader(
                        new InputStreamReader(clientSocket.getInputStream()));
        ) {
            SimpleNetworkProtocol protocol = new SimpleNetworkProtocol(fromClient, toClient);

            protocol.initialMessage();
            /* This call will not return unless user ends connection with 'bye' response */
            protocol.proceedData();
            protocol.lastMessage();

        } catch (IOException e) {
            System.out.println("Connection error!");
            e.printStackTrace();
        }
    }
}

Add local server-client over socket example where server does not shutdown instantly, when the connection ends


package org.lantern;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import org.apache.commons.io.IOUtils;

import com.google.common.base.Charsets;

public class HostSpoofingTest {

    public static void main(final String... args) throws Exception {
        final SSLSocket sock = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
        sock.connect(new InetSocketAddress("www.google.com", 443), 10000);

        OutputStream os = null;
        try {
            os = sock.getOutputStream();
            writeHttpRequest(os);
            readResponse(sock.getInputStream());
        } finally {
            IOUtils.closeQuietly(os);
        }
    }

    private static void readResponse(InputStream inputStream) throws IOException {
        /*
        BufferedReader br = null;
        br = new BufferedReader(new InputStreamReader(inputStream));
        String cur = br.readLine();
        while (!StringUtils.isEmpty(cur)) {
            System.err.println(cur);
            cur = br.readLine();
        }
        */
        final byte[] body = new byte[1200];
        inputStream.read(body);
        System.err.println(new String(body, "UTF-8"));
    }

    private static void writeHttpRequest(final OutputStream os) throws IOException {
        os.write("GET / HTTP/1.1\r\n".getBytes(Charsets.UTF_8));
        //os.write("Host: lantern-compute-engine-test.c.o59bxf5.internal\r\n".getBytes(Charsets.UTF_8));
        //os.write("Host: 23.236.59.9\r\n".getBytes(Charsets.UTF_8));
        os.write("Host: 10.240.200.99\r\n".getBytes(Charsets.UTF_8));
        os.write("\r\n".getBytes(Charsets.UTF_8));
    }

}

Test for host spoofing on different sites


package org.apache.markt.leaks.java2d;

import org.apache.markt.leaks.LeakBase;

/**
 * Java 5
 *  - update 22 - leaks
 * Java 6
 *  - update =<00 - leaks
 *    ??? when was this fixed ???
 *  - update >=45 - no leak
 * Java 7 - no leak
 * Java 8 - no leak
 */
public class Java2dDisposerThreadLeak extends LeakBase {

    public static void main(String[] args) {
        Java2dDisposerThreadLeak java2dDisposerThreadLeak = new Java2dDisposerThreadLeak();
        java2dDisposerThreadLeak.doLeakTest();
    }

    @Override
    protected void createLeakingObjects() {
        try {
            Class.forName("sun.java2d.Disposer");
        } catch (ClassNotFoundException e) {
            RuntimeException r = new RuntimeException();
            r.initCause(e);
            throw r;
        }
    }

    @Override
    protected void cleanUpLeakingObjects() {
        // None
    }
}

Add Java 2D Disposer thread leak test

Add Java 2D Disposer thread leak test


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package epfc.cours3449;

/**
 *
 * @author jedepaepe
 */
public class lesson11 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
    }

}

Create first class in repository

Create first class in repository


package org.twig.functional;

import org.junit.Assert;
import org.junit.Test;
import org.twig.exception.TwigException;

import java.util.HashMap;

public class RenderLogicTests extends FunctionalTests {
    @Test
    public void canRenderPlainBoolean() throws TwigException {
        HashMap<String, String> templates = new HashMap<>();
        templates.put("foo.twig", "{{ true }}");
        setupEnvironment(templates);

        Assert.assertEquals("Bool should render text bool", "true", environment.render("foo.twig"));
    }
}

Add a functional test suite for logic

Add a functional test suite for logic


// Copyright 2019 Google LLC
//
// 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
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.sps;

import com.google.sps.data.ProductDetectionData;

/**
 * Interface for ProductDetectionAPIImpl, respective FakeProductDetectionAPI, used for testing.
 */
public interface ProductDetectionAPI {
  public ProductDetectionData detectProductPhotoContent(byte[] imageBytes) throws PhotoDetectionException;
}

Create interface for product detection classes


package org.opendroidphp.app.common.tasks;

import org.opendroidphp.app.Constants;
import org.opendroidphp.app.common.shell.SH;

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

public class DestroyServer implements Runnable {

    @Override
    public void run() {

        initialize();
    }

    protected void initialize() {

        List<String> command = new ArrayList<String>();

        command.add(Constants.BUSYBOX_SBIN_LOCATION + " killall lighttpd");
        command.add(Constants.BUSYBOX_SBIN_LOCATION + " killall mysqld");
        command.add(Constants.BUSYBOX_SBIN_LOCATION + " killall php");

        SH.run(command);
    }
}

Destroy the running web servers process

Destroy the running web servers process


import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        if(!scan.hasNext()) {
            System.out.print(0);
            scan.close();
            return;
        }

        String sentence = scan.nextLine().trim();
        scan.close();

        String delimeters = "[ !,?._'@]+";
        String[] tokens = sentence.split(delimeters);
        System.out.println(tokens.length);
        for (String token: tokens) {
            System.out.println(token);
        }
    }
}

Solve java string tokens, test case 9 stinks


package Utils;

import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;

public class Player {
	public static void playStream(AudioInputStream inputStream) {
		AudioFormat format = inputStream.getFormat();
		DataLine.Info info = new DataLine.Info(Clip.class, format);
		Clip clip;

		try {
			clip = (Clip) AudioSystem.getLine(info);
			clip.open(inputStream);
			clip.start();
		} catch (LineUnavailableException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Add utility class for playing streams

Add utility class for playing streams


package com.aviras.mrassistant.models;

import io.realm.RealmModel;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;

/**
 * Unit for medicines
 * <p/>
 * Created by ashish on 8/6/16.
 */
public class Unit extends RealmObject {

    @PrimaryKey
    private int id;

    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Add unit model to represent unit for medicine


package org.cyclops.commoncapabilities.modcompat.tconstruct.capability.work;

import org.cyclops.commoncapabilities.api.capability.work.IWorker;
import slimeknights.tconstruct.gadgets.tileentity.TileDryingRack;

/**
 * Worker capability for the drying rack.
 * @author rubensworks
 */
public class TileDryingRackWorker implements IWorker {

    private final TileDryingRack tile;

    public TileDryingRackWorker(TileDryingRack tile) {
        this.tile = tile;
    }

    @Override
    public boolean hasWork() {
        return !tile.getStackInSlot(0).isEmpty();
    }

    @Override
    public boolean canWork() {
        return true;
    }

}

Add worker capability for TCon's Drying Rack


/**
 * Copyright (C) 2009-2013 FoundationDB, LLC
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.foundationdb.util;

public class FileTestUtils {

    public static void printClickableFile(String filename, String suffix, int lineNumber) {
        if (filename != null) {
            try {
                System.err.println("  at " + filename.replace("src/test/resources/", "").
                        replaceFirst("/([^/]+.)$", "($1." + suffix + ":" + lineNumber + ")").replaceAll("/", "."));
                // for those running from maven or elsewhere
                System.err.println("  aka: " + filename + "." + suffix + ":" + lineNumber);
            } catch (Exception e) {
                System.err.println("Tried to write filename but failed: " +
                        filename + "." + suffix + ":" + lineNumber + " -- " + e.getMessage());
            }
        } else {
            System.err.println("NULL filename");
        }
    }
}

/**
 * Copyright (C) 2009-2013 FoundationDB, LLC
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.foundationdb.util;

public class FileTestUtils {

    public static void printClickableFile(String filename, String suffix, int lineNumber) {
        if (filename != null) {
            System.err.println("  at " + filename.replace("src/test/resources/", "").
                    replaceFirst("/([^/]+.)$", "($1." + suffix + ":" + lineNumber + ")").replaceAll("/", "."));
            // for those running from maven or elsewhere
            System.err.println("  aka: " + filename + "." + suffix + ":" + lineNumber);
        } else {
            System.err.println("NULL filename");
        }
    }
}

Revert "Made printClickableFilename more robust"

This reverts commit 39dfa9311ba4c1eb470384540a516feeb7f8f6b3.


import java.time.LocalDateTime;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * This class is used to generate sample data.
 */
public class Generator {

    private static final String[] levels = {"VERBOSE", "DEBUG", "INFO", "WARN", "ERROR"};

    private static final String[] classes =
            {"com.amadeus.DataMap", "org.bigfoot.Toe", "java.util.Map", "com.fizzy.Twizzer", "org.whynot.Question",
                    "com.enterprise.Business"};

    private static final String[] nouns = {"file", "message", "id", "PNR", "reservation", "service", "class", "object"};

    private static final String[] participates = {"found", "deleted", "inserted", "retrieved", "read", "downloaded", "accessed", "returned"};

    private static final String[] verbs = {"cannot be", "was", "has been", "could not be"};

    private final Random random = new Random();

    public static void main(String[] args) {
        new Generator().generate();
    }

    private void generate() {
        String format = "<%s> <%s> <%s> <> <%s;jsessionid=%s>%n";

        for (int i = 0; i < 600; i++) {
            System.out.printf(format, LocalDateTime.now(), rand(levels), rand(classes), randMsg(), randSID());
        }
    }

    private String rand(String[] array) {
        return array[random.nextInt(array.length)];
    }

    private String randMsg() {
        return String.format("The %s %s %s", rand(nouns), rand(verbs), rand(participates));
    }

    private String randSID() {
        return random.ints(16, 0, 0xFFFF).mapToObj(Integer::toHexString).collect(Collectors.joining());
    }
}

Add log generator to have test data

Add log generator to have test data