package com.orientechnologies.orient.core.storage.impl.local;

import com.orientechnologies.common.concur.lock.OInterruptedException;
import com.orientechnologies.common.log.OLogManager;

public class OStorageInterruptionManager {

  private int depth = 0;
  private boolean interrupted = false;

  protected void interrupt(Thread thread) {
    synchronized (this) {
      if (depth <= 0) {
        interrupted = true;
      } else if (thread != null) {
        thread.interrupt();
      }
    }
  }

  protected void enterCriticalPath() {
    synchronized (this) {
      if (Thread.currentThread().isInterrupted() || (interrupted && depth == 0)) {
        final Thread thread = Thread.currentThread();
        //        thread.interrupt();
        OLogManager.instance().warnNoDb(this, "Execution  of thread '%s' is interrupted", thread);
        throw new OInterruptedException("Command interrupted");
      }
      this.depth++;
    }
  }

  protected void exitCriticalPath() {
    synchronized (this) {
      this.depth--;
      if (interrupted && depth == 0) {
        final Thread thread = Thread.currentThread();
        //        thread.interrupt();
        OLogManager.instance().warnNoDb(this, "Execution  of thread '%s' is interrupted", thread);
        throw new OInterruptedException("Command interrupted");
      }
    }
  }
}

package com.orientechnologies.orient.core.storage.impl.local;

import com.orientechnologies.common.concur.lock.OInterruptedException;
import com.orientechnologies.common.log.OLogManager;

public class OStorageInterruptionManager {

  private int depth = 0;
  private boolean interrupted = false;

  protected void interrupt(Thread thread) {
    synchronized (this) {
      if (depth <= 0) {
        interrupted = true;
      } else if (thread != null) {
        thread.interrupt();
      }
    }
  }

  public void enterCriticalPath() {
    synchronized (this) {
      if (Thread.currentThread().isInterrupted() || (interrupted && depth == 0)) {
        final Thread thread = Thread.currentThread();
        //        thread.interrupt();
        OLogManager.instance().warnNoDb(this, "Execution  of thread '%s' is interrupted", thread);
        throw new OInterruptedException("Command interrupted");
      }
      this.depth++;
    }
  }

  public void exitCriticalPath() {
    synchronized (this) {
      this.depth--;
      if (interrupted && depth == 0) {
        final Thread thread = Thread.currentThread();
        //        thread.interrupt();
        OLogManager.instance().warnNoDb(this, "Execution  of thread '%s' is interrupted", thread);
        throw new OInterruptedException("Command interrupted");
      }
    }
  }
}

Change visibility of storage interruption manager


package com.github.aureliano.edocs.app.gui.menu;

import javax.swing.JMenuBar;

public class MenuBar extends JMenuBar {

	private static final long serialVersionUID = 5179328504511930019L;

	public MenuBar() {
		this.addMenus();
	}

	private void addMenus() {
		super.add(new FileMenu());
	}
}

package com.github.aureliano.edocs.app.gui.menu;

import javax.swing.JMenuBar;

public class MenuBar extends JMenuBar {

	private static final long serialVersionUID = 5179328504511930019L;

	private FileMenu fileMenu;
	private DocumentMenu documentMenu;

	public MenuBar() {
		this.addMenus();
	}

	private void addMenus() {
		this.fileMenu = new FileMenu();
		this.documentMenu = new DocumentMenu();

		super.add(this.fileMenu);
		super.add(this.documentMenu);
	}
}

Add document menu to menu bar.

Add document menu to menu bar.


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

/**
 * Given a integer, can you write a method to transform a given integer to String? Take into
 * account
 * you can receive negative integers.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class IntToString {

  public String transform(int number) {
    return null;
  }

}

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

/**
 * Given a integer, can you write a method to transform a given integer to String? Take into
 * account
 * you can receive negative integers.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class IntToString {

  /**
   * Algorithm implementation based on the module of a given number and iterate until the number is
   * zero. With this approach we get a complexity order equals to O(N) in time terms where N is the
   * number of digits in the given integer. In space terms, the complexity order is also O(N)
   * because we are using an StringBuilder as auxiliary data structure.
   */
  public String transform(int number) {
    boolean isNegative = false;
    StringBuilder sb = new StringBuilder();
    if (number == 0) {
      return "0";
    } else if (number < 0) {
      isNegative = true;
    }
    number = Math.abs(number);

    while (number > 0) {
      sb.append(number % 10);
      number /= 10;
    }

    if (isNegative) {
      sb.append("-");
    }

    return sb.reverse().toString();
  }
}

Add implementation to problem 11

Add implementation to problem 11


/*
 * 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();
	}

}

/*
 * 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.NamesFromClassResources;
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, new NamesFromClassResources(options.match())).run();
	}

}

Update client to account for change in signature.

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


/*
 * #%L
 * wcm.io
 * %%
 * Copyright (C) 2014 wcm.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.
 * #L%
 */
/**
 * Miscellaneous helper classes.
 */
@org.osgi.annotation.versioning.Version("0.5.0")
package io.wcm.sling.commons.util;

/*
 * #%L
 * wcm.io
 * %%
 * Copyright (C) 2014 wcm.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.
 * #L%
 */
/**
 * Miscellaneous helper classes.
 */
@org.osgi.annotation.versioning.Version("0.6.0")
package io.wcm.sling.commons.util;

Add Escape.jcrQueryLiteral and Escape.jcrQueryContainsExpr methods.


/*
 * Copyright 2015-2016 the original author or authors.
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution and is available at
 *
 * http://www.eclipse.org/legal/epl-v10.html
 */

package extensions;

import org.junit.gen5.api.Assertions;
import org.junit.gen5.api.extension.AfterEachExtensionPoint;
import org.junit.gen5.api.extension.ExceptionHandlerExtensionPoint;
import org.junit.gen5.api.extension.ExtensionContext.Namespace;
import org.junit.gen5.api.extension.ExtensionContext.Store;
import org.junit.gen5.api.extension.TestExtensionContext;
import org.opentest4j.AssertionFailedError;

public class ExpectToFailExtension implements ExceptionHandlerExtensionPoint, AfterEachExtensionPoint {

	@Override
	public void handleException(TestExtensionContext context, Throwable throwable) throws Throwable {
		if (throwable instanceof AssertionFailedError) {
			getExceptionStore(context).put("exception", throwable);
			return;
		}
		throw throwable;
	}

	private Store getExceptionStore(TestExtensionContext context) {
		return context.getStore(Namespace.of(context));
	}

	@Override
	public void afterEach(TestExtensionContext context) throws Exception {
		if (getExceptionStore(context).get("exception") == null)
			Assertions.fail("Test should have failed");
	}
}

/*
 * Copyright 2015-2016 the original author or authors.
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution and is available at
 *
 * http://www.eclipse.org/legal/epl-v10.html
 */

package extensions;

import static org.junit.gen5.api.Assertions.assertNotNull;

import org.junit.gen5.api.extension.AfterEachExtensionPoint;
import org.junit.gen5.api.extension.ExceptionHandlerExtensionPoint;
import org.junit.gen5.api.extension.ExtensionContext.Namespace;
import org.junit.gen5.api.extension.ExtensionContext.Store;
import org.junit.gen5.api.extension.TestExtensionContext;
import org.opentest4j.AssertionFailedError;

public class ExpectToFailExtension implements ExceptionHandlerExtensionPoint, AfterEachExtensionPoint {

	@Override
	public void handleException(TestExtensionContext context, Throwable throwable) throws Throwable {
		if (throwable instanceof AssertionFailedError) {
			getExceptionStore(context).put("exception", throwable);
			return;
		}
		throw throwable;
	}

	@Override
	public void afterEach(TestExtensionContext context) throws Exception {
		assertNotNull(getExceptionStore(context).get("exception"), "Test should have failed");
	}

	private Store getExceptionStore(TestExtensionContext context) {
		return context.getStore(Namespace.of(context));
	}
}

Use assertNotNull instead of `if`

Use assertNotNull instead of `if`


package devopsdistilled.operp.server.data.repo.items.custom.impl;

import javax.inject.Inject;

import devopsdistilled.operp.server.data.repo.items.ProductRepository;
import devopsdistilled.operp.server.data.repo.items.custom.ProductRepositoryCustom;

public class ProductRepositoryCustomImpl implements ProductRepositoryCustom {
	@Inject
	private ProductRepository repo;

}

package devopsdistilled.operp.server.data.repo.items.custom.impl;

import devopsdistilled.operp.server.data.repo.items.custom.ProductRepositoryCustom;

public class ProductRepositoryCustomImpl implements ProductRepositoryCustom {

}

Remove warning message by removing unused field

OPEN - task 32: Add "Create Item" functionalities
http://github.com/DevOpsDistilled/OpERP/issues/issue/32


//
// TrueRandom.java -- Java class TrueRandom
// Project OrcSites
//
// Copyright (c) 2009 The University of Texas at Austin. All rights reserved.
//
// Use and redistribution of this file is governed by the license terms in
// the LICENSE file found in the project's top-level directory and also found at
// URL: http://orc.csres.utexas.edu/license.shtml .
//

package orc.lib.net;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import orc.error.runtime.JavaException;
import orc.error.runtime.TokenException;
import orc.values.sites.compatibility.Args;
import orc.values.sites.compatibility.EvalSite;

public class TrueRandom extends EvalSite {
    private static String baseURL = "http://www.random.org/integers/?num=1&col=1&base=10&format=plain&rnd=new";

    @Override
    public Object evaluate(final Args args) throws TokenException {
        try {
            final String number = HTTPUtils.getURL(new URL(baseURL + "&min=" + args.longArg(0) + "&max=" + (args.longArg(1) - 1)));
            return new Long(number.trim());
        } catch (final MalformedURLException e) {
            throw new JavaException(e);
        } catch (final IOException e) {
            throw new JavaException(e);
        }
    }
}

//
// TrueRandom.java -- Java class TrueRandom
// Project OrcSites
//
// Copyright (c) 2009 The University of Texas at Austin. All rights reserved.
//
// Use and redistribution of this file is governed by the license terms in
// the LICENSE file found in the project's top-level directory and also found at
// URL: http://orc.csres.utexas.edu/license.shtml .
//

package orc.lib.net;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import orc.error.runtime.JavaException;
import orc.error.runtime.TokenException;
import orc.values.sites.compatibility.Args;
import orc.values.sites.compatibility.EvalSite;

public class TrueRandom extends EvalSite {
	private static String baseURL = "https://www.random.org/integers/?num=1&col=1&base=10&format=plain&rnd=new";

    @Override
    public Object evaluate(final Args args) throws TokenException {
        try {
            final String number = HTTPUtils.getURL(new URL(baseURL + "&min=" + args.longArg(0) + "&max=" + (args.longArg(1) - 1)));
            return new Long(number.trim());
        } catch (final MalformedURLException e) {
            throw new JavaException(e);
        } catch (final IOException e) {
            throw new JavaException(e);
        }
    }
}

Fix URL to be HTTPS.

Fix URL to be HTTPS.

random.org now redirects to HTTPS and we don't handle the redirect
correctly, but if we start on HTTPS there is no redirect.


/*
 * -\-\-
 * Spotify Apollo okhttp Client Module
 * --
 * Copyright (C) 2013 - 2015 Spotify AB
 * --
 * 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.spotify.apollo.http.client;

import org.mockserver.mock.action.ExpectationCallback;
import org.mockserver.model.HttpRequest;
import org.mockserver.model.HttpResponse;

public class SleepCallback implements ExpectationCallback {

  @Override
  public HttpResponse handle(final HttpRequest httpRequest) {
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      return HttpResponse.response().withStatusCode(500);
    }
    return HttpResponse.response().withStatusCode(200);
  }
}

Fix needed trailing spaces in the license


/*******************************************************************************
 * Copyright (c) 2010 Oak Ridge National Laboratory.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 ******************************************************************************/
package org.csstudio.display.pvtable.ui;

import org.csstudio.display.pvtable.model.PVTableItem;
import org.eclipse.jface.viewers.CellLabelProvider;

/** Cell label provider for PV Table that handles the tool tip
 *  @author Kay Kasemir
 */
abstract public class PVTableCellLabelProvider extends CellLabelProvider
{
    private static final int TOOL_TIP_MAX = 100;

    @Override
    public String getToolTipText(final Object element)
    {
        final PVTableItem item = (PVTableItem) element;
        final String text = item.toString();
        // Limit size of tool tip (in case of array data)
        if (text.length() > TOOL_TIP_MAX)
            return text.substring(0, TOOL_TIP_MAX) + "...";
        return text;
    }
}

/*******************************************************************************
 * Copyright (c) 2010 Oak Ridge National Laboratory.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 ******************************************************************************/
package org.csstudio.display.pvtable.ui;

import org.csstudio.display.pvtable.model.PVTableItem;
import org.eclipse.jface.viewers.CellLabelProvider;

/** Cell label provider for PV Table that handles the tool tip
 *  @author Kay Kasemir
 */
abstract public class PVTableCellLabelProvider extends CellLabelProvider
{
    private static final int TOOL_TIP_MAX = 100;

    @Override
    public String getToolTipText(final Object element)
    {
        final PVTableItem item = (PVTableItem) element;
        if (item == PVTableModelContentProvider.NEW_ITEM)
            return "Add new PV to table by adding its name";
        final String text = item.toString();
        // Limit size of tool tip (in case of array data)
        if (text.length() > TOOL_TIP_MAX)
            return text.substring(0, TOOL_TIP_MAX) + "...";
        return text;
    }
}

Fix tool tip of last row

display.pvtable: Fix tool tip of last row


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

package org.openmhealth.dsu.configuration;

/**
 * An interface containing shared properties for OAuth2 configurations.
 *
 * @author Emerson Farrugia
 */
public interface OAuth2Properties {

    String CLIENT_ROLE = "ROLE_CLIENT";
    String END_USER_ROLE = "ROLE_END_USER";
    String DATA_POINT_RESOURCE_ID = "dataPoints";
    String DATA_POINT_READ_SCOPE = "read_data_points";
    String DATA_POINT_WRITE_SCOPE = "write_data_points";
    String DATA_POINT_DELETE_SCOPE = "delete_data_points";
}

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

package org.openmhealth.dsu.configuration;

/**
 * An interface containing shared properties for OAuth2 configurations.
 *
 * @author Emerson Farrugia
 */
public interface OAuth2Properties {

    String CLIENT_ROLE = "ROLE_CLIENT";
    String END_USER_ROLE = "ROLE_END_USER";
    String DATA_POINT_RESOURCE_ID = "dataPoint";
    String DATA_POINT_READ_SCOPE = "read_data_points";
    String DATA_POINT_WRITE_SCOPE = "write_data_points";
    String DATA_POINT_DELETE_SCOPE = "delete_data_points";
}

Use old resource ID, so it's backward compatible with existing tokens.


/*
 * Copyright 2014 A.C.R. Development
 */
package acr.browser.lightning;

public class SettingsController {

	static boolean clearHistory = false;

	/**
	 * The purpose of this class is so that I can clear the dropdown history in the main activities if the user selects
	 * to clear the history from the disk in advanced settings
	 */
	static void setClearHistory(boolean choice) {
		clearHistory = choice;
	}

	/**
	 * return the choice
	 */
	static boolean getClearHistory() {
		if (clearHistory) {
			clearHistory = false;
			return true;
		}
		return clearHistory;
	}
}

/*
 * Copyright 2014 A.C.R. Development
 */
package acr.browser.lightning;

public class SettingsController {

	private static boolean clearHistory;

	/**
	 * The purpose of this class is so that I can clear the dropdown history in the main activities if the user selects
	 * to clear the history from the disk in advanced settings
	 */
	public static void setClearHistory(boolean choice) {
		clearHistory = choice;
	}

	/**
	 * return the choice
	 */
	public static boolean getClearHistory() {
		if (clearHistory) {
			clearHistory = false;
			return true;
		}
		return false;
	}
}

Add missing 'private' and 'public' access' modifiers, fix warnings


package io.tracee.contextlogger.jaxws.container;

/**
 * This class is not directly used but exists for the users convenience
 * (Like adding @HandlerChain(xmlFile=TraceeContextLoggerJaxwsConstants.TRACEE_WITH_ERROR_LOGGING_HANDLER_CHAIN_URL)
 */
@SuppressWarnings("UnusedDeclaration")
public final class TraceeContextLoggerJaxwsConstants {

	private TraceeContextLoggerJaxwsConstants() { }

	public static final String TRACEE_WITH_ERROR_LOGGING_HANDLER_CHAIN_URL =
			"/src/main/resources/io/tracee/contextlogger/jaxws/TraceeWithErrorLoggingHandlerChain.xml";

}

package io.tracee.contextlogger.jaxws.container;

/**
 * This class is not directly used but exists for the users convenience
 * (Like adding @HandlerChain(xmlFile=TraceeContextLoggerJaxwsConstants.TRACEE_WITH_ERROR_LOGGING_HANDLER_CHAIN_URL)
 */
@SuppressWarnings("UnusedDeclaration")
public final class TraceeContextLoggerJaxwsConstants {

	private TraceeContextLoggerJaxwsConstants() { }

	public static final String TRACEE_WITH_ERROR_LOGGING_HANDLER_CHAIN_URL =
			"/io/tracee/contextlogger/jaxws/TraceeWithErrorLoggingHandlerChain.xml";

}

Adjust path: If the file is assembled with the xml file into a jar file, the project structure is discarded.


/**
 *
 */
package jp.ac.nii.prl.mape.monitoring.service;

import org.springframework.stereotype.Service;

import jp.ac.nii.prl.mape.monitoring.model.Instance;

@Service("instanceService")
public class InstanceServiceImpl implements InstanceService {

	/* (non-Javadoc)
	 * @see jp.ac.nii.prl.mape.monitoring.service.InstanceService#fromAWS(com.amazonaws.services.ec2.model.Instance)
	 */
	@Override
	public Instance fromAWS(com.amazonaws.services.ec2.model.Instance aws) {
		Instance instance = new Instance();
		instance.setAmi(aws.getImageId());
		instance.setInstID(aws.getInstanceId());
		instance.setInstStatus(0);
		instance.setInstType(aws.getInstanceType());
		instance.setSecurityGroupRef(aws.getSecurityGroups().iterator().next().getGroupId());
		instance.setState(aws.getState().getCode());
		return instance;
	}

}

/**
 *
 */
package jp.ac.nii.prl.mape.monitoring.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jp.ac.nii.prl.mape.monitoring.model.Instance;

@Service("instanceService")
public class InstanceServiceImpl implements InstanceService {

	private final CloudWatchService cwService;

	@Autowired
	public InstanceServiceImpl(CloudWatchService cwService) {
		this.cwService = cwService;
	}

	/* (non-Javadoc)
	 * @see jp.ac.nii.prl.mape.monitoring.service.InstanceService#fromAWS(com.amazonaws.services.ec2.model.Instance)
	 */
	@Override
	public Instance fromAWS(com.amazonaws.services.ec2.model.Instance aws) {
		Instance instance = new Instance();
		instance.setAmi(aws.getImageId());
		instance.setInstID(aws.getInstanceId());
		instance.setInstStatus(0);
		instance.setInstType(aws.getInstanceType());
		instance.setSecurityGroupRef(aws.getSecurityGroups().iterator().next().getGroupId());
		instance.setState(aws.getState().getCode());
		instance.setLoad(cwService.getLoad(instance.getInstID()));
		return instance;
	}

}

Include instance load in instance creation


package com.yammer.tenacity.testing;

import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.Hystrix;
import com.netflix.hystrix.contrib.yammermetricspublisher.HystrixYammerMetricsPublisher;
import com.netflix.hystrix.strategy.HystrixPlugins;
import org.junit.After;

import java.util.concurrent.TimeUnit;

public abstract class TenacityTest {
    static {
        initialization();
    }

    private static void initialization() {
        HystrixPlugins.getInstance().registerMetricsPublisher(new HystrixYammerMetricsPublisher());
        ConfigurationManager
                .getConfigInstance()
                .setProperty("hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds", "1");
    }

    @After
    public void testTeardown() {
        Hystrix.reset(1, TimeUnit.SECONDS);
    }
}

package com.yammer.tenacity.testing;

import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.Hystrix;
import com.netflix.hystrix.contrib.yammermetricspublisher.HystrixYammerMetricsPublisher;
import com.netflix.hystrix.strategy.HystrixPlugins;
import org.junit.After;
import org.junit.Before;

import java.util.concurrent.TimeUnit;

public abstract class TenacityTest {
    static {
        HystrixPlugins.getInstance().registerMetricsPublisher(new HystrixYammerMetricsPublisher());
    }

    @Before
    public void testInitialization() {
        ConfigurationManager
                .getConfigInstance()
                .setProperty("hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds", "1");
    }

    @After
    public void testTeardown() {
        Hystrix.reset(1, TimeUnit.SECONDS);
        ConfigurationManager.getConfigInstance().clear();
    }
}

Reset the ConfigurationManager when testing Tenacity


package net.daverix.slingerorm.sample;

import android.provider.BaseColumns;
import net.daverix.slingerorm.annotation.DatabaseEntity;
import net.daverix.slingerorm.annotation.FieldName;
import net.daverix.slingerorm.annotation.GetField;
import net.daverix.slingerorm.annotation.SetField;

/**
 * Created by daverix on 2/2/14.
 */
@DatabaseEntity
public abstract class AbstractComplexEntity {
    @FieldName(BaseColumns._ID) private long _id;

    @GetField("_id")
    public long getId() {
        return _id;
    }

    @SetField("_id")
    public void setId(long id) {
        _id = id;
    }

}

package net.daverix.slingerorm.sample;

import net.daverix.slingerorm.annotation.DatabaseEntity;
import net.daverix.slingerorm.annotation.FieldName;
import net.daverix.slingerorm.annotation.GetField;
import net.daverix.slingerorm.annotation.SetField;

/**
 * Created by daverix on 2/2/14.
 */
@DatabaseEntity
public abstract class AbstractComplexEntity {
    @FieldName("_Id") private long _id;

    @GetField("_id")
    public long getId() {
        return _id;
    }

    @SetField("_id")
    public void setId(long id) {
        _id = id;
    }

}

Change name on id to see that it generates correct


package day01;

import common.BaseSolution;
import common.InputReader;

public class Solution extends BaseSolution implements common.Solution {

    public static void main(String[] args) {
        new Solution().run();
    }

    class BaseFuelCalculator {
        public int calculateFuel() {
            int mass, totalFuel = 0;
            InputReader reader = getInputReader();
            String line = reader.next();
            while (line != null) {
                mass = Integer.parseInt(line);
                totalFuel += getFuel(mass);
                line = reader.next();
            }
            return totalFuel;
        }

        protected int getFuelForMass(int mass) {
            return mass / 3 - 2;
        }

        protected int getFuel(int mass) {
            return 0;
        }
    }

    class Part1FuelCalculator extends BaseFuelCalculator {
        protected int getFuel(int mass) {
            return getFuelForMass(mass);
        }
    }

    class Part2FuelCalculator extends BaseFuelCalculator {
        protected int getFuel(int mass) {
            int fuel = 0;
            int fuelPiece = mass;
            do {
                fuelPiece = getFuelForMass(fuelPiece);
                if (fuelPiece > 0) {
                    fuel += fuelPiece;
                }
            } while (fuelPiece > 0);
            return fuel;
        }
    }

    public String part1() {
        return String.valueOf(new Part1FuelCalculator().calculateFuel());
    }

    public String part2() {
        return String.valueOf(new Part2FuelCalculator().calculateFuel());
    }
}

package day01;

import common.BaseSolution;
import common.InputReader;

public class Solution extends BaseSolution implements common.Solution {

    public static void main(String[] args) {
        new Solution().run();
    }

    class BaseFuelCalculator {
        public int calculateFuel() {
            int mass, totalFuel = 0;
            InputReader reader = getInputReader();
            String line = reader.next();
            while (line != null) {
                mass = Integer.parseInt(line);
                totalFuel += getFuel(mass);
                line = reader.next();
            }
            return totalFuel;
        }

        protected int getFuelForMass(int mass) {
            return mass / 3 - 2;
        }

        protected int getFuel(int mass) {
            return 0;
        }
    }

    class Part1FuelCalculator extends BaseFuelCalculator {
        protected int getFuel(int mass) {
            return getFuelForMass(mass);
        }
    }

    class Part2FuelCalculator extends BaseFuelCalculator {
        protected int getFuel(int mass) {
            int fuel = 0;
            int fuelPiece = getFuelForMass(mass);
            while (fuelPiece > 0) {
                fuel += fuelPiece;
                fuelPiece = getFuelForMass(fuelPiece);
            }
            return fuel;
        }
    }

    public String part1() {
        return String.valueOf(new Part1FuelCalculator().calculateFuel());
    }

    public String part2() {
        return String.valueOf(new Part2FuelCalculator().calculateFuel());
    }
}

Simplify existing day 1 loop

Simplify existing day 1 loop


/**
 * Copyright 2016-2017 Sixt GmbH & Co. Autovermietung KG
 * 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.sixt.service.framework.kafka.messaging;

import com.google.inject.Inject;
import com.sixt.service.framework.ServiceProperties;
import org.apache.kafka.clients.CommonClientConfigs;

import java.util.Properties;

public class ProducerFactory {

    private final ServiceProperties serviceProperties;

    @Inject
    public ProducerFactory(ServiceProperties serviceProperties) {
        this.serviceProperties = serviceProperties;
    }

    public Producer createProducer() {
        String kafkaBootstrapServers = serviceProperties.getKafkaServer();

        Properties kafkaProducerConfig = new Properties();
        kafkaProducerConfig.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, kafkaBootstrapServers);

        return new Producer(kafkaProducerConfig);
    }

}

/**
 * Copyright 2016-2017 Sixt GmbH & Co. Autovermietung KG
 * 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.sixt.service.framework.kafka.messaging;

import com.google.inject.Inject;
import com.sixt.service.framework.ServiceProperties;
import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.clients.producer.ProducerConfig;

import java.util.Properties;

public class ProducerFactory {

    private final ServiceProperties serviceProperties;

    @Inject
    public ProducerFactory(ServiceProperties serviceProperties) {
        this.serviceProperties = serviceProperties;
    }

    public Producer createProducer() {
        String kafkaBootstrapServers = serviceProperties.getKafkaServer();

        Properties kafkaProducerConfig = new Properties();
        kafkaProducerConfig.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, kafkaBootstrapServers);
        kafkaProducerConfig.put(ProducerConfig.ACKS_CONFIG, "all");  // ensure that records have been replicated to other kafka nodes

        return new Producer(kafkaProducerConfig);
    }

}

Set ack to all to ensure records are replicated on other kafka nodes.


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

/**
 * Interfaces and API for input normalization.
 *
 * @since 4.0
 */
@org.gradle.api.Incubating
package org.gradle.normalization;

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

/**
 * Interfaces and API for input normalization.
 *
 * @since 4.0
 */
@org.gradle.api.Incubating
@org.gradle.api.NonNullApi
package org.gradle.normalization;

Cover `org.gradle.normalization` with nullability annotations


package com.craftminecraft.bungee.bungeeban.command;

import com.craftminecraft.bungee.bungeeban.BanManager;

import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.plugin.Command;

public class GUnbanIpCommand extends Command {
	public GUnbanIpCommand() {
		super("gunbanip", "bungeeban.command.gunbanip");
	}
	@Override
	public void execute(CommandSender sender, String[] args) {
		if (args.length != 2) {
			sender.sendMessage(ChatColor.RED + "Wrong command format. <required> [optional]");
			sender.sendMessage(ChatColor.RED + "/gunbanip <ip>");
			return;
		}
		BanManager.gunban(args[0]);
		sender.sendMessage(ChatColor.RED + args[0] + " has been unbanned");
	}

}

package com.craftminecraft.bungee.bungeeban.command;

import com.craftminecraft.bungee.bungeeban.BanManager;

import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.plugin.Command;

public class GUnbanIpCommand extends Command {
	public GUnbanIpCommand() {
		super("gunbanip", "bungeeban.command.gunbanip");
	}
	@Override
	public void execute(CommandSender sender, String[] args) {
		if (args.length != 1) {
			sender.sendMessage(ChatColor.RED + "Wrong command format. <required> [optional]");
			sender.sendMessage(ChatColor.RED + "/gunbanip <ip>");
			return;
		}
		BanManager.gunban(args[0]);
		sender.sendMessage(ChatColor.RED + args[0] + " has been unbanned");
	}

}

Fix gunbanip wanting 2 arguments

Fix gunbanip wanting 2 arguments


package seedu.task.storage;

import javax.xml.bind.annotation.XmlValue;

import seedu.task.commons.exceptions.IllegalValueException;
import seedu.task.model.tag.Tag;

/**
 * JAXB-friendly adapted version of the Tag.
 */
public class XmlAdaptedTag {

    @XmlValue
    public String tagName;

    /**
     * Constructs an XmlAdaptedTag.
     * This is the no-arg constructor that is required by JAXB.
     */
    public XmlAdaptedTag() {}

    /**
     * Converts a given Tag into this class for JAXB use.
     *
     * @param source future changes to this will not affect the created
     */
    public XmlAdaptedTag(Tag source) {
        tagName = source.tagName;
    }

    /**
     * Converts this jaxb-friendly adapted tag object into the model's Tag object.
     *
     * @throws IllegalValueException if there were any data constraints violated in the adapted task
     */
    public Tag toModelType() throws IllegalValueException {
        return new Tag(tagName);
    }

}

Fix trailing whitespace for checkstyle

Fix trailing whitespace for checkstyle


package org.springframework.site.domain.projects;

import org.junit.Test;

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

public class ProjectVersionTests {

	@Test
	public void getShortNameForCurrentVersion() {
		ProjectRelease version = new ProjectRelease("1.2.3.RELEASE", ProjectRelease.ReleaseStatus.CURRENT, "", "", "", "");
		assertThat(version.getVersionDisplayName(), equalTo("1.2.3"));
	}

	@Test
	public void getShortNameForPreReleaseVersion() {
		ProjectRelease version = new ProjectRelease("1.2.3.M1", ProjectRelease.ReleaseStatus.PRERELEASE, "", "", "", "");
		assertThat(version.getVersionDisplayName(), equalTo("1.2.3.M1"));
	}

	@Test
	public void getShortNameForOtherVersion() {
		ProjectRelease version = new ProjectRelease("1.2.3.RC1", ProjectRelease.ReleaseStatus.PRERELEASE,"", "", "", "");
		assertThat(version.getVersionDisplayName(), equalTo("1.2.3.RC1"));
	}
}

package org.springframework.site.domain.projects;

import org.junit.Test;

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

public class ProjectVersionTests {

	@Test
	public void getDisplayNameForCurrentVersion() {
		ProjectRelease version = new ProjectRelease("1.2.3.RELEASE", ProjectRelease.ReleaseStatus.CURRENT, "", "", "", "");
		assertThat(version.getVersionDisplayName(), equalTo("1.2.3"));
	}

	@Test
	public void getDisplayNameForPreReleaseVersion() {
		ProjectRelease version = new ProjectRelease("1.2.3.M1", ProjectRelease.ReleaseStatus.PRERELEASE, "", "", "", "");
		assertThat(version.getVersionDisplayName(), equalTo("1.2.3.M1"));
	}

	@Test
	public void getDisplayNameForOtherVersion() {
		ProjectRelease version = new ProjectRelease("1.2.3.RC1", ProjectRelease.ReleaseStatus.PRERELEASE,"", "", "", "");
		assertThat(version.getVersionDisplayName(), equalTo("1.2.3.RC1"));
	}
}

Rename remaining 'shortName' refs to 'versionDisplayName'


package com.example.jourdanrodrigues.controk;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

public abstract class BaseFragmentCreation extends BaseFragment{

    protected abstract Boolean errorInFields();
    protected abstract void initializeFields(View view);

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);

        initializeFields(view);

        return view;
    }

    protected void validateEmptyField(EditText editText) {
        editText.setError(editText.getText().toString().isEmpty() ? "Field cannot be empty!" : null);
    }

    protected void setEmptyFieldValidations(final EditText editText) {
        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) { validateEmptyField(editText); }
        });
        editText.addTextChangedListener(new TextValidator(editText) {
            @Override
            public void validate(EditText innerEditText) { validateEmptyField(innerEditText); }
        });
    }
}

package com.example.jourdanrodrigues.controk;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

public abstract class BaseFragmentCreation extends BaseFragment {

    protected abstract Boolean errorInFields();

    protected abstract void initializeFields(View view);

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);

        initializeFields(view);

        return view;
    }

    protected void validateEmptyField(EditText editText) {
        editText.setError(editText.getText().toString().isEmpty() ? "Field cannot be empty!" : null);
    }

    protected void setEmptyFieldValidations(final EditText editText) {
        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                validateEmptyField(editText);
            }
        });
        editText.addTextChangedListener(new TextValidator(editText) {
            @Override
            public void validate(EditText innerEditText) {
                validateEmptyField(innerEditText);
            }
        });
    }
}

Reformat base fragment creation file

:art: Reformat base fragment creation file


package controllers;

import play.mvc.Controller;
import play.mvc.Result;
import views.html.confighelper;
import views.html.index;

/**
 * This controller contains an action to handle HTTP requests
 * to the application's home page.
 */
public class HomeController extends Controller {

    /**
     * Renders the main home page and provides the Gnag client ID used to create the GitHub authentication
     * link.
     * @return
     */
    public Result index() {
        return ok(index.render());
    }

    /**
     * Will show the page for generating a Gradle config for a specific project. If the user has not authorized GitHub
     * this will redirect to start the authentication flow.
     * @return
     */
    public Result configHelper() {
        if (session(GitHubAuthController.TOKEN_KEY) == null) {
            return redirect("/startAuth");
        } else {
            return ok(confighelper.render(session(GitHubAuthController.TOKEN_KEY)));
        }
    }

}

package controllers;

import play.mvc.Controller;
import play.mvc.Result;
import views.html.confighelper;
import views.html.index;

/**
 * This controller contains an action to handle HTTP requests
 * to the application's home page.
 */
public class HomeController extends Controller {

    /**
     * Renders the main home page and provides the Gnag client ID used to create the GitHub authentication
     * link.
     * @return
     */
    public Result index() {
        session().remove(GitHubAuthController.TOKEN_KEY);
        return ok(index.render());
    }

    /**
     * Will show the page for generating a Gradle config for a specific project. If the user has not authorized GitHub
     * this will redirect to start the authentication flow.
     * @return
     */
    public Result configHelper() {
        if (session(GitHubAuthController.TOKEN_KEY) == null) {
            return redirect("/startAuth");
        } else {
            return ok(confighelper.render(session(GitHubAuthController.TOKEN_KEY)));
        }
    }

}

Remove token from session once back on the index page


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

import static com.google.common.base.StandardSystemProperty.JAVA_SPECIFICATION_VERSION;

import java.sql.SQLException;

/**
 * A {@code SQLExceptionWrapper} is used to accommodate for
 * {@literal Java™ 7}'s suppressed exceptions.
 *
 * <p>
 * When {@literal Java™ 6} is used, a fallback {@code SQLExceptionWrapper}
 * that produces similar output is used instead.
 * </p>
 * @author Shredder121
 */
public abstract class SQLExceptionWrapper {

    public static final SQLExceptionWrapper INSTANCE;

    static {
        double javaVersion
                = Double.parseDouble(JAVA_SPECIFICATION_VERSION.value());
        if (javaVersion > 1.6) {
            INSTANCE = new JaveSE7SQLExceptionWrapper();
        } else {
            INSTANCE = new JavaSE6SQLExceptionWrapper();
        }
    }

    public abstract RuntimeException wrap(SQLException exception);

    public abstract RuntimeException wrap(String message, SQLException exception);

}

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

import static com.google.common.base.StandardSystemProperty.JAVA_SPECIFICATION_VERSION;

import java.sql.SQLException;

/**
 * A {@code SQLExceptionWrapper} is used to accommodate for
 * Java™ 7's suppressed exceptions.
 *
 * <p>
 * When Java™ 6 is used, a fallback {@code SQLExceptionWrapper}
 * that produces similar output is used instead.
 * </p>
 * @author Shredder121
 */
public abstract class SQLExceptionWrapper {

    public static final SQLExceptionWrapper INSTANCE;

    static {
        double javaVersion
                = Double.parseDouble(JAVA_SPECIFICATION_VERSION.value());
        if (javaVersion > 1.6) {
            INSTANCE = new JaveSE7SQLExceptionWrapper();
        } else {
            INSTANCE = new JavaSE6SQLExceptionWrapper();
        }
    }

    public abstract RuntimeException wrap(SQLException exception);

    public abstract RuntimeException wrap(String message, SQLException exception);

}

Remove the {@literal } wrapping in the JavaDoc


/*
 * Copyright (C) 2015 Piotr Wittchen
 *
 * 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.pwittchen.prefser.library.rx2;

import com.google.gson.Gson;
import java.lang.reflect.Type;

public final class GsonConverter implements JsonConverter {

  private final Gson gson = new Gson();

  @Override public <T> T fromJson(String json, Type typeOfT) {
    return gson.fromJson(json, typeOfT);
  }

  @Override public <T> String toJson(T object, Type typeOfT) {
    return gson.toJson(object, typeOfT);
  }
}

/*
 * Copyright (C) 2015 Piotr Wittchen
 *
 * 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.pwittchen.prefser.library.rx2;

import android.support.annotation.NonNull;
import com.google.gson.Gson;
import java.lang.reflect.Type;

public final class GsonConverter implements JsonConverter {

  private final Gson gson;

  public GsonConverter(@NonNull Gson gson) {
    this.gson = gson;
  }

  public GsonConverter() {
    gson = new Gson();
  }

  @Override public <T> T fromJson(String json, Type typeOfT) {
    return gson.fromJson(json, typeOfT);
  }

  @Override public <T> String toJson(T object, Type typeOfT) {
    return gson.toJson(object, typeOfT);
  }
}

Allow to pass custom instance of Gson object


package org.openqa.selenium.testing.drivers;

import com.google.common.base.Supplier;

import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;

public class SauceBackedDriverSupplier implements Supplier<WebDriver> {

  private final Capabilities capabilities;

  public SauceBackedDriverSupplier(Capabilities caps) {
    this.capabilities = caps;
  }

  public WebDriver get() {
    if (!SauceDriver.shouldUseSauce()) {
      return null;
    }

    return new SauceDriver(capabilities);
  }
}

package org.openqa.selenium.testing.drivers;

import com.google.common.base.Supplier;

import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.LocalFileDetector;

public class SauceBackedDriverSupplier implements Supplier<WebDriver> {

  private final Capabilities capabilities;

  public SauceBackedDriverSupplier(Capabilities caps) {
    this.capabilities = caps;
  }

  public WebDriver get() {
    if (!SauceDriver.shouldUseSauce()) {
      return null;
    }

    SauceDriver driver = new SauceDriver(capabilities);
    driver.setFileDetector(new LocalFileDetector());
    return driver;
  }
}

Use a file detector for Sauce tests

DanielWagnerHall: Use a file detector for Sauce tests

r15219


package org.kew.shs.dedupl.transformers;

import org.apache.commons.lang.StringUtils;

/**
 * This transformer translates author strings in the form "(Author1) Author2" to "Author1"
 * @author nn00kg
 *
 */
public class StripPublishingAuthorTransformer implements Transformer{

	public String transform(String s) {
		String transformed = s;
		if (StringUtils.isNotBlank(s) && ((s.indexOf("(") != -1) && s.indexOf(")") != -1))
			transformed = s.substring(s.indexOf("(")+1,s.indexOf(")"));
		return transformed;
	}

	public static void main(String[] args) {
		StripPublishingAuthorTransformer t  = new StripPublishingAuthorTransformer();
		System.out.println(t.transform("(Author1) Author 2"));
	}

}

package org.kew.shs.dedupl.transformers;

import org.apache.commons.lang.StringUtils;

/**
 * This transformer translates author strings in the form "(Author1) Author2" to "Author1"
 * @author nn00kg
 *
 */
public class StripPublishingAuthorTransformer implements Transformer{

	public String transform(String s) {
		String transformed = s;
		if (StringUtils.isNotBlank(s) && ((s.indexOf("(") != -1) && s.indexOf(")") != -1))
			transformed = s.substring(s.indexOf("(")+1,s.indexOf(")"));
		else
			transformed = "";
		return transformed;
	}

	public static void main(String[] args) {
		StripPublishingAuthorTransformer t  = new StripPublishingAuthorTransformer();
		System.out.println(t.transform("(Author1) Author 2"));
		System.out.println(t.transform("Author3"));
		System.out.println(t.transform("(Author4)"));
	}

}

Add delimited output file and new AuthorAbbreviatedMatcher

Updated luceneUtils.java and lucenematcher.java to output a new delimited file
than can be imported direct into a db. Also added new Matchers called
AuthorAbbreviatedMatcher.java, EmptyStringMatch.java. Also added a config
and properties file to read data from the T:drive


import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.commons.Method;

public class Gen {

    public static void main(String[] args) {
        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
        cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "GenBCode", null, "java/lang/Object", null);

        Method init = Method.getMethod("void <init>()");
        GeneratorAdapter gaInit = new GeneratorAdapter(Opcodes.ACC_PUBLIC, init, null, null, cw);
        gaInit.visitCode();
        gaInit.loadThis();
        gaInit.invokeConstructor(Type.getType(Object.class), init);
        gaInit.returnValue();
        gaInit.endMethod();

        Method run = Method.getMethod("int run()");
        GeneratorAdapter ga = new GeneratorAdapter((Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC), run, null, null, cw);
        ga.visitCode();
        // BEGIN important part
        ga.push(42);
        // END important part
        ga.returnValue();
        ga.endMethod();

        cw.visitEnd();

        byte[] generatedByteCode = cw.toByteArray();
    }
}

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.commons.Method;

public class Gen {

    public static void main(String[] args) {
        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
        cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "GenBCode", null, "java/lang/Object", null);

        Method init = Method.getMethod("void <init>()");
        GeneratorAdapter gaInit = new GeneratorAdapter(Opcodes.ACC_PUBLIC, init, null, null, cw);
        gaInit.visitCode();
        gaInit.loadThis();
        gaInit.invokeConstructor(Type.getType(Object.class), init);
        gaInit.returnValue();
        gaInit.endMethod();

        Method run = Method.getMethod("int run()");
        GeneratorAdapter ga = new GeneratorAdapter((Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC), run, null, null, cw);
        ga.visitCode();
        // BEGIN important part
        ga.push(42);
        // END important part
        ga.returnValue();
        ga.endMethod();

        cw.visitEnd();

        byte[] generatedByteCode = cw.toByteArray();

        try {
            Path path = Paths.get("GenBCode.class");
            Files.write(path, generatedByteCode);
        } catch(Exception e) {
            System.out.println("Cannot write to file");
        }

        System.out.println(GenBCode.run());
    }
}

FEATURE/MINOR: Write generated class to a .class and run it


package me.rkfg.xmpp.bot;

import me.rkfg.xmpp.bot.irc.IRCBot;
import ru.ppsrk.gwt.client.LogicException;

public class Main {

    public static final IBot INSTANCE = new IRCBot();

    public static void main(String[] args) throws LogicException {
        INSTANCE.run();
    }

}

package me.rkfg.xmpp.bot;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import me.rkfg.xmpp.bot.irc.IRCBot;
import me.rkfg.xmpp.bot.matrix.MatrixBot;
import me.rkfg.xmpp.bot.xmpp.XMPPBot;
import ru.ppsrk.gwt.client.LogicException;
import ru.ppsrk.gwt.server.SettingsManager;

public class Main {

    public static final IBot INSTANCE;
    private static Logger log = LoggerFactory.getLogger(Main.class);

    static {
        SettingsManager sm = SettingsManager.getInstance();
        sm.setFilename("settings.ini");
        try {
            sm.loadSettings();
        } catch (IOException e) {
            log.warn("{}", e);
        }
        String type = sm.getStringSetting("type");
        if (type == null) {
            INSTANCE = null;
        } else {
            switch (type) {
            case "xmpp":
                INSTANCE = new XMPPBot();
                break;
            case "matrix":
                INSTANCE = new MatrixBot();
                break;
            case "irc":
                INSTANCE = new IRCBot();
                break;
            default:
                INSTANCE = null;
                break;
            }
        }
    }

    public static void main(String[] args) throws LogicException {
        if (INSTANCE == null) {
            log.error("Set 'type' parameter in settings.ini to the bot type (xmpp, matrix or irc).");
            return;
        }
        INSTANCE.run();
    }

}

Select bot type via config

Select bot type via config


package org.mozilla.mozstumbler;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

final class NetworkUtils {
    private static final String LOGTAG = NetworkUtils.class.getName();

    private NetworkUtils() {
    }

    @SuppressWarnings("deprecation")
    static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
            Log.e(LOGTAG, "ConnectivityManager is null!");
            return false;
        }

        if (!cm.getBackgroundDataSetting()) {
            Log.w(LOGTAG, "Background data is restricted!");
            return false;
        }

        NetworkInfo network = cm.getActiveNetworkInfo();
        if (network == null) {
            Log.w(LOGTAG, "No active network!");
            return false;
        }

        if (!network.isAvailable()) {
            Log.w(LOGTAG, "Active network is not available!");
            return false;
        }

        if (!network.isConnected()) {
            Log.w(LOGTAG, "Active network is not connected!");
            return false;
        }

        if (network.isRoaming()) {
            Log.w(LOGTAG, "Active network is roaming!");
            return false;
        }

        return true; // Network is OK!
    }

    static String getUserAgentString(Context context) {
        String appName = context.getString(R.string.app_name);
        String appVersion = PackageUtils.getAppVersion(context);

        // "MozStumbler/X.Y.Z"
        return appName + '/' + appVersion;
    }
}

package org.mozilla.mozstumbler;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

final class NetworkUtils {
    private static final String LOGTAG = NetworkUtils.class.getName();

    private NetworkUtils() {
    }

    @SuppressWarnings("deprecation")
    static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
            Log.e(LOGTAG, "ConnectivityManager is null!");
            return false;
        }

        if (!cm.getBackgroundDataSetting()) {
            Log.w(LOGTAG, "Background data is restricted!");
            return false;
        }

        NetworkInfo network = cm.getActiveNetworkInfo();
        if (network == null) {
            Log.w(LOGTAG, "No active network!");
            return false;
        }

        if (!network.isAvailable()) {
            Log.w(LOGTAG, "Active network is not available!");
            return false;
        }

        if (!network.isConnected()) {
            Log.w(LOGTAG, "Active network is not connected!");
            return false;
        }

        return true; // Network is OK!
    }

    static String getUserAgentString(Context context) {
        String appName = context.getString(R.string.app_name);
        String appVersion = PackageUtils.getAppVersion(context);

        // "MozStumbler/X.Y.Z"
        return appName + '/' + appVersion;
    }
}

Remove check for network roaming

Remove check for network roaming


package edu.umd.cs.findbugs.detect;

import org.apache.bcel.classfile.CodeException;

import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;

public class DontCatchNullPointerException
        extends PreorderVisitor implements Detector {

    private final BugReporter reporter;
    ClassContext classContext;

    public DontCatchNullPointerException(BugReporter reporter) {
        this.reporter = reporter;
    }

    private static final String NullPtrExceptionID =
            "java.lang.NullPointerException";

    @Override
    public void visit(CodeException exc) {
        int type = exc.getCatchType();

        if (type == 0)
            return;

        String name = getConstantPool()
                .constantToString(getConstantPool()
                        .getConstant(type));

        if (name.equals(NullPtrExceptionID)) {
            BugInstance bug = new BugInstance(this,
                    "DCN_NULLPOINTER_EXCEPTION",
                    NORMAL_PRIORITY);
            bug.addClassAndMethod(this);
            bug.addSourceLine(this.classContext, this, exc.getHandlerPC());

            reporter.reportBug(bug);
        }
    }

    @Override
    public void visitClassContext(ClassContext classContext) {
        this.classContext = classContext;
        this.classContext.getJavaClass().accept(this);
    }

    @Override
    public void report() {
    }
}

package edu.umd.cs.findbugs.detect;

import org.apache.bcel.classfile.CodeException;

import edu.umd.cs.findbugs.internalAnnotations.DottedClassName;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;

public class DontCatchNullPointerException
        extends BytecodeScanningDetector {

    private final BugReporter reporter;

    public DontCatchNullPointerException(BugReporter reporter) {
        this.reporter = reporter;
    }

    @DottedClassName
    private static final String NULLPOINTER_EXCEPTION_FQCN =
            "java.lang.NullPointerException";

    @Override
    public void visit(CodeException exc) {
        int type = exc.getCatchType();

        if (type == 0)
            return;

        String name = getConstantPool()
                .constantToString(getConstantPool()
                        .getConstant(type));

        if (name.equals(NULLPOINTER_EXCEPTION_FQCN)) {
            BugInstance bug = new BugInstance(this,
                    "DCN_NULLPOINTER_EXCEPTION",
                    NORMAL_PRIORITY);
            bug.addClassAndMethod(this);
            bug.addSourceLine(getClassContext(), this, exc.getHandlerPC());

            reporter.reportBug(bug);
        }
    }
}

Use BytecodeScanningDetector as base class


package forager.client;

import java.io.IOException;

public class StatusMonitor implements Runnable {

    int maxActive = 4;

    boolean online;

    private Forager forager;

    public StatusMonitor(Forager forager) {
        this.forager = forager;
    }

    public void run() {
        online = true;

        while (online) {
            int active = forager.getActiveCount();
            if (active < maxActive) {
                int numTasks = maxActive - active;
                try {
                    forager.submitTaskRequest(numTasks);
                } catch (IOException e) {
                    System.out.println("Failed to submit task request!");
                    e.printStackTrace();
                }
            }
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) { }
        }
    }
}

package forager.client;

import java.io.IOException;

public class StatusMonitor implements Runnable {

    int maxActive = 4;

    boolean online;

    private Forager forager;

    public StatusMonitor(Forager forager) {
        this.forager = forager;
    }

    public void run() {
        online = true;

        while (online) {
            int active = forager.getActiveCount();
            if (active < maxActive) {
                int numTasks = maxActive - active;
                try {
                    forager.submitTaskRequest(numTasks);
                } catch (IOException e) {
                    System.out.println("Failed to submit task request!");
                    e.printStackTrace();
                }
            }
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) { }
        }
    }
}

Increase iteration time a bit

Increase iteration time a bit


package pw.scho.battleship.persistence.configuration;

import com.mongodb.ServerAddress;
import org.mongolink.MongoSession;
import org.mongolink.MongoSessionManager;
import org.mongolink.Settings;
import org.mongolink.UpdateStrategies;
import org.mongolink.domain.mapper.ContextBuilder;

import java.net.UnknownHostException;
import java.util.Arrays;

public class MongoConfiguration {

    public static void stop() {
        Singleton.INSTANCE.mongoSessionManager.close();
    }

    public static MongoSession createSession() {
        return Singleton.INSTANCE.mongoSessionManager.createSession();
    }

    private enum Singleton {

        INSTANCE;

        private final MongoSessionManager mongoSessionManager;

        private Singleton() {
            ContextBuilder builder = new ContextBuilder("pw.scho.battleship.persistence.mongo.mapping");
            Settings settings = null;
            try {
                settings = Settings.defaultInstance()
                        .withDefaultUpdateStrategy(UpdateStrategies.DIFF)
                        .withDbName("battleship")
                        .withAddresses(Arrays.asList(new ServerAddress("localhost", 27017)));

            } catch (UnknownHostException e) {
            }
            mongoSessionManager = MongoSessionManager.create(builder, settings);
        }
    }
}

package pw.scho.battleship.persistence.configuration;

import com.mongodb.DB;
import com.mongodb.MongoURI;
import com.mongodb.ServerAddress;
import org.mongolink.MongoSession;
import org.mongolink.MongoSessionManager;
import org.mongolink.Settings;
import org.mongolink.UpdateStrategies;
import org.mongolink.domain.mapper.ContextBuilder;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MongoConfiguration {

    public static void stop() {
        Singleton.INSTANCE.mongoSessionManager.close();
    }

    public static MongoSession createSession() {
        return Singleton.INSTANCE.mongoSessionManager.createSession();
    }

    private enum Singleton {

        INSTANCE;

        private final MongoSessionManager mongoSessionManager;

        private Singleton() {
            ContextBuilder builder = new ContextBuilder("pw.scho.battleship.persistence.mongo.mapping");
            Settings settings = null;
            try {
                settings = Settings.defaultInstance()
                        .withDefaultUpdateStrategy(UpdateStrategies.DIFF)
                        .withDbName("battleship");
                String mongoHqUrl = System.getenv("MONGOHQ_URL");

                if(mongoHqUrl!= null){
                    MongoURI mongoURI = new MongoURI(mongoHqUrl);
                    List<ServerAddress> serverAdresses = new ArrayList<>();
                    for(String host : mongoURI.getHosts()){
                        serverAdresses.add(new ServerAddress(host, 27017));
                    }
                    settings = settings.withAddresses(serverAdresses)
                            .withAuthentication(mongoURI.getUsername(), mongoURI.getPassword().toString());
                } else {
                    settings = settings.withAddresses(Arrays.asList(new ServerAddress("localhost", 27017)));
                }
            } catch (UnknownHostException e) {
            }
            mongoSessionManager = MongoSessionManager.create(builder, settings);
        }
    }
}

Add mongo hq authentication for heroku

Add mongo hq authentication for heroku


package io.github.droidkaigi.confsched2017.viewmodel;

import android.databinding.BaseObservable;
import android.support.annotation.NonNull;

import io.github.droidkaigi.confsched2017.model.Contributor;

public class ContributorViewModel extends BaseObservable implements ViewModel {

    private Callback callback;

    private Contributor contributor;

    private String name;

    private String avatarUrl;

    private String htmlUrl;

    private int contributions;

    public ContributorViewModel(@NonNull Contributor contributor) {
        this.contributor = contributor;
        this.avatarUrl = contributor.avatarUrl;
        this.name = contributor.name;
        this.htmlUrl = contributor.htmlUrl;
        this.contributions = contributor.contributions;
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    @Override
    public void destroy() {
        this.callback = null;
    }

    public interface Callback {

        void onClickContributor();
    }

    public int getContributions() {
        return contributions;
    }

    public Contributor getContributor() {
        return contributor;
    }

    public String getName() {
        return name;
    }

    public String getAvatarUrl() {
        return avatarUrl;
    }

    public String getHtmlUrl() {
        return htmlUrl;
    }
}

package io.github.droidkaigi.confsched2017.viewmodel;

import android.databinding.BaseObservable;
import android.support.annotation.NonNull;
import android.view.View;

import io.github.droidkaigi.confsched2017.model.Contributor;

public class ContributorViewModel extends BaseObservable implements ViewModel {

    private Callback callback;

    private Contributor contributor;

    private String name;

    private String avatarUrl;

    private String htmlUrl;

    private int contributions;

    public ContributorViewModel(@NonNull Contributor contributor) {
        this.contributor = contributor;
        this.avatarUrl = contributor.avatarUrl;
        this.name = contributor.name;
        this.htmlUrl = contributor.htmlUrl;
        this.contributions = contributor.contributions;
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    @Override
    public void destroy() {
        this.callback = null;
    }

    public interface Callback {

        void onClickContributor(String htmlUrl);
    }

    public void onClickContributor(@SuppressWarnings("UnusedParameters") View view) {
        if (callback != null) {
            callback.onClickContributor(htmlUrl);
        }
    }

    public int getContributions() {
        return contributions;
    }

    public Contributor getContributor() {
        return contributor;
    }

    public String getName() {
        return name;
    }

    public String getAvatarUrl() {
        return avatarUrl;
    }

    public String getHtmlUrl() {
        return htmlUrl;
    }
}

Fix the problem with handling onClick event


package org.wikipedia.util;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.feed.announcement.GeoIPCookieUnmarshaller;

public final class GeoUtil {

    public static void sendGeoIntent(@NonNull Activity activity,
                                     @NonNull Location location,
                                     @Nullable String placeName) {
        String geoStr = "geo:";
        geoStr += Double.toString(location.getLatitude()) + ","
                + Double.toString(location.getLongitude());
        if (!TextUtils.isEmpty(placeName)) {
            geoStr += "?q=" + Uri.encode(placeName);
        }
        try {
            activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(geoStr)));
        } catch (ActivityNotFoundException e) {
            FeedbackUtil.showMessage(activity, R.string.error_no_maps_app);
        }
    }

    @Nullable public static String getGeoIPCountry() {
        try {
            return GeoIPCookieUnmarshaller.unmarshal(WikipediaApp.getInstance()).country();
        } catch (IllegalArgumentException e) {
            // For our purposes, don't care about malformations in the GeoIP cookie for now.
            return null;
        }
    }

    private GeoUtil() {
    }
}

package org.wikipedia.util;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.feed.announcement.GeoIPCookieUnmarshaller;

public final class GeoUtil {

    public static void sendGeoIntent(@NonNull Activity activity,
                                     @NonNull Location location,
                                     @Nullable String placeName) {
        // Using geo:latitude,longitude doesn't give a point on the map,
        // hence using query
        String geoStr = "geo:0,0?q=" + location.getLatitude()
                + "," + location.getLongitude();
        if (!TextUtils.isEmpty(placeName)) {
            geoStr += "(" + Uri.encode(placeName) + ")";
        }
        try {
            activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(geoStr)));
        } catch (ActivityNotFoundException e) {
            FeedbackUtil.showMessage(activity, R.string.error_no_maps_app);
        }
    }

    @Nullable public static String getGeoIPCountry() {
        try {
            return GeoIPCookieUnmarshaller.unmarshal(WikipediaApp.getInstance()).country();
        } catch (IllegalArgumentException e) {
            // For our purposes, don't care about malformations in the GeoIP cookie for now.
            return null;
        }
    }

    private GeoUtil() {
    }
}

Make Google Maps use the coordinates supplied by Wikipedia app

Bug: T120275
Change-Id: I7eebb4c2b4e7164cb481ea23831296d4d50a426b


package com.bugielmarek.timetable.tests.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestUtils {

	 public static String createStringWithLength(int length){
		 	StringBuilder sb = new StringBuilder();
		 	for(int i=0; i<length; i++){
		 		sb.append("a");
		 	}
		 	return sb.toString();
	 }

	/* public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
	        ObjectMapper mapper = new ObjectMapper();
	        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
	        return mapper.writeValueAsBytes(object);
	    }*/

	 public static String asJsonString(Object object) throws JsonProcessingException{
		 ObjectMapper mapper = new ObjectMapper();
		 mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		 return mapper.writeValueAsString(object);
	 }
}

package com.bugielmarek.timetable.tests.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestUtils {

	 public static String createStringWithLength(int length){
		 	StringBuilder sb = new StringBuilder();
		 	for(int i=0; i<length; i++){
		 		sb.append("a");
		 	}
		 	return sb.toString();
	 }

	 public static String asJsonString(Object object) throws JsonProcessingException{
		 ObjectMapper mapper = new ObjectMapper();
		 mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		 return mapper.writeValueAsString(object);
	 }
}

Delete byte[] method, was superfluous

Delete byte[] method, was superfluous


package io.lithiumsheep.weatherlib;

import io.lithiumsheep.weatherlib.api.HttpClient;
import io.lithiumsheep.weatherlib.models.CurrentWeather;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;

public class WeatherLib {

    public static Observable<CurrentWeather> getObservableCurrentWeather(String cityOrZip) {
        return HttpClient.getObservableService().getCurrentWeather(cityOrZip)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public static Call<CurrentWeather> getCurrentWeather(String cityOrZip) {
        return HttpClient.getService().getCurrentWeather(cityOrZip);
    }

    public static Call<Void> getWeatherZip(String zip) {
        return HttpClient.getService().getWeatherByZip(zip);
    }
}

package io.lithiumsheep.weatherlib;

import io.lithiumsheep.weatherlib.api.HttpClient;
import io.lithiumsheep.weatherlib.models.CurrentWeather;
import retrofit2.Call;

public class WeatherLib {

    public static Call<CurrentWeather> getCurrentWeather(String cityOrZip) {
        return HttpClient.getService().getCurrentWeather(cityOrZip);
    }

    public static Call<Void> getWeatherZip(String zip) {
        return HttpClient.getService().getWeatherByZip(zip);
    }
}

Remove observable service from facade

Remove observable service from facade


package org.springframework.social.salesforce.connect;

import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;

import java.util.Map;

/**
 * Salesforce OAuth2Template implementation.
 * <p/>
 * The reason to extend is to extract non-standard instance_url from Salesforce's oauth token response.
 *
 * @author Umut Utkan
 */
public class SalesforceOAuth2Template extends OAuth2Template {

    private String instanceUrl = null;

    public SalesforceOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String accessTokenUrl) {
        super(clientId, clientSecret, authorizeUrl, accessTokenUrl);
    }

    public SalesforceOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String authenticateUrl, String accessTokenUrl) {
        super(clientId, clientSecret, authorizeUrl, authenticateUrl, accessTokenUrl);
    }

    @Override
    protected AccessGrant createAccessGrant(String accessToken, String scope, String refreshToken, Integer expiresIn, Map<String, Object> response) {
        this.instanceUrl = (String) response.get("instance_url");

        return super.createAccessGrant(accessToken, scope, refreshToken, expiresIn, response);
    }

    public String getInstanceUrl() {
        return instanceUrl;
    }

}

package org.springframework.social.salesforce.connect;

import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;

import java.util.Map;

/**
 * Salesforce OAuth2Template implementation.
 * <p/>
 * The reason to extend is to extract non-standard instance_url from Salesforce's oauth token response.
 *
 * @author Umut Utkan
 */
public class SalesforceOAuth2Template extends OAuth2Template {

    private String instanceUrl = null;

    public SalesforceOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String accessTokenUrl) {
        this(clientId, clientSecret, authorizeUrl, null, accessTokenUrl);
    }

    public SalesforceOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String authenticateUrl, String accessTokenUrl) {
        super(clientId, clientSecret, authorizeUrl, authenticateUrl, accessTokenUrl);
        setUseParametersForClientAuthentication(true);
    }

    @Override
    protected AccessGrant createAccessGrant(String accessToken, String scope, String refreshToken, Integer expiresIn, Map<String, Object> response) {
        this.instanceUrl = (String) response.get("instance_url");

        return super.createAccessGrant(accessToken, scope, refreshToken, expiresIn, response);
    }

    public String getInstanceUrl() {
        return instanceUrl;
    }

}

Set OAuth2Template to use parameter-based client authentication (see SOCIAL-320) since Salesforce does not yet support the spec-recommended HTTP Basic client authentication.


package com.hewgill.android.nzsldict;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class DownloadReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
            Intent startIntent = new Intent(context, FavouritesActivity.class);
            startIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            context.startActivity(startIntent);
        }
    }
}

package com.hewgill.android.nzsldict;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class DownloadReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
            Intent startIntent = new Intent(context, FavouritesActivity.class);
            startIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            context.startActivity(startIntent);
            return;
        }

        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            Toast.makeText(context, "Download completed?", Toast.LENGTH_SHORT).show();

        }
    }
}

Add stub to indicate that the download has completed; this needs to be raised to the favourites activity


package com.github.jsonldjava.core;

import com.github.jsonldjava.utils.JsonUtils;
import java.io.IOException;
import org.junit.Test;
import static org.junit.Assert.*;

public class JsonLdFramingTest {

    @Test
    public void testFrame0001() throws IOException, JsonLdError {
        try {
            Object frame = JsonUtils.fromInputStream(
                    getClass().getResourceAsStream("/custom/frame-0001-frame.jsonld"));
            Object in = JsonUtils.fromInputStream(
                    getClass().getResourceAsStream("/custom/frame-0001-in.jsonld"));

            JsonLdProcessor.frame(in, frame, new JsonLdOptions());
        } catch (Throwable t) {
            t.printStackTrace();

            fail();
        }
    }

}

package com.github.jsonldjava.core;

import com.github.jsonldjava.utils.JsonUtils;
import java.io.IOException;
import java.util.Map;

import org.junit.Test;
import static org.junit.Assert.*;

public class JsonLdFramingTest {

    @Test
    public void testFrame0001() throws IOException, JsonLdError {
        Object frame = JsonUtils.fromInputStream(
                getClass().getResourceAsStream("/custom/frame-0001-frame.jsonld"));
        Object in = JsonUtils.fromInputStream(
                getClass().getResourceAsStream("/custom/frame-0001-in.jsonld"));

        Map<String, Object> frame2 = JsonLdProcessor.frame(in, frame, new JsonLdOptions());

        assertEquals(2, frame2.size());
    }

}

Add positive test for completion in the framing test


package com.thaiopensource.relaxng;

import org.relaxng.datatype.ValidationContext;

import org.xml.sax.SAXException;

class AttributeAtom extends Atom {
  String namespaceURI;
  String localName;
  StringAtom value;

  AttributeAtom(String namespaceURI, String localName, String value, ValidationContext vc) {
    this.namespaceURI = namespaceURI;
    this.localName = localName;
    this.value = value == null ? null : new StringAtom(value, vc);
  }
  boolean matchesAttribute(PatternBuilder b, NameClass nc, Pattern valuePattern) {
    return (nc.contains(namespaceURI, localName)
	    && (value == null
		|| valuePattern.residual(b, value).isNullable()));
  }
  boolean isAttribute() {
    return true;
  }
}

package com.thaiopensource.relaxng;

import org.relaxng.datatype.ValidationContext;

import org.xml.sax.SAXException;

class AttributeAtom extends Atom {
  String namespaceURI;
  String localName;
  StringAtom value;

  AttributeAtom(String namespaceURI, String localName, String value, ValidationContext vc) {
    this.namespaceURI = namespaceURI;
    this.localName = localName;
    this.value = value == null ? null : new StringAtom(value, vc);
  }
  boolean matchesAttribute(PatternBuilder b, NameClass nc, Pattern valuePattern) {
    if (!nc.contains(namespaceURI, localName))
      return false;
    if (value == null)
      return true;
    if (value.isEmpty() && valuePattern.isNullable())
      return true;
    return valuePattern.residual(b, value).isNullable();
  }
  boolean isAttribute() {
    return true;
  }
}

Allow an empty attribute value to match <empty/>.

git-svn-id: ca8e9bb6f3f9b50a093b443c23951d3c25ca0913@390 369101cc-9a96-11dd-8e58-870c635edf7a


package ethereumjava.solidity;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import ethereumjava.exception.EthereumJavaException;
import ethereumjava.module.Eth;

/**
 * Created by gunicolas on 30/08/16.
 */
public class Contract<T extends ContractType> {

    Class<T> abi;
    String address;
    Eth eth;

    public Contract(Eth eth){
        this.eth = eth;
    }

    public Contract<T> withAbi(Class<T> abi){
        this.abi = abi;
        return this;
    }

    public T at(String address){
        this.address = address;
        return (T) Proxy.newProxyInstance(abi.getClassLoader(),new Class[]{abi},new InvocationHandler());
    }

    class InvocationHandler implements java.lang.reflect.InvocationHandler{

        @Override
        public SolidityElement invoke(Object proxy, Method method, Object[] args) throws Throwable {

            if( method.getReturnType().isAssignableFrom(SolidityFunction.class) ){
                return new SolidityFunction(address,method,eth,args);
            } else if( method.getReturnType().isAssignableFrom(SolidityEvent.class) ){
                return new SolidityEvent(address,method,eth);
            }
            throw new EthereumJavaException("Contract element return type is invalid");
        }
    }

}

package ethereumjava.solidity;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import ethereumjava.exception.EthereumJavaException;
import ethereumjava.module.Eth;

/**
 * Created by gunicolas on 30/08/16.
 */
public class Contract {

    String address;
    Eth eth;

    public final class ContractInstance<T extends ContractType> {
        Class<T> clazz;

        public ContractInstance(Class<T> aClazz) {
            clazz = aClazz;
        }

        public T at(String address){
            Contract.this.address = address;
            return (T) Proxy.newProxyInstance(clazz.getClassLoader(),new Class[]{clazz},new InvocationHandler());
        }

    }

    public Contract(Eth eth){
        this.eth = eth;
    }

    public <T extends ContractType> ContractInstance<T> withAbi(Class<T> clazz){
        return new ContractInstance(clazz);
    }

    class InvocationHandler implements java.lang.reflect.InvocationHandler{

        @Override
        public SolidityElement invoke(Object proxy, Method method, Object[] args) throws Throwable {

            if( method.getReturnType().isAssignableFrom(SolidityFunction.class) ){
                return new SolidityFunction(address,method,eth,args);
            } else if( method.getReturnType().isAssignableFrom(SolidityEvent.class) ){
                return new SolidityEvent(address,method,eth);
            }
            throw new EthereumJavaException("Contract element return type is invalid");
        }
    }

}

Allow to not cast ethereum Java contract


package org.rundeck.client.util;

import com.simplifyops.toolbelt.ANSIColorOutput;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by greg on 7/19/16.
 */
public class Colorz {
    /**
     * Return a map with key/values replaced with colorized versions, if specified
     *
     * @param data data
     * @param key  key color, or null
     *
     * @return colorized keys/values
     */
    public static Map<?, ?> colorizeMapRecurse(
            Map<?, ?> data,
            ANSIColorOutput.Color key
    )
    {
        LinkedHashMap<Object, Object> result = new LinkedHashMap<>();
        data.keySet().forEach(k -> {
            final Object value = data.get(k);
            result.put(
                    key != null ? ANSIColorOutput.colorize(key, k.toString()) : k,
                    value instanceof Map ? colorizeMapRecurse((Map) value, key) : value
            );
        });
        return result;
    }
}

package org.rundeck.client.util;

import com.simplifyops.toolbelt.ANSIColorOutput;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by greg on 7/19/16.
 */
public class Colorz {
    /**
     * Return a map with key/values replaced with colorized versions, if specified
     *
     * @param data data
     * @param colors  key color, or null
     *
     * @return colorized keys/values
     */
    public static Map<?, ?> colorizeMapRecurse(
            Map<?, ?> data,
            ANSIColorOutput.Color... colors
    )
    {
        LinkedHashMap<Object, Object> result = new LinkedHashMap<>();
        data.keySet().forEach(k -> {
            final Object value = data.get(k);
            ANSIColorOutput.Color keyColor = colors != null && colors.length > 0 ? colors[0] : null;
            ANSIColorOutput.Color[] subcolors = null;
            if (colors != null && colors.length > 1) {
                subcolors = new ANSIColorOutput.Color[colors.length - 1];
                System.arraycopy(colors, 1, subcolors, 0, subcolors.length);
            }
            result.put(
                    keyColor != null
                    ? ANSIColorOutput.colorize(
                            keyColor,
                            k.toString()
                    )
                    : k,

                    value instanceof Map && subcolors != null
                    ? colorizeMapRecurse(
                            (Map) value,
                            subcolors
                    )

                    : value
            );
        });
        return result;
    }
}

Update to support more than one color

Update to support more than one color


/**
 * Abstract Syntax Tree.
 *
 * <pre>
 * Group ::= Abbreviation* Definition*
 *
 * Definition ::= Test | FourPhaseTest | Table
 *
 * Test ::= Assertion*
 *
 * Assertion ::= Proposition* Fixture
 *
 * Proposition ::= QuotedExpr Predicate
 *
 * Predicate ::= IsPredicate | IsNotPredicate | ThrowsPredicate
 *
 * IsPredicate ::= Matcher
 * IsNotPredicate ::= Matcher
 * ThrowsPredicate ::= Matcher
 *
 * Matcher ::= EqualToMatcher
 *           | InstanceOfMatcher
 *           | InstanceSuchThatMatcher
 *           | NullValueMatcher
 *
 * EqualToMatcher ::= QuotedExpr
 * InstanceOfMatcher ::= ClassType
 * InstanceSuchThatMatcher ::= ClassType Proposition+
 *
 * Expr ::= QuotedExpr | StubExpr
 *
 * StubExpr ::= ClassType StubBehavior*
 *
 * StubBehavior ::= MethodPattern Expr
 *
 * MethodPattern ::= Type*
 *
 * Type ::= NonArrayType
 * NonArrayType ::= PrimitiveType | ClassType
 * PrimitiveType ::= Kind
 *
 * Fixture ::= | TableRef | Bindings
 *
 * TableRef ::= Ident+ TableType
 *
 * TableType :: INLINE | CSV | TSV | EXCEL
 *
 * Bindings ::= Binding*
 * Binding ::= Ident Expr
 *
 * FourPhaseTest ::= Phase? Phase? VerifyPhase Phase?
 *
 * Phase ::= LetBindings? Execution?
 * VerifyPhase ::= Assertion+
 *
 * Execution ::= QuotedExpr*
 *
 * Table ::= Ident* Row*
 *
 * Row ::= Expr*
 * </pre>
 *
 */
package yokohama.unit.ast;

/**
 * Abstract Syntax Tree.
 *
 * <pre>
 * Group ::= Abbreviation* Definition*
 *
 * Definition ::= Test | FourPhaseTest | Table
 *
 * Test ::= Assertion*
 *
 * Assertion ::= Proposition* Fixture
 *
 * Proposition ::= QuotedExpr Predicate
 *
 * Predicate ::= IsPredicate | IsNotPredicate | ThrowsPredicate
 *
 * IsPredicate ::= Matcher
 * IsNotPredicate ::= Matcher
 * ThrowsPredicate ::= Matcher
 *
 * Matcher ::= EqualToMatcher
 *           | InstanceOfMatcher
 *           | InstanceSuchThatMatcher
 *           | NullValueMatcher
 *
 * EqualToMatcher ::= QuotedExpr
 * InstanceOfMatcher ::= ClassType
 * InstanceSuchThatMatcher ::= ClassType Proposition+
 *
 * Expr ::= QuotedExpr | StubExpr
 *
 * StubExpr ::= ClassType StubBehavior*
 *
 * StubBehavior ::= MethodPattern Expr
 *
 * MethodPattern ::= Type*
 *
 * Type ::= NonArrayType
 * NonArrayType ::= PrimitiveType | ClassType
 * PrimitiveType ::= Kind
 *
 * Fixture ::= | TableRef | Bindings
 *
 * TableRef ::= Ident+ TableType
 *
 * TableType :: INLINE | CSV | TSV | EXCEL
 *
 * Bindings ::= Binding*
 * Binding ::= Ident Expr
 *
 * FourPhaseTest ::= Phase? Phase? VerifyPhase Phase?
 *
 * Phase ::= LetBindings? Execution?
 * VerifyPhase ::= Assertion+
 *
 * LetBindings ::= LetBinding+
 * LetBinding ::= Expr
 *
 * Execution ::= QuotedExpr*
 *
 * Table ::= Ident* Row*
 *
 * Row ::= Expr*
 * </pre>
 *
 */
package yokohama.unit.ast;

Add description of LetBindings and LetBinding, which were missing from document