package com.codahale.metrics;

import static java.lang.Math.min;

/**
 * A {@link Reservoir} implementation backed by a sliding window that stores the last {@code N}
 * measurements.
 */
public class SlidingWindowReservoir implements Reservoir {
    private final long[] measurements;
    private boolean fullWindow;
    private long count;

    /**
     * Creates a new {@link SlidingWindowReservoir} which stores the last {@code size} measurements.
     *
     * @param size the number of measurements to store
     */
    public SlidingWindowReservoir(int size) {
        this.measurements = new long[size];
        this.count = 0;
    }

    @Override
    public synchronized int size() {
    	if(fullWindow){
    		return measurements.length;
    	}else{
    		return (int) min(count, measurements.length);
    	}
    }

    @Override
    public synchronized void update(long value) {
        measurements[(int) count++] = value;
    	if(count >= measurements.length){
    		count = 0;
    		fullWindow = true;
    	}
    }

    @Override
    public Snapshot getSnapshot() {
        final long[] values = new long[size()];
        for (int i = 0; i < values.length; i++) {
            synchronized (this) {
                values[i] = measurements[i];
            }
        }
        return new Snapshot(values);
    }
}

package com.codahale.metrics;

import static java.lang.Math.min;

/**
 * A {@link Reservoir} implementation backed by a sliding window that stores the last {@code N}
 * measurements.
 */
public class SlidingWindowReservoir implements Reservoir {
    private final long[] measurements;
    private long count;

    /**
     * Creates a new {@link SlidingWindowReservoir} which stores the last {@code size} measurements.
     *
     * @param size the number of measurements to store
     */
    public SlidingWindowReservoir(int size) {
        this.measurements = new long[size];
        this.count = 0;
    }

    @Override
    public synchronized int size() {
        return (int) min(count, measurements.length);
    }

    @Override
    public synchronized void update(long value) {
        measurements[(int) (count++ % measurements.length)] = value;
    }

    @Override
    public Snapshot getSnapshot() {
        final long[] values = new long[size()];
        for (int i = 0; i < values.length; i++) {
            synchronized (this) {
                values[i] = measurements[i];
            }
        }
        return new Snapshot(values);
    }
}

Update fix per ceetav's comments.

Update fix per ceetav's comments.


/*
 * Created by Michael Carrara <michael.carrara@breadwallet.com> on 5/31/18.
 * Copyright (c) 2018 Breadwinner AG.  All right reserved.
 *
 * See the LICENSE file at the project root for license information.
 * See the CONTRIBUTORS file at the project root for a list of contributors.
 */
package com.breadwallet.crypto.events.walletmanager;

import android.support.annotation.Nullable;

import com.google.common.base.Optional;

import java.util.Date;

public final class WalletManagerSyncProgressEvent implements WalletManagerEvent {

    private final double percentComplete;

    @Nullable
    private final Date timestamp;

    public WalletManagerSyncProgressEvent(double percentComplete, @Nullable Date timestamp) {
        this.percentComplete = percentComplete;
        this.timestamp = timestamp;
    }

    public double getPercentComplete() {
        return percentComplete;
    }

    public Optional<Date> getTimestamp() {
        return Optional.fromNullable(timestamp);
    }

    @Override
    public <T> T accept(WalletManagerEventVisitor<T> visitor) {
        return visitor.visit(this);
    }
}

/*
 * Created by Michael Carrara <michael.carrara@breadwallet.com> on 5/31/18.
 * Copyright (c) 2018 Breadwinner AG.  All right reserved.
 *
 * See the LICENSE file at the project root for license information.
 * See the CONTRIBUTORS file at the project root for a list of contributors.
 */
package com.breadwallet.crypto.events.walletmanager;

import android.support.annotation.Nullable;

import com.google.common.base.Optional;

import java.util.Date;

public final class WalletManagerSyncProgressEvent implements WalletManagerEvent {

    private final float percentComplete;

    @Nullable
    private final Date timestamp;

    public WalletManagerSyncProgressEvent(float percentComplete, @Nullable Date timestamp) {
        this.percentComplete = percentComplete;
        this.timestamp = timestamp;
    }

    public float getPercentComplete() {
        return percentComplete;
    }

    public Optional<Date> getTimestamp() {
        return Optional.fromNullable(timestamp);
    }

    @Override
    public <T> T accept(WalletManagerEventVisitor<T> visitor) {
        return visitor.visit(this);
    }
}

CORE-504: Update Java progress events to use floats


package com.vaenow.appupdate.android;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

/**
 * Created by LuoWen on 2015/10/27.
 */
public class CheckAppUpdate extends CordovaPlugin {
    public static final String TAG = "CheckAppUpdate";

    private UpdateManager updateManager = null;

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
            throws JSONException {

        if (action.equals("checkAppUpdate")) {
            getUpdateManager(args, callbackContext).checkUpdate();
            return true;
        }
        callbackContext.error(Utils.makeJSON(Constants.NO_SUCH_METHOD, "no such method: " + action));
        return false;
    }

    public UpdateManager getUpdateManager(JSONArray args, CallbackContext callbackContext)
            throws JSONException {

        if (this.updateManager == null) {
            this.updateManager = new UpdateManager(this.cordova.getActivity(), this.cordova);
        }

        return this.updateManager.options(args, callbackContext);
    }
}

package com.vaenow.appupdate.android;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.Manifest;
import android.support.v4.app.ActivityCompat;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

/**
 * Created by LuoWen on 2015/10/27.
 */
public class CheckAppUpdate extends CordovaPlugin {
    public static final String TAG = "CheckAppUpdate";

    private UpdateManager updateManager = null;

    // Storage Permissions
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE };

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
            throws JSONException {

        if (action.equals("checkAppUpdate")) {
            verifyStoragePermissions(this.cordova.getActivity());
            getUpdateManager(args, callbackContext).checkUpdate();
            return true;
        }
        callbackContext.error(Utils.makeJSON(Constants.NO_SUCH_METHOD, "no such method: " + action));
        return false;
    }

    public UpdateManager getUpdateManager(JSONArray args, CallbackContext callbackContext)
            throws JSONException {

        if (this.updateManager == null) {
            this.updateManager = new UpdateManager(this.cordova.getActivity(), this.cordova);
        }

        return this.updateManager.options(args, callbackContext);
    }

    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
        Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
            REQUEST_EXTERNAL_STORAGE);
        }
    }
}

Handle android EXTERNAL_STORAGE permissions in M

Depend on
 https://www.npmjs.com/package/cordova-plugin-android-support-v4


package ca.corefacility.bioinformatics.irida.web.controller.thymeleaf;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * The Thymeleaf portion of the web project is powered by an AngularJS single-page application. This controller is
 * responsible for only responding with a Thymeleaf index page, then the AngularJS application takes over and queries
 * the server for resources using the REST api.
 */
@Controller
@RequestMapping("/**")
public class RootController {
    @RequestMapping
    public String getRoot() {
        return "index";
    }
}

package ca.corefacility.bioinformatics.irida.web.controller.thymeleaf;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * The Thymeleaf portion of the web project is powered by an AngularJS single-page application. This controller is
 * responsible for only responding with a Thymeleaf index page, then the AngularJS application takes over and queries
 * the server for resources using the REST api.
 */
@Controller
public class RootController {
    private static final Logger logger = LoggerFactory.getLogger(RootController.class);

    /**
     * Get the index for any request that does not contain the string "css", "js",
     * or "font" for thymeleaf to render.
     * @return the name of the index page
     */
    @RequestMapping(value = {"{path:(?!css|js|font).*$}", "{path:(?!css|js|font).*$}/**", "/"})
    public String getRoot() {
        logger.debug("Loading index.");
        return "index";
    }
}

Load the index page for *all* requests (except those that should be handled as resources by spring).


package myproject1;

public class HelloWorld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.print("Hello World!");
	}

}

package myproject1;

public class HelloWorld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.print("Hello World! 日本語追加");
	}

}

Change print text with Japanese.

Change print text with Japanese.


package io.quarkus.dynamodb.runtime;

import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;

@ConfigRoot(phase = ConfigPhase.RUN_TIME)
public class DynamodbConfig {

    /**
     * Enable DynamoDB service endpoint discovery.
     */
    @ConfigItem
    public boolean enableEndpointDiscovery;

    /**
     * AWS service configurations
     */
    @ConfigItem
    public AwsConfig aws;

    /**
     * SDK client configurations
     */
    @ConfigItem(name = ConfigItem.PARENT)
    public SdkConfig sdk;

    /**
     * Apache HTTP client transport configuration
     */
    @ConfigItem
    public ApacheHttpClientConfig syncClient;

    /**
     * Netty HTTP client transport configuration
     */
    @ConfigItem
    public NettyHttpClientConfig asyncClient;
}

package io.quarkus.dynamodb.runtime;

import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;

@ConfigRoot(phase = ConfigPhase.RUN_TIME)
public class DynamodbConfig {

    /**
     * Enable DynamoDB service endpoint discovery.
     */
    @ConfigItem
    public boolean enableEndpointDiscovery;

    /**
     * SDK client configurations
     */
    @ConfigItem(name = ConfigItem.PARENT)
    public SdkConfig sdk;

    /**
     * AWS service configurations
     */
    @ConfigItem
    public AwsConfig aws;

    /**
     * Apache HTTP client transport configuration
     */
    @ConfigItem
    public ApacheHttpClientConfig syncClient;

    /**
     * Netty HTTP client transport configuration
     */
    @ConfigItem
    public NettyHttpClientConfig asyncClient;
}

Reorder config groups for better documentation


/*
 * Copyright 2016 higherfrequencytrading.com
 *
 * 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.openhft.chronicle.bytes.util;

import net.openhft.chronicle.bytes.Bytes;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/*
 * Created by Peter Lawrey on 17/09/15.
 */
public class StringInternerBytesTest {

    @Test
    public void testIntern() {
        @NotNull StringInternerBytes si = new StringInternerBytes(128);
        for (int i = 0; i < 100; i++) {
            Bytes b = Bytes.from("key" + i);
            si.intern(b, (int) b.readRemaining());
        }
        assertEquals(82, si.valueCount());
    }
}

/*
 * Copyright 2016 higherfrequencytrading.com
 *
 * 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.openhft.chronicle.bytes.util;

import net.openhft.chronicle.bytes.Bytes;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/*
 * Created by Peter Lawrey on 17/09/15.
 */
public class StringInternerBytesTest {

    @Test
    public void testIntern() {
        @NotNull StringInternerBytes si = new StringInternerBytes(128);
        for (int i = 0; i < 100; i++) {
            Bytes b = Bytes.from("key" + i);
            si.intern(b, (int) b.readRemaining());
        }
        assertEquals(86, si.valueCount());
    }
}

Improve test coverage and deprecate some methods.


package com.skogsrud.halvard.springmvc.spike.controller;

import com.skogsrud.halvard.springmvc.spike.tomcat.Server;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.net.ServerSocket;

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

public class HelloWorldControllerIT {
    private static Server server;
    private static int port;
    private static OkHttpClient client;

    @BeforeClass
    public static void beforeClass() throws Exception {
        port = findRandomOpenPort();
        server = new Server(port);
        server.start();
        client = new OkHttpClient();
    }

    @AfterClass
    public static void afterClass() throws Exception {
        server.stop();
    }

    @Test
    public void testHelloWorld() throws Exception {
        Request request = new Request.Builder()
                .url("http://localhost:" + port + "/app/hello")
                .build();
        Response response = client.newCall(request).execute();
        assertThat(response.body().string(), equalTo("Hello world"));
    }

    private static int findRandomOpenPort() throws IOException {
        try (ServerSocket socket = new ServerSocket(0)) {
            return socket.getLocalPort();
        }
    }
}

package com.skogsrud.halvard.springmvc.spike.controller;

import com.skogsrud.halvard.springmvc.spike.tomcat.Server;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.net.ServerSocket;

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

public class HelloWorldControllerIT {
    private static Server server;
    private static int port;
    private static OkHttpClient client;

    @BeforeClass
    public static void beforeClass() throws Exception {
        port = findRandomOpenPort();
        server = new Server(port);
        server.start();
        client = new OkHttpClient();
    }

    @AfterClass
    public static void afterClass() throws Exception {
        server.stop();
    }

    @Test
    public void testHelloWorld() throws Exception {
        Request request = new Request.Builder()
                .url("http://localhost:" + port + "/app/hello")
                .build();
        Response response = client.newCall(request).execute();
        assertThat(response.code(), equalTo(200));
        assertThat(response.body().string(), equalTo("Hello world"));
    }

    private static int findRandomOpenPort() throws IOException {
        try (ServerSocket socket = new ServerSocket(0)) {
            return socket.getLocalPort();
        }
    }
}

Add assert for response status code

Add assert for response status code


/*
 * (C) Copyright 2017 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;

import java.io.IOException;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

public class ExceptionTest {

    @ExtendWith(IgnoreIOExceptionExtension.class)
    @Test
    public void firstTest() throws IOException {
        throw new IOException("IO Exception");
    }

    @Disabled
    @Test
    public void secondTest() throws IOException {
        throw new IOException("My IO Exception");
    }

}

/*
 * (C) Copyright 2017 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;

import java.io.IOException;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

public class ExceptionTest {

    @RegisterExtension
    static IgnoreIOExceptionExtension ignoreIOExceptionExtension = new IgnoreIOExceptionExtension();

    @Test
    public void firstTest() throws IOException {
        throw new IOException("IO Exception");
    }

    @Test
    public void secondTest() throws IOException {
        throw new IOException("My IO Exception");
    }

}

Use @RegisterExtension in junit5-extension-model 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 io.trino.testing;

import com.google.common.collect.ImmutableMap;

import java.util.Map;

public final class FaultTolerantExecutionConnectorTestHelper
{
    private FaultTolerantExecutionConnectorTestHelper() {}

    public static Map<String, String> getExtraProperties()
    {
        return ImmutableMap.<String, String>builder()
                .put("retry-policy", "TASK")
                .put("fault-tolerant-execution-partition-count", "5")
                .put("fault-tolerant-execution-target-task-input-size", "10MB")
                .put("fault-tolerant-execution-target-task-split-count", "4")
                // to trigger spilling
                .put("exchange.deduplication-buffer-size", "1kB")
                .put("fault-tolerant-execution-task-memory", "1GB")
                .buildOrThrow();
    }
}

/*
 * 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.trino.testing;

import com.google.common.collect.ImmutableMap;

import java.util.Map;

public final class FaultTolerantExecutionConnectorTestHelper
{
    private FaultTolerantExecutionConnectorTestHelper() {}

    public static Map<String, String> getExtraProperties()
    {
        return ImmutableMap.<String, String>builder()
                .put("retry-policy", "TASK")
                .put("retry-initial-delay", "50ms")
                .put("retry-max-delay", "100ms")
                .put("fault-tolerant-execution-partition-count", "5")
                .put("fault-tolerant-execution-target-task-input-size", "10MB")
                .put("fault-tolerant-execution-target-task-split-count", "4")
                // to trigger spilling
                .put("exchange.deduplication-buffer-size", "1kB")
                .put("fault-tolerant-execution-task-memory", "1GB")
                .buildOrThrow();
    }
}

Decrease retry delay in fault tolerant execution tests

Some tests are written to fail with an external failure what causes
tasks being retried several times.


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin.monitoring;

import ai.vespa.metricsproxy.core.VespaMetrics;
import com.google.common.collect.ImmutableList;

import static com.yahoo.vespa.model.admin.monitoring.NetworkMetrics.networkMetricSet;
import static com.yahoo.vespa.model.admin.monitoring.SystemMetrics.systemMetricSet;
import static com.yahoo.vespa.model.admin.monitoring.VespaMetricSet.vespaMetricSet;
import static java.util.Collections.emptyList;

/**
 * This class sets up the 'Vespa' metrics consumer.
 *
 * @author trygve
 * @author gjoranv
 */
public class VespaMetricsConsumer {

    public static final String VESPA_CONSUMER_ID = VespaMetrics.VESPA_CONSUMER_ID.id;

    private static final MetricSet defaultConsumerMetrics = new MetricSet("vespa-consumer-metrics",
                                                                          emptyList(),
                                                                          ImmutableList.of(vespaMetricSet,
                                                                                systemMetricSet,
                                                                                networkMetricSet));

    public static MetricsConsumer getVespaMetricsConsumer() {
        return new MetricsConsumer(VESPA_CONSUMER_ID, defaultConsumerMetrics);
    }

}

// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin.monitoring;

import ai.vespa.metricsproxy.core.VespaMetrics;
import com.google.common.collect.ImmutableList;

import static com.yahoo.vespa.model.admin.monitoring.NetworkMetrics.networkMetricSet;
import static com.yahoo.vespa.model.admin.monitoring.SystemMetrics.systemMetricSet;
import static com.yahoo.vespa.model.admin.monitoring.VespaMetricSet.vespaMetricSet;
import static java.util.Collections.emptyList;

/**
 * This class sets up the 'Vespa' metrics consumer, which is mainly used for Yamas in hosted Vespa.
 *
 * @author trygve
 * @author gjoranv
 */
public class VespaMetricsConsumer {

    public static final String VESPA_CONSUMER_ID = VespaMetrics.VESPA_CONSUMER_ID.id;

    private static final MetricSet vespaConsumerMetrics = new MetricSet("vespa-consumer-metrics",
                                                                        emptyList(),
                                                                        ImmutableList.of(vespaMetricSet,
                                                                                systemMetricSet,
                                                                                networkMetricSet));

    public static MetricsConsumer getVespaMetricsConsumer() {
        return new MetricsConsumer(VESPA_CONSUMER_ID, vespaConsumerMetrics);
    }

}

Rename default -> vespa and add clarifying comment.


/*
 * Copyright (C) 2011-2012 The University of Manchester
 *
 * See the file "LICENSE" for license terms.
 */
package org.taverna.server.port_description;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

import org.taverna.server.port_description.utils.IntAdapter;

@XmlType(name = "Port")
public class AbstractPort {
	@XmlAttribute(required = true)
	public String name;

	@XmlAttribute
	@XmlSchemaType(name = "int")
	@XmlJavaTypeAdapter(IntAdapter.class)
	public Integer depth;
}

/*
 * Copyright (C) 2011-2012 The University of Manchester
 *
 * See the file "LICENSE" for license terms.
 */
package org.taverna.server.port_description;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

import org.taverna.server.port_description.utils.IntAdapter;

@XmlType(name = "Port")
public class AbstractPort {
	@XmlID
	@XmlAttribute(required = true)
	public String name;

	@XmlAttribute
	@XmlSchemaType(name = "int")
	@XmlJavaTypeAdapter(IntAdapter.class)
	public Integer depth;
}

Make ports in descriptors be XML IDs

Make ports in descriptors be XML IDs


/*
 * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
 *
 * 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.orientechnologies.orient.core.serialization.serializer.stream;

import java.io.IOException;

import com.orientechnologies.orient.core.serialization.OBinaryProtocol;

public class OStreamSerializerLong implements OStreamSerializer {
	public static final String								NAME			= "l";

	public static final OStreamSerializerLong	INSTANCE	= new OStreamSerializerLong();

	public String getName() {
		return NAME;
	}

	public Object fromStream(final byte[] iStream) throws IOException {
		return OBinaryProtocol.bytes2long(iStream);
	}

	public byte[] toStream(final Object iObject) throws IOException {
		return OBinaryProtocol.long2bytes((Long) iObject);
	}
}

/*
 * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
 *
 * 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.orientechnologies.orient.core.serialization.serializer.stream;

import java.io.IOException;

import com.orientechnologies.orient.core.serialization.OBinaryProtocol;

public class OStreamSerializerLong implements OStreamSerializer {
	public static final String								NAME			= "lo";

	public static final OStreamSerializerLong	INSTANCE	= new OStreamSerializerLong();

	public String getName() {
		return NAME;
	}

	public Object fromStream(final byte[] iStream) throws IOException {
		return OBinaryProtocol.bytes2long(iStream);
	}

	public byte[] toStream(final Object iObject) throws IOException {
		return OBinaryProtocol.long2bytes((Long) iObject);
	}
}

Fix by Sylvain on duplicated name for serializers Record and Long


package at.ac.tuwien.inso.controller.lecturer.forms;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.entity.Tag;

public class AddCourseForm {

    private Course course;

    private List<AddCourseTag> activeAndInactiveTags = new ArrayList<>();

    protected AddCourseForm() {
    }

    public AddCourseForm(Course course) {
        this.course = course;

    }

    public AddCourseForm setInitialTags(List<Tag> tags) {
        tags.forEach(tag -> activeAndInactiveTags.add(new AddCourseTag(tag, false)));
        return this;
    }

    public Course getCourse() {
        return course;
    }

    public void setCourse(Course course) {
        this.course = course;
    }

    public List<AddCourseTag> getActiveAndInactiveTags() {
        return activeAndInactiveTags;
    }

    public void setActiveAndInactiveTags(List<AddCourseTag> activeAndInactiveTags) {
        this.activeAndInactiveTags = activeAndInactiveTags;
    }
}

package at.ac.tuwien.inso.controller.lecturer.forms;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.entity.Tag;

public class AddCourseForm {

    private Course course;

    private List<AddCourseTag> activeAndInactiveTags = new ArrayList<>();

    protected AddCourseForm() {
    }

    public AddCourseForm(Course course) {
        this.course = course;

    }

    public AddCourseForm setInitialTags(List<Tag> tags) {
        tags.forEach(tag -> activeAndInactiveTags.add(new AddCourseTag(tag, false)));
        return this;
    }

    public Course getCourse() {
        return course;
    }

    public void setCourse(Course course) {
        this.course = course;
    }

    public List<AddCourseTag> getActiveAndInactiveTags() {
        return activeAndInactiveTags;
    }

    public void setActiveAndInactiveTags(List<AddCourseTag> activeAndInactiveTags) {
        this.activeAndInactiveTags = activeAndInactiveTags;
    }

    public void setInitialActiveTags(List<Tag> initialActiveTags) {
        activeAndInactiveTags.stream()
                .filter(tag -> initialActiveTags.contains(tag.getTag()))
                .forEach(tag -> tag.setActive(true));
    }
}

Add method to extract active tags from courses when editing


// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.metricsproxy.metric.model;

import java.util.Objects;

/**
 * @author gjoranv
 */
public class MetricId {

    public static final MetricId empty = toMetricId("");
    public final String id;
    private MetricId(String id) { this.id = id; }

    public static MetricId toMetricId(String id) { return new MetricId(id); }

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

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

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

}

// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.metricsproxy.metric.model;

import com.yahoo.yolean.concurrent.CopyOnWriteHashMap;

import java.util.Map;
import java.util.Objects;

/**
 * @author gjoranv
 */
public class MetricId {

    private static final Map<String, MetricId> dictionary = new CopyOnWriteHashMap<>();
    public static final MetricId empty = toMetricId("");
    public final String id;
    private MetricId(String id) { this.id = id; }

    public static MetricId toMetricId(String id) {
        return dictionary.computeIfAbsent(id, key -> new MetricId(key));
    }

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

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

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

}

Use a dictionary for metrid ids. There are few unique ones (less than 1k), but many instances.


package br.odb.multiplayer.model;

import java.util.HashMap;

import javax.servlet.ServletContext;

public class ServerContext {
	public final HashMap<Integer, Game> games = new HashMap<Integer, Game>();
	public final HashMap< String, Game > gameBuilders = new HashMap< String, Game >();

	public ServerContext() {
	}

	public static ServerContext createOrRetrieve( ServletContext servletContext) {

		ServerContext context = (ServerContext) servletContext
				.getAttribute("games-context");

		if (context == null) {
			reset( servletContext );
		}

		return context;
	}

	public static void reset(ServletContext servletContext) {
		servletContext.setAttribute("games-context", new ServerContext() );
	}
}

package br.odb.multiplayer.model;

import java.util.HashMap;

import javax.servlet.ServletContext;

public class ServerContext {
	public final HashMap<Integer, Game> games = new HashMap<Integer, Game>();
	public final HashMap< String, Game > gameBuilders = new HashMap< String, Game >();

	public ServerContext() {
	}

	public static ServerContext createOrRetrieve( ServletContext servletContext) {

		ServerContext context = (ServerContext) servletContext
				.getAttribute("games-context");

		if (context == null) {
			reset( servletContext );

			context = (ServerContext) servletContext.getAttribute("games-context");
		}

		return context;
	}

	public static void reset(ServletContext servletContext) {
		servletContext.setAttribute("games-context", new ServerContext() );
	}
}

Fix idiotic bug in GetGameId

Fix idiotic bug in GetGameId

The first try to play would always fail.


package nl.opengeogroep.safetymaps.server.stripes;

import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;

/**
 *
 * @author matthijsln
 */
@UrlBinding("/viewer/api/login")
public class LoginActionBean implements ActionBean {
    private ActionBeanContext context;

    @Override
    public ActionBeanContext getContext() {
        return context;
    }

    @Override
    public void setContext(ActionBeanContext context) {
        this.context = context;
    }

    public Resolution redirect() {
        return new StreamingResolution("text/html",
            "" +
                "<meta http-equiv=\"refresh\" content=\"0;url=" + context.getRequest().getContextPath() + "/viewer/\">" +
            ""
        );
    }
}

package nl.opengeogroep.safetymaps.server.stripes;

import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;

/**
 *
 * @author matthijsln
 */
@UrlBinding("/viewer/api/login")
public class LoginActionBean implements ActionBean {
    private ActionBeanContext context;

    @Override
    public ActionBeanContext getContext() {
        return context;
    }

    @Override
    public void setContext(ActionBeanContext context) {
        this.context = context;
    }

    public Resolution redirect() {
        String returnTo = request.getParameter("returnTo");

        if (returnTo == null || returnTo.length() == 0) {
            returnTo = "/viewer/";
        }

        return new StreamingResolution("text/html",
            "" +
                "<meta http-equiv=\"refresh\" content=\"0;url=" + context.getRequest().getContextPath() + returnTo + "\">" +
            ""
        );
    }
}

Add returnTo param to normal login request


/*******************************************************************************
 * Copyright (c) 2005 Actuate Corporation.
 * 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:
 *  Actuate Corporation  - initial API and implementation
 *******************************************************************************/
package org.eclipse.birt.report.viewer.utilities;

/** A class used to get a workspace classpath
 *
 */
public class WorkspaceClasspathManager
{

	public static final String PROPERTYSEPARATOR = ";";

	private static IWorkspaceClasspathFinder finder;

	public static String getClassPath( )
	{
		if ( finder == null )
			return null;

		return finder.getClassPath( );
	}

	public static void registerClassPathFinder(
			IWorkspaceClasspathFinder pathfinder )
	{
		finder = pathfinder;
	}
}

/*******************************************************************************
 * Copyright (c) 2005 Actuate Corporation.
 * 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:
 *  Actuate Corporation  - initial API and implementation
 *******************************************************************************/
package org.eclipse.birt.report.viewer.utilities;

/** A class used to get a workspace classpath
 *
 */
public class WorkspaceClasspathManager
{

	private static IWorkspaceClasspathFinder finder;

	public static String getClassPath( )
	{
		if ( finder == null )
			return null;

		return finder.getClassPath( );
	}

	public static void registerClassPathFinder(
			IWorkspaceClasspathFinder pathfinder )
	{
		finder = pathfinder;
	}
}

Fix 188486 -- remove hard code for the property separator as ';'.


package co.uk.real_logic.aeron.tools;

import org.apache.commons.cli.ParseException;
import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import uk.co.real_logic.aeron.tools.PubSubOptions;

/**
 * Created by bhorst on 3/3/15.
 */
public class PubSubOptionsTest
{
    PubSubOptions opts;
    @Before
    public void SetUp() {
        opts = new PubSubOptions();
    }

    @Test
    public void threadsShorthandValid() throws Exception {
        String[] args = { "-t", "1234" };
        opts.parseArgs(args);
        assertThat(opts.getThreads(), is(1234L));
    }

    @Test
    public void threadsLonghandValid() throws Exception {
        String[] args = { "--threads", "1234" };
        opts.parseArgs(args);
        assertThat(opts.getThreads(), is(1234L));
    }

    @Test (expected=ParseException.class)
    public void threadsInvalid() {

    }

    @Test (expected=ParseException.class)
    public void threadsLonghandInvalid() throws Exception {
        String[] args = { "--threads", "asdf" };
        opts.parseArgs(args);
    }
}

package co.uk.real_logic.aeron.tools;

import org.apache.commons.cli.ParseException;
import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import uk.co.real_logic.aeron.tools.PubSubOptions;

/**
 * Created by bhorst on 3/3/15.
 */
public class PubSubOptionsTest
{
    PubSubOptions opts;
    @Before
    public void setUp()
    {
        opts = new PubSubOptions();
    }

    @Test
    public void threadsShorthandValid() throws Exception
    {
        String[] args = { "-t", "1234" };
        opts.parseArgs(args);
        assertThat(opts.getThreads(), is(1234L));
    }

    @Test
    public void threadsLonghandValid() throws Exception
    {
        String[] args = { "--threads", "1234" };
        opts.parseArgs(args);
        assertThat(opts.getThreads(), is(1234L));
    }

    @Test (expected=ParseException.class)
    public void threadsInvalid() throws Exception
    {
        String[] args = { "-t", "asdf" };
        opts.parseArgs(args);
    }

    @Test (expected=ParseException.class)
    public void threadsLonghandInvalid() throws Exception
    {
        String[] args = { "--threads", "asdf" };
        opts.parseArgs(args);
    }
}

Fix the syntax of unit tests

Fix the syntax of unit tests


package net.sourceforge.javydreamercsw.validation.manager.web.file;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author Javier A. Ortiz Bultron <javier.ortiz.78@gmail.com>
 */
public abstract class AbstractFileDisplay implements IFileDisplay {

    @Override
    public boolean supportFile(File f) {
        return f.isFile() && supportFile(f.getName());
    }

    @Override
    public File loadFile(String name, byte[] bytes) throws IOException {
        File result = new File(System.getProperty("java.io.tmpdir")
                + System.getProperty("file.separator") + name);
        FileUtils.writeByteArrayToFile(result, bytes);
        return result;
    }
}

package net.sourceforge.javydreamercsw.validation.manager.web.file;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author Javier A. Ortiz Bultron <javier.ortiz.78@gmail.com>
 */
public abstract class AbstractFileDisplay implements IFileDisplay {

    @Override
    public boolean supportFile(File f) {
        return supportFile(f.getName());
    }

    @Override
    public File loadFile(String name, byte[] bytes) throws IOException {
        File result = new File(System.getProperty("java.io.tmpdir")
                + System.getProperty("file.separator") + name);
        FileUtils.writeByteArrayToFile(result, bytes);
        return result;
    }
}

Fix bug when deciding if file is supported.


package uk.ac.ic.wlgitbridge.writelatex.model.db.sql.update.create;

import uk.ac.ic.wlgitbridge.writelatex.model.db.sql.SQLUpdate;

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

/**
 * Created by Winston on 21/02/15.
 */
public class CreateIndexURLIndexStore implements SQLUpdate {

    public static final String CREATE_INDEX_URL_INDEX_STORE = "CREATE INDEX `project_path_index` ON `url_index_store`(`project_name`, `path`);\n";

    @Override
    public String getSQL() {
        return CREATE_INDEX_URL_INDEX_STORE;
    }

    @Override
    public void addParametersToStatement(PreparedStatement statement) throws SQLException {

    }

}

package uk.ac.ic.wlgitbridge.writelatex.model.db.sql.update.create;

import uk.ac.ic.wlgitbridge.writelatex.model.db.sql.SQLUpdate;

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

/**
 * Created by Winston on 21/02/15.
 */
public class CreateIndexURLIndexStore implements SQLUpdate {

    public static final String CREATE_INDEX_URL_INDEX_STORE =
            "CREATE INDEX IF NOT EXISTS `project_path_index` ON `url_index_store`(`project_name`, `path`);\n";

    @Override
    public String getSQL() {
        return CREATE_INDEX_URL_INDEX_STORE;
    }

    @Override
    public void addParametersToStatement(PreparedStatement statement) throws SQLException {

    }

}

Add IF NOT EXISTS to index creation sql statement.


package es.ucm.fdi.tp.views.swing;

public class MessagesBox extends ScrollableTextarea {

	private static final long serialVersionUID = 768586332299945974L;

	public MessagesBox() {
		super();
	}

	public MessagesBox(String text) {
		super(text);
	}

	public MessagesBox(int rows, int cols) {
		super(rows,cols);
	}

	public MessagesBox(String text, int rows, int cols) {
		super(text,rows,cols);
	}

	@Override
	protected void formatTextArea() {
		super.formatTextArea();
		this.textarea.setEditable(false);
		this.textarea.setHighlighter(null);
	}

	/**
	 * @throws UnsupportedOperationException when editable is set to true.
	 */
	@Override
	public void setEditable(boolean b) {
		if(b) throw new UnsupportedOperationException(
				"This textarea object is read-only to users. ");
		else this.textarea.setEditable(false);
	}

	/**
	 * Adds a new message to the box list. Does nothing if the model is null or
	 * the string is null or empty.
	 */
	@Override
	public void append(String str) {
		textarea.append("* " + str + "\n");
	}
}

package es.ucm.fdi.tp.views.swing;

import javax.swing.border.TitledBorder;

public class MessagesBox extends ScrollableTextarea {

	private static final long serialVersionUID = 768586332299945974L;

	public MessagesBox() {
		super();
	}

	public MessagesBox(String text) {
		super(text);
	}

	public MessagesBox(int rows, int cols) {
		super(rows,cols);
	}

	public MessagesBox(String text, int rows, int cols) {
		super(text,rows,cols);
	}

	@Override
	protected void formatTextArea() {
		super.formatTextArea();
		this.textarea.setEditable(false);
		this.textarea.setHighlighter(null);
		this.setBorder(new TitledBorder("Status Messages"));
	}

	/**
	 * @throws UnsupportedOperationException when editable is set to true.
	 */
	@Override
	public void setEditable(boolean b) {
		if(b) throw new UnsupportedOperationException(
				"This textarea object is read-only to users. ");
		else this.textarea.setEditable(false);
	}

	/**
	 * Adds a new message to the box list. Does nothing if the model is null or
	 * the string is null or empty.
	 */
	@Override
	public void append(String str) {
		textarea.append("* " + str + "\n");
	}
}

Add missing border to messages box

Add missing border to messages box


package org.metaborg.meta.lang.dynsem.interpreter.nabl2.sg.nodes;

import org.metaborg.meta.lang.dynsem.interpreter.nabl2.NaBL2SolutionUtils;
import org.metaborg.meta.lang.dynsem.interpreter.nabl2.sg.TermIndex;
import org.metaborg.meta.lang.dynsem.interpreter.nodes.building.NativeOpBuild;
import org.metaborg.meta.lang.dynsem.interpreter.nodes.building.TermBuild;
import org.metaborg.meta.lang.dynsem.interpreter.terms.ITerm;

import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.source.SourceSection;

@NodeChild(value = "term", type = TermBuild.class)
public abstract class GetTopLevelTermIndex extends NativeOpBuild {

	public GetTopLevelTermIndex(SourceSection source) {
		super(source);
	}

	@Specialization
	public TermIndex executeTermIndex(ITerm term) {
		mb.nabl2.stratego.TermIndex termIndex = NaBL2SolutionUtils.getTermIndex(nabl2Context(), term.getStrategoTerm());

		return new TermIndex(termIndex.getResource(), 0);
	}

	public static GetTopLevelTermIndex create(SourceSection source, TermBuild term) {
		return ScopeNodeFactories.createGetTopLevelTermIndex(source, term);
	}
}

package org.metaborg.meta.lang.dynsem.interpreter.nabl2.sg.nodes;

import org.metaborg.meta.lang.dynsem.interpreter.nabl2.NaBL2SolutionUtils;
import org.metaborg.meta.lang.dynsem.interpreter.nabl2.sg.TermIndex;
import org.metaborg.meta.lang.dynsem.interpreter.nodes.building.NativeOpBuild;
import org.metaborg.meta.lang.dynsem.interpreter.nodes.building.TermBuild;
import org.metaborg.meta.lang.dynsem.interpreter.terms.ITerm;

import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.source.SourceSection;

@NodeChild(value = "term", type = TermBuild.class)
public abstract class GetTopLevelTermIndex extends NativeOpBuild {

	public GetTopLevelTermIndex(SourceSection source) {
		super(source);
	}

	@Specialization
	public TermIndex executeTermIndex(ITerm term) {
		mb.nabl2.stratego.TermIndex termIndex = NaBL2SolutionUtils.getTermIndex(term.getStrategoTerm());

		return new TermIndex(termIndex.getResource(), 0);
	}

	public static GetTopLevelTermIndex create(SourceSection source, TermBuild term) {
		return ScopeNodeFactories.createGetTopLevelTermIndex(source, term);
	}
}

Fix incorrect method call after a previous refactoring


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

package org.mutabilitydetector.unittesting.assertionbenchmarks;

import java.math.BigDecimal;

import org.mutabilitydetector.cli.CommandLineOptions;
import org.mutabilitydetector.cli.RunMutabilityDetector;

import com.google.classpath.ClassPath;
import com.google.classpath.ClassPathFactory;

public class CheckSomeClass {

	public static void main(String[] args) {
		//checkClass(TestIllegalFieldValueException.class);
//		checkClass(DurationField.class);
		checkClass(BigDecimal.class);
	}

	private static void checkClass(Class<?> toAnalyse) {
		ClassPath cp = new ClassPathFactory().createFromJVM();
		String match = toAnalyse.getName().replace("$", "\\$");
		CommandLineOptions options = new CommandLineOptions(System.out, "-v", "-match", match);
		new RunMutabilityDetector(cp, options).run();
	}

}

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

package org.mutabilitydetector.unittesting.assertionbenchmarks;

import java.math.BigDecimal;

import org.mutabilitydetector.cli.CommandLineOptions;
import org.mutabilitydetector.cli.RunMutabilityDetector;
import org.mutabilitydetector.repackaged.com.google.classpath.ClassPath;
import org.mutabilitydetector.repackaged.com.google.classpath.ClassPathFactory;

public class CheckSomeClass {

	public static void main(String[] args) {
		//checkClass(TestIllegalFieldValueException.class);
//		checkClass(DurationField.class);
		checkClass(BigDecimal.class);
	}

	private static void checkClass(Class<?> toAnalyse) {
		ClassPath cp = new ClassPathFactory().createFromJVM();
		String match = toAnalyse.getName().replace("$", "\\$");
		CommandLineOptions options = new CommandLineOptions(System.out, "-v", "-match", match);
		new RunMutabilityDetector(cp, options).run();
	}

}

Use the repackaged versions of classes.

Use the repackaged versions of classes.

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


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

package net.myrrix.client.translating;

public final class GenericTranslatedRecommendedItem implements TranslatedRecommendedItem {

  private final String itemID;
  private final float value;

  public GenericTranslatedRecommendedItem(String itemID, float value) {
    this.itemID = itemID;
    this.value = value;
  }

  @Override
  public String getItemID() {
    return itemID;
  }

  @Override
  public float getValue() {
    return value;
  }

}

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

package net.myrrix.client.translating;

import java.io.Serializable;

import com.google.common.base.Preconditions;
import org.apache.mahout.common.RandomUtils;

/**
 *
A simple implementation of {@link TranslatedRecommendedItem}.

 *
 * @author Sean Owen
 */
public final class GenericTranslatedRecommendedItem implements TranslatedRecommendedItem, Serializable {

  private final String itemID;
  private final float value;

  /**
   * @throws IllegalArgumentException if item is null or value is NaN or infinite
   */
  public GenericTranslatedRecommendedItem(String itemID, float value) {
    Preconditions.checkNotNull(itemID);
    Preconditions.checkArgument(!Float.isNaN(value) && !Float.isInfinite(value));
    this.itemID = itemID;
    this.value = value;
  }

  @Override
  public String getItemID() {
    return itemID;
  }

  @Override
  public float getValue() {
    return value;
  }

  @Override
  public String toString() {
    return "GenericTranslatedRecommendedItem[item:" + itemID + ", value:" + value + ']';
  }

  @Override
  public int hashCode() {
    return itemID.hashCode() ^ RandomUtils.hashFloat(value);
  }

  @Override
  public boolean equals(Object o) {
    if (!(o instanceof GenericTranslatedRecommendedItem)) {
      return false;
    }
    GenericTranslatedRecommendedItem other = (GenericTranslatedRecommendedItem) o;
    return itemID.equals(other.getItemID()) && value == other.getValue();
  }

}

Add a few more changes to be consistent with GenericRecommendedItem, like toString()


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

/**
 *
 * @author Ryan Gilera
 */
public enum LoginValidationNum {
    STUDENT_ID_MIN_VALUE(10000),
    STUDENT_ID_MAX_VALUE(99999),
    STUDENT_ID_LENGTH(5),
    EMAIL_MAX_LENGTH(254),
    PASSWORD_MAX_LENGTH(16),
    PASSWORD_MIN_LENGTH(6)
    ;
    private final int value;

    private LoginValidationNum(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

}

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

/**
 *
 * @author Ryan Gilera
 */
public enum LoginValidationNum {
    STUDENT_ID_MIN_VALUE(100000),
    STUDENT_ID_MAX_VALUE(999999),
    STUDENT_ID_LENGTH(6),
    EMAIL_MAX_LENGTH(254),
    PASSWORD_MAX_LENGTH(16),
    PASSWORD_MIN_LENGTH(6)
    ;
    private final int value;

    private LoginValidationNum(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

}

Update range to 6 figures

Update range to 6 figures


package protocolsupport.protocol.packet.middleimpl;

import io.netty.buffer.ByteBuf;
import protocolsupport.protocol.packet.PacketType;

public interface RunnableTransformOperation extends Runnable, IPacketData {

	@Override
	default PacketType getPacketType() {
		return PacketType.NONE;
	}

	@Override
	default void writeData(ByteBuf to) {
		run();
	}

	@Override
	default void recycle() {
	}

}

package protocolsupport.protocol.packet.middleimpl;

import io.netty.buffer.ByteBuf;
import protocolsupport.protocol.packet.PacketType;

public class RunnableTransformOperation implements IPacketData {

	protected final Runnable runnable;
	public RunnableTransformOperation(Runnable runnable) {
		this.runnable = runnable;
	}

	@Override
	public void writeData(ByteBuf to) {
		runnable.run();
	}

	@Override
	public int getDataLength() {
		return 0;
	}

	@Override
	public PacketType getPacketType() {
		return PacketType.NONE;
	}

	@Override
	public void recycle() {
	}

}

Make runnabletransformoperation into a class instead


package kfs.springutils;

import java.io.IOException;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author pavedrim
 */
public class RunApp {

    public static void run(String profileName) {
        run(profileName, "pidfile", "appContext.xml");
    }

    public static void run(String profileName, String pidPropertyFilename, String contextFile) {
        if (pidPropertyFilename != null) {
            String pidf = System.getProperty(pidPropertyFilename);
            if ((pidf != null) && !pidf.isEmpty()) {
                ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", "echo $PPID > " + pidf);
                try {
                    Process p = pb.start();
                } catch (IOException e) {
                }
            }
        }
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();
        ctx.setConfigLocation(contextFile);
        ctx.getEnvironment().setActiveProfiles(profileName);
        ctx.refresh();
    }
}

package kfs.springutils;

import java.io.IOException;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author pavedrim
 */
public class RunApp {

    public static String defaultContextFile = "appContext.xml";
    public static String defaultPidFilePropertyName = "pidfile";

    public static void run(String profileName) {
        run(profileName, defaultPidFilePropertyName, defaultContextFile);
    }

    public static void run(String profileName, String pidPropertyFilename, String contextFile) {
        if (pidPropertyFilename != null) {
            String pidf = System.getProperty(pidPropertyFilename);
            if ((pidf != null) && !pidf.isEmpty()) {
                ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", "echo $PPID > " + pidf);
                try {
                    Process p = pb.start();
                } catch (IOException e) {
                }
            }
        }
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();
        ctx.setConfigLocation(contextFile);
        ctx.getEnvironment().setActiveProfiles(profileName);
        ctx.refresh();
    }
}

Use fafault values as a constats

Use fafault values as a constats


package com.example.android.androidsimulator;

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

public class AddContactsActivity extends AppCompatActivity {

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

package com.example.android.androidsimulator;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddContactsActivity extends AppCompatActivity {

    Toast toast;
    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    EditText nameContact;
    EditText numberContact;
    Button buttonAddContact;

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

        nameContact = (EditText) findViewById(R.id.nameContact_editText);
        numberContact = (EditText) findViewById(R.id.numberContact_editText);
        buttonAddContact = (Button) findViewById(R.id.addContact_button);

        buttonAddContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addContact();
            }
        });
    }

    private void addContact() {
        // SharedPreferences to save data on internal storage
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        editor = preferences.edit();

        int totalContacts = preferences.getInt("totalContacts", 0);

        CharSequence validationMessage;
        String name = String.valueOf(nameContact.getText());
        String number = String.valueOf(numberContact.getText());

        // validation of contact
        if (name.isEmpty()) {
            validationMessage = "You need to insert a name";
        }
        else if (number.isEmpty()) {
            validationMessage = "You need to insert a number";
        }
        else {
            validationMessage = "Added contact";
            totalContacts += 1;

            // add info of contact on internal storage
            editor.putInt("totalContacts", totalContacts);
            editor.putString("nameContact" + totalContacts, name);
            editor.putInt("numberContact" + totalContacts, Integer.valueOf(number));
            editor.apply();
        }

       toast = Toast.makeText(this, validationMessage, Toast.LENGTH_SHORT);
       toast.show();
    }
}

Add contacts to internal storage

Add contacts to internal storage


/*
 *    Copyright (C) 2015 Haruki Hasegawa
 *
 *    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.h6ah4i.android.example.advrecyclerview.common.utils;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewParent;

public class AdapterUtils {
    public static View findParentViewHolderItemView(View v) {
        final ViewParent parent = v.getParent();
        if (parent instanceof RecyclerView) {
            // returns the passed instance if the parent is RecyclerView
            return v;
        } else if (v instanceof View) {
            // check the parent view recursively
            return findParentViewHolderItemView((View) parent);
        } else {
            return null;
        }
    }
}

/*
 *    Copyright (C) 2015 Haruki Hasegawa
 *
 *    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.h6ah4i.android.example.advrecyclerview.common.utils;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewParent;

public class AdapterUtils {
    public static View findParentViewHolderItemView(View v) {
        final ViewParent parent = v.getParent();
        if (parent instanceof RecyclerView) {
            // returns the passed instance if the parent is RecyclerView
            return v;
        } else if (parent instanceof View) {
            // check the parent view recursively
            return findParentViewHolderItemView((View) parent);
        } else {
            return null;
        }
    }
}

Fix a lint warned bug

Fix a lint warned bug


package io.subutai.hub.share.dto;

/**
 * Created by ${Zubaidullo} on 2/18/16.
 */
public enum SystemConfigurationType
{
    SUBUTAI_SOCIAL, SUBUTAI_SOCIAL_PLUGIN, SUBUTAI_SOCIAL_HUB
}

package io.subutai.hub.share.dto;

/**
 * Created by ${Zubaidullo} on 2/18/16.
 */
public enum SystemConfigurationType
{
    SUBUTAI_SOCIAL, SUBUTAI_SOCIAL_PLUGIN, SUBUTAI_SOCIAL_HUB, RESOURCE_HOST, P2P
}

Add system config type: RH and P2P

Add system config type: RH and P2P


/*
 * Copyright 2021, TeamDev. 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
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.server.entity.given.repository;

import io.spine.server.entity.TransactionalEntity;
import io.spine.test.entity.Project;
import io.spine.test.entity.ProjectId;

public class ProjectEntity extends TransactionalEntity<ProjectId, Project, Project.Builder> {
    private ProjectEntity(ProjectId id) {
        super(id);
    }
}

/*
 * Copyright 2021, TeamDev. 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
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.server.entity.given.repository;

import io.spine.server.entity.TransactionalEntity;
import io.spine.test.entity.Project;
import io.spine.test.entity.ProjectId;

public final class ProjectEntity extends TransactionalEntity<ProjectId, Project, Project.Builder> {

    private ProjectEntity(ProjectId id) {
        super(id);
    }
}

Reformat the code. Mark the type `final`.


package com.github.florent37.materialviewpager.header;

import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;

/**
 * Created by florentchampigny on 10/06/15.
 */
public class HeaderDesign {
    protected int color;
    protected int colorRes;
    protected String imageUrl;
    protected Drawable drawable;

    private HeaderDesign() {
    }

    public static HeaderDesign fromColorAndUrl(@ColorInt int color, String imageUrl) {
        HeaderDesign headerDesign = new HeaderDesign();
        headerDesign.color = color;
        headerDesign.imageUrl = imageUrl;
        return headerDesign;
    }

    public static HeaderDesign fromColorResAndUrl(@ColorRes int colorRes, String imageUrl) {
        HeaderDesign headerDesign = new HeaderDesign();
        headerDesign.colorRes = colorRes;
        headerDesign.imageUrl = imageUrl;
        return headerDesign;
    }

    public static HeaderDesign fromColorAndDrawable(@ColorInt int color, Drawable drawable) {
        HeaderDesign headerDesign = new HeaderDesign();
        headerDesign.drawable = drawable;
        headerDesign.color = color;
        return headerDesign;
    }

    public static HeaderDesign fromColorResAndDrawable(@ColorRes int colorRes, String imageUrl) {
        HeaderDesign headerDesign = new HeaderDesign();
        headerDesign.colorRes = colorRes;
        headerDesign.imageUrl = imageUrl;
        return headerDesign;
    }

    public int getColor() {
        return color;
    }

    public int getColorRes() {
        return colorRes;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public Drawable getDrawable() {
        return drawable;
    }
}

package com.github.florent37.materialviewpager.header;

import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;

/**
 * Created by florentchampigny on 10/06/15.
 */
public class HeaderDesign {
    protected int color;
    protected int colorRes;
    protected String imageUrl;
    protected Drawable drawable;

    private HeaderDesign() {
    }

    public static HeaderDesign fromColorAndUrl(@ColorInt int color, String imageUrl) {
        HeaderDesign headerDesign = new HeaderDesign();
        headerDesign.color = color;
        headerDesign.imageUrl = imageUrl;
        return headerDesign;
    }

    public static HeaderDesign fromColorResAndUrl(@ColorRes int colorRes, String imageUrl) {
        HeaderDesign headerDesign = new HeaderDesign();
        headerDesign.colorRes = colorRes;
        headerDesign.imageUrl = imageUrl;
        return headerDesign;
    }

    public static HeaderDesign fromColorAndDrawable(@ColorInt int color, Drawable drawable) {
        HeaderDesign headerDesign = new HeaderDesign();
        headerDesign.drawable = drawable;
        headerDesign.color = color;
        return headerDesign;
    }

    public static HeaderDesign fromColorResAndDrawable(@ColorRes int colorRes, Drawable drawable) {
        HeaderDesign headerDesign = new HeaderDesign();
        headerDesign.colorRes = colorRes;
        headerDesign.drawable = drawable;
        return headerDesign;
    }

    public int getColor() {
        return color;
    }

    public int getColorRes() {
        return colorRes;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public Drawable getDrawable() {
        return drawable;
    }
}

Fix what seems to be a mistake in fromColorResAndDrawable

Based off the name of the function, it seems that `fromColorResAndDrawable` should take in a `Drawable` object, not a `String` imageUrl.


package org.springframework.support;

import org.springframework.versions.AncestorRootId;
import org.springframework.versions.SuccessorId;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class TestEntityVersioned {
    @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id;

    // these are required to satisfy the
    @AncestorRootId private String ancestralRootId;
    @SuccessorId private String successorId;
}

package org.springframework.support;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import org.springframework.versions.AncestorId;
import org.springframework.versions.AncestorRootId;
import org.springframework.versions.SuccessorId;

@Entity
public class TestEntityVersioned {
    @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id;

    // these are required to satisfy the
    @AncestorRootId private String ancestralRootId;
    @AncestorId private String ancestorId;
    @SuccessorId private String successorId;
}

Make test entities for versioned repositories implement an ancestorId field

- required after the working copy refactor


package heufybot.core;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import heufybot.utils.FileUtils;

public class Logger
{
	public static void log(String line)
	{
		//Timestamp line
		DateFormat dateFormat = new SimpleDateFormat("[HH:mm]");
		Date date = new Date();
		line = dateFormat.format(date) + " " + line;

		//Output to console
		System.out.println(line);

		//Output to logfile
		FileUtils.writeFileAppend("test.log", line + "\n");
	}

	public static void error(String errorSource, String line)
	{
		System.err.println(errorSource + " - ERROR: " + line);
	}
}

package heufybot.core;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import heufybot.utils.FileUtils;

public class Logger
{
	public static void log(String line, String target)
	{
		//Timestamp line
		DateFormat dateFormat = new SimpleDateFormat("[HH:mm]");
		Date date = new Date();
		line = dateFormat.format(date) + " " + line;

		//Output to console
		if(target.equals(""))
		{
			System.out.println(line);
		}
		else
		{
			System.out.println(target + " - " + line);
		}

		//Output to logfile
		FileUtils.writeFileAppend("test.log", line + "\n");
	}

	public static void log(String line)
	{
		log(line, "");
	}

	public static void error(String errorSource, String line)
	{
		System.err.println(errorSource + " - ERROR: " + line);
	}
}

Add logging to a target, for creating logfiles for seperate channels later


package uk.ac.ebi.spot.goci.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 * Created by emma on 27/11/14.
 *
 * @author emma
 *         <p>
 *         Model object representing status assigned to studies
 */

@Entity
public class CurationStatus {
    @Id
    @GeneratedValue
    private Long id;

    private String status;

    private String seqnbr;

    // JPA no-args constructor
    public CurationStatus() {
    }

    public CurationStatus(Long id, String curationStatus, String seqnbr) {
        this.id = id;
        this.status = curationStatus;
        this.seqnbr = seqnbr;
    }

    public Long getId() {
        return id;
    }

    public String getStatus() {
        return status;
    }

    public String getSeqnbr() {
        return seqnbr;
    }

    @Override
    public String toString() {
        return "CurationStatus{" +
                "id=" + id +
                ", curationStatus='" + status + '\'' +
                ", seqnbr='" + seqnbr + '\'' +
                '}';
    }
}

package uk.ac.ebi.spot.goci.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 * Created by emma on 27/11/14.
 *
 * @author emma
 *         <p>
 *         Model object representing status assigned to studies
 */

@Entity
public class CurationStatus {
    @Id
    @GeneratedValue
    private Long id;

    private String status;

    private String seqnbr;

    // JPA no-args constructor
    public CurationStatus() {
    }

    public CurationStatus(Long id, String curationStatus, String seqnbr) {
        this.id = id;
        this.status = curationStatus;
        this.seqnbr = seqnbr;
    }

    public Long getId() {
        return id;
    }

    public String getStatus() {
        return status;
    }

    public String getSeqnbr() {
        return seqnbr;
    }

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

    public void setStatus(String status) {
        this.status = status;
    }

    public void setSeqnbr(String seqnbr) {
        this.seqnbr = seqnbr;
    }
}

Remove toString method, add setters

Remove toString method, add setters


package com.palantir.atlasdb.keyvalue.partition;

import com.palantir.atlasdb.keyvalue.api.RangeRequest;
import com.palantir.common.annotation.Immutable;

@Immutable public class ConsistentRingRangeRequest {
    private final RangeRequest rangeRequest;
    public RangeRequest get() {
        return rangeRequest;
    }
    private ConsistentRingRangeRequest(RangeRequest rangeRequest) {
        this.rangeRequest = rangeRequest;
    }
    public static ConsistentRingRangeRequest of(RangeRequest rangeRequest) {
        return new ConsistentRingRangeRequest(rangeRequest);
    }
    public String toString() {
        return "CRRR=[" + rangeRequest + "]";
    }
}

package com.palantir.atlasdb.keyvalue.partition;

import com.palantir.atlasdb.keyvalue.api.RangeRequest;
import com.palantir.common.annotation.Immutable;

@Immutable public class ConsistentRingRangeRequest {
    private final RangeRequest rangeRequest;
    public RangeRequest get() {
        return rangeRequest;
    }
    private ConsistentRingRangeRequest(RangeRequest rangeRequest) {
        this.rangeRequest = rangeRequest;
    }
    public static ConsistentRingRangeRequest of(RangeRequest rangeRequest) {
        return new ConsistentRingRangeRequest(rangeRequest);
    }
    public String toString() {
        return "CRRR=[" + rangeRequest + "]";
    }
    @Override
    public boolean equals(Object other) {
        if (other instanceof ConsistentRingRangeRequest == false) {
            return false;
        }
        ConsistentRingRangeRequest otherCrrr = (ConsistentRingRangeRequest) other;
        return get().equals(otherCrrr.get());
    }
}

Add equals impl to CRRR

Add equals impl to CRRR


package protocolsupport.protocol.transformer.middlepacketimpl.serverbound.play.v_1_4_1_5_1_6_1_7;

import java.io.IOException;

import net.minecraft.server.v1_9_R1.BlockPosition;
import protocolsupport.protocol.PacketDataSerializer;
import protocolsupport.protocol.transformer.middlepacket.serverbound.play.MiddleBlockPlace;

public class BlockPlace extends MiddleBlockPlace {

	@Override
	public void readFromClientData(PacketDataSerializer serializer) throws IOException {
		position = new BlockPosition(serializer.readInt(), serializer.readUnsignedByte(), serializer.readInt());
		face = serializer.readUnsignedByte();
		cX = serializer.readUnsignedByte();
		cY = serializer.readUnsignedByte();
		cZ = serializer.readUnsignedByte();
	}

}

package protocolsupport.protocol.transformer.middlepacketimpl.serverbound.play.v_1_4_1_5_1_6_1_7;

import java.io.IOException;

import net.minecraft.server.v1_9_R1.BlockPosition;
import protocolsupport.protocol.PacketDataSerializer;
import protocolsupport.protocol.transformer.middlepacket.serverbound.play.MiddleBlockPlace;

public class BlockPlace extends MiddleBlockPlace {

	@Override
	public void readFromClientData(PacketDataSerializer serializer) throws IOException {
		position = new BlockPosition(serializer.readInt(), serializer.readUnsignedByte(), serializer.readInt());
		face = serializer.readUnsignedByte();
		serializer.readItemStack();
		cX = serializer.readUnsignedByte();
		cY = serializer.readUnsignedByte();
		cZ = serializer.readUnsignedByte();
	}

}

Fix block place packet reading

Fix block place packet reading


package com.servinglynk.hmis.warehouse.service.converter;

import com.servinglynk.hmis.warehouse.core.model.EnrollmentCoc;
public class EnrollmentCocConverter  extends BaseConverter {

   public static com.servinglynk.hmis.warehouse.model.v2014.EnrollmentCoc modelToEntity (EnrollmentCoc model ,com.servinglynk.hmis.warehouse.model.v2014.EnrollmentCoc entity) {
       if(entity==null) entity = new com.servinglynk.hmis.warehouse.model.v2014.EnrollmentCoc();
       	  entity.setId(model.getEnrollmentCocId());
          entity.setCocCode(model.getCocCode());
       return entity;
   }

   public static EnrollmentCoc entityToModel (com.servinglynk.hmis.warehouse.model.v2014.EnrollmentCoc entity) {
       EnrollmentCoc model = new EnrollmentCoc();
       model.setEnrollmentCocId(entity.getId());
       model.setCocCode(entity.getCocCode());
       model.setEnrollmentId(entity.getEnrollmentid().getId());
       model.setProjectCocId(entity.getProjectCoc().getId());
       model.setDateCreated(entity.getDateCreated());
       model.setDateUpdated(entity.getDateUpdated());
       return model;
   }

}

package com.servinglynk.hmis.warehouse.service.converter;

import com.servinglynk.hmis.warehouse.core.model.EnrollmentCoc;
public class EnrollmentCocConverter  extends BaseConverter {

   public static com.servinglynk.hmis.warehouse.model.v2014.EnrollmentCoc modelToEntity (EnrollmentCoc model ,com.servinglynk.hmis.warehouse.model.v2014.EnrollmentCoc entity) {
       if(entity==null) entity = new com.servinglynk.hmis.warehouse.model.v2014.EnrollmentCoc();
       	  entity.setId(model.getEnrollmentCocId());
          entity.setCocCode(model.getCocCode());
       return entity;
   }

   public static EnrollmentCoc entityToModel (com.servinglynk.hmis.warehouse.model.v2014.EnrollmentCoc entity) {
       EnrollmentCoc model = new EnrollmentCoc();
       model.setEnrollmentCocId(entity.getId());
       model.setCocCode(entity.getCocCode());
       model.setEnrollmentId(entity.getEnrollmentid() !=null ? entity.getEnrollmentid().getId() : null);
       model.setProjectCocId(entity.getProjectCoc() !=null ? entity.getProjectCoc().getId() : null);
       model.setDateCreated(entity.getDateCreated());
       model.setDateUpdated(entity.getDateUpdated());
       return model;
   }

}

Fix NPE in the enrollmentcoc api

Fix NPE in the enrollmentcoc api


package org.javarosa.xml.util;

import org.javarosa.core.services.locale.Localization;

/**
 * Invalid structure error that can _potentially_ be recovered from via
 * advanced user intervention. Useful for notifying the user that the issue lies
 * on the server.
 *
 * @author Phillip Mates (pmates@dimagi.com).
 */
public class ActionableInvalidStructureException extends InvalidStructureException {
    private String localizationKey;
    private String[] localizationParameters;

    public ActionableInvalidStructureException(String localizationKey,
                                                String[] localizationParameters,
                                                String message) {
        super(message);
        this.localizationKey = localizationKey;
        this.localizationParameters = localizationParameters;
    }

    @Override
    public String getLocalizedMessage() {
        if (localizationKey != null) {
            return Localization.get(localizationKey, localizationParameters);
        } else {
            return getMessage();
        }
    }
}

package org.javarosa.xml.util;

import org.javarosa.core.services.locale.Localization;
import org.javarosa.core.util.NoLocalizedTextException;

/**
 * Invalid structure error that can _potentially_ be recovered from via
 * advanced user intervention. Useful for notifying the user that the issue lies
 * on the server.
 *
 * @author Phillip Mates (pmates@dimagi.com).
 */
public class ActionableInvalidStructureException extends InvalidStructureException {
    private String localizationKey;
    private String[] localizationParameters;

    public ActionableInvalidStructureException(String localizationKey,
                                                String[] localizationParameters,
                                                String message) {
        super(message);
        this.localizationKey = localizationKey;
        this.localizationParameters = localizationParameters;
    }

    @Override
    public String getLocalizedMessage() {
        if (localizationKey != null) {
            try {
                return Localization.get(localizationKey, localizationParameters);
            } catch (NoLocalizedTextException e) {
                return getMessage();
            }
        } else {
            return getMessage();
        }
    }
}

Add error handling for localization failures


/*
 * Copyright 2015-2017 Hewlett Packard Enterprise Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.frontend.find.idol.parametricfields;

import com.hp.autonomy.frontend.find.core.parametricfields.AbstractParametricValuesServiceIT;

public class IdolParametricValuesServiceIT extends AbstractParametricValuesServiceIT {}

/*
 * Copyright 2015-2017 Hewlett Packard Enterprise Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.frontend.find.idol.parametricfields;

import com.hp.autonomy.frontend.find.core.parametricfields.AbstractParametricValuesServiceIT;
import org.springframework.test.annotation.DirtiesContext;

@DirtiesContext
public class IdolParametricValuesServiceIT extends AbstractParametricValuesServiceIT {}

Add @DirtiesContext for test preceding the failing test


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

package io.undertow.servlet.core;

import io.undertow.server.HttpServerExchange;
import io.undertow.servlet.api.ThreadSetupAction;

/**
 * @author Stuart Douglas
 */
public class ContextClassLoaderSetupAction implements ThreadSetupAction {

    private final ClassLoader classLoader;

    public ContextClassLoaderSetupAction(final ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    @Override
    public Handle setup(final HttpServerExchange exchange) {
        final ClassLoader old = SecurityActions.getContextClassLoader();
        Thread.currentThread().setContextClassLoader(classLoader);
        return new Handle() {
            @Override
            public void tearDown() {
                SecurityActions.setContextClassLoader(old);
            }
        };
    }
}

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

package io.undertow.servlet.core;

import io.undertow.server.HttpServerExchange;
import io.undertow.servlet.api.ThreadSetupAction;

/**
 * @author Stuart Douglas
 */
public class ContextClassLoaderSetupAction implements ThreadSetupAction {

    private final ClassLoader classLoader;

    public ContextClassLoaderSetupAction(final ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    @Override
    public Handle setup(final HttpServerExchange exchange) {
        final ClassLoader old = SecurityActions.getContextClassLoader();
        SecurityActions.setContextClassLoader(classLoader);
        return new Handle() {
            @Override
            public void tearDown() {
                SecurityActions.setContextClassLoader(old);
            }
        };
    }
}

Use SecurityActions to set the TCCL

Use SecurityActions to set the TCCL


package io.quarkus.hibernate.orm.runtime.customized;

import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;

import org.hibernate.engine.transaction.jta.platform.internal.AbstractJtaPlatform;

public final class QuarkusJtaPlatform extends AbstractJtaPlatform {

    public static final QuarkusJtaPlatform INSTANCE = new QuarkusJtaPlatform();

    private QuarkusJtaPlatform() {
        //nothing
    }

    @Override
    protected TransactionManager locateTransactionManager() {
        return com.arjuna.ats.jta.TransactionManager.transactionManager();
    }

    @Override
    protected UserTransaction locateUserTransaction() {
        return com.arjuna.ats.jta.UserTransaction.userTransaction();
    }

}

package io.quarkus.hibernate.orm.runtime.customized;

import javax.transaction.Synchronization;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;

import org.hibernate.engine.transaction.jta.platform.internal.JtaSynchronizationStrategy;
import org.hibernate.engine.transaction.jta.platform.internal.TransactionManagerAccess;
import org.hibernate.engine.transaction.jta.platform.internal.TransactionManagerBasedSynchronizationStrategy;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;

public final class QuarkusJtaPlatform implements JtaPlatform, TransactionManagerAccess {

    public static final QuarkusJtaPlatform INSTANCE = new QuarkusJtaPlatform();

    private final JtaSynchronizationStrategy tmSynchronizationStrategy = new TransactionManagerBasedSynchronizationStrategy(
            this);
    private volatile TransactionManager transactionManager;
    private volatile UserTransaction userTransaction;

    private QuarkusJtaPlatform() {
        //nothing
    }

    @Override
    public TransactionManager retrieveTransactionManager() {
        TransactionManager transactionManager = this.transactionManager;
        if (transactionManager == null) {
            transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager();
            this.transactionManager = transactionManager;
        }
        return transactionManager;
    }

    @Override
    public TransactionManager getTransactionManager() {
        return retrieveTransactionManager();
    }

    @Override
    public UserTransaction retrieveUserTransaction() {
        UserTransaction userTransaction = this.userTransaction;
        if (this.userTransaction == null) {
            userTransaction = com.arjuna.ats.jta.UserTransaction.userTransaction();
            this.userTransaction = userTransaction;
        }
        return userTransaction;
    }

    @Override
    public Object getTransactionIdentifier(final Transaction transaction) {
        return transaction;
    }

    @Override
    public void registerSynchronization(Synchronization synchronization) {
        this.tmSynchronizationStrategy.registerSynchronization(synchronization);
    }

    @Override
    public boolean canRegisterSynchronization() {
        return this.tmSynchronizationStrategy.canRegisterSynchronization();
    }

    @Override
    public int getCurrentStatus() throws SystemException {
        return this.retrieveTransactionManager().getStatus();
    }

}

Reimplement the QuarkusJTAPlatform to avoid leaking the ORM registry


// JSPyIterableObject.java

/**
*    Copyright (C) 2008 10gen Inc.
*
*    This program is free software: you can redistribute it and/or  modify
*    it under the terms of the GNU Affero General Public License, version 3,
*    as published by the Free Software Foundation.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU 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 ed.lang.python;

import java.util.*;

import org.python.core.*;

public class JSPyIterableObject extends JSPyObjectWrapper implements Iterable {
    public JSPyIterableObject( PyObject p ){
        super(p);
    }

    public Iterator iterator(){
        return _p.asIterable().iterator();
    }
}

// JSPyIterableObject.java

/**
*    Copyright (C) 2008 10gen Inc.
*
*    This program is free software: you can redistribute it and/or  modify
*    it under the terms of the GNU Affero General Public License, version 3,
*    as published by the Free Software Foundation.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU 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 ed.lang.python;

import java.util.*;

import org.python.core.*;

public class JSPyIterableObject extends JSPyObjectWrapper implements Iterable {
    public JSPyIterableObject( PyObject p ){
        super(p);
    }

    public Iterator iterator(){
        return new IterWrapper( _p.asIterable().iterator() );
    }

    class IterWrapper implements Iterator {
        Iterator _iter;
        IterWrapper( Iterator i ){
            _iter = i;
        }
        public Object next(){
            return Python.toJS( next() );
        }
    }
}

Convert iterated Python objects to JS.

Convert iterated Python objects to JS.


/*******************************************************************************
 * Copyright (c) 2007 Actuate Corporation.
 * 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:
 *  Actuate Corporation  - initial API and implementation
 *******************************************************************************/

package org.eclipse.birt.report.designer.ui.extensions;

import org.eclipse.birt.report.model.api.DesignElementHandle;

/**
 * ReportItemViewAdapter
 */
public abstract class ReportItemViewAdapter implements IReportItemViewProvider
{

	/*
	 * (non-Javadoc)
	 *
	 * @see org.eclipse.birt.report.designer.ui.extensions.IReportItemViewProvider#createView(org.eclipse.birt.report.model.api.DesignElementHandle)
	 */
	public DesignElementHandle createView( DesignElementHandle host )
	{
		return null;
	}

}

/*******************************************************************************
 * Copyright (c) 2007 Actuate Corporation.
 * 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:
 *  Actuate Corporation  - initial API and implementation
 *******************************************************************************/

package org.eclipse.birt.report.designer.ui.extensions;

import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.model.api.DesignElementHandle;

/**
 * ReportItemViewAdapter
 */
public abstract class ReportItemViewAdapter implements IReportItemViewProvider
{

	/*
	 * (non-Javadoc)
	 *
	 * @see org.eclipse.birt.report.designer.ui.extensions.IReportItemViewProvider#createView(org.eclipse.birt.report.model.api.DesignElementHandle)
	 */
	public DesignElementHandle createView( DesignElementHandle host ) throws BirtException
	{
		return null;
	}

}

Add BirtException declaration on createView method.