package com.github.blindpirate.gogradle.util.logging;

import com.github.blindpirate.gogradle.GogradleGlobal;
import org.gradle.internal.logging.progress.ProgressLogger;
import org.gradle.internal.logging.progress.ProgressLoggerFactory;
import org.gradle.internal.service.ServiceRegistry;

import java.io.IOException;
import java.io.InputStream;

import static com.github.blindpirate.gogradle.util.IOUtils.byteCountToDisplaySize;

public class ProgressMonitorInputStream extends InputStream {
    private InputStream delegate;
    private ProgressLogger logger;
    private int totalBytes;

    public ProgressMonitorInputStream(String url, InputStream delegate) {
        this.delegate = delegate;
        ProgressLoggerFactory progressLoggerFactory =
                GogradleGlobal.getInstance(ServiceRegistry.class).get(ProgressLoggerFactory.class);
        logger = progressLoggerFactory.newOperation(this.getClass());

        String description = "Start downloading from " + url;
        logger.start(description, description);
    }

    @Override
    public int read() throws IOException {
        int bytes = delegate.read();
        if (bytes == -1) {
            logger.completed();
        } else {
            totalBytes += bytes;
            logger.progress(byteCountToDisplaySize(totalBytes) + " downloaded");
        }
        return bytes;
    }
}

package com.github.blindpirate.gogradle.util.logging;

import com.github.blindpirate.gogradle.GogradleGlobal;
import org.gradle.internal.logging.progress.ProgressLogger;
import org.gradle.internal.logging.progress.ProgressLoggerFactory;
import org.gradle.internal.service.ServiceRegistry;

import java.io.IOException;
import java.io.InputStream;

import static com.github.blindpirate.gogradle.util.IOUtils.byteCountToDisplaySize;

public class ProgressMonitorInputStream extends InputStream {
    private InputStream delegate;
    private ProgressLogger logger;
    private int totalBytes;
    private boolean completed;

    public ProgressMonitorInputStream(String url, InputStream delegate) {
        this.delegate = delegate;
        ProgressLoggerFactory progressLoggerFactory =
                GogradleGlobal.getInstance(ServiceRegistry.class).get(ProgressLoggerFactory.class);
        logger = progressLoggerFactory.newOperation(this.getClass());

        String description = "Start downloading from " + url;
        logger.start(description, description);
    }

    @Override
    public int read() throws IOException {
        int bytes = delegate.read();
        if (completed) {
            return bytes;
        }
        if (bytes == -1) {
            logger.completed();
            completed = true;
        } else {
            totalBytes += bytes;
            logger.progress(byteCountToDisplaySize(totalBytes) + " downloaded");
        }
        return bytes;
    }
}

Adjust progress monitoring in downloading


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

package com.google.devtools.build.lib.skylarkbuildapi.platform;

import com.google.devtools.build.lib.skylarkbuildapi.StructApi;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModule;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModuleCategory;

/**
 * Info object representing data about a specific toolchain.
 */
@SkylarkModule(
    name = "ToolchainInfo",
    doc = "Provides access to data about a specific toolchain.",
    category = SkylarkModuleCategory.PROVIDER
)
public interface ToolchainInfoApi extends StructApi {
}

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

package com.google.devtools.build.lib.skylarkbuildapi.platform;

import com.google.devtools.build.lib.skylarkbuildapi.StructApi;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModule;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModuleCategory;

/** Info object representing data about a specific toolchain. */
@SkylarkModule(
    name = "ToolchainInfo",
    doc =
        "Provider which allows rule-specific toolchains to communicate data back to the actual"
            + " rule implementation. Read more about <a"
            + " href='../../toolchains.$DOC_EXT'>toolchains</a> for more information.",
    category = SkylarkModuleCategory.PROVIDER)
public interface ToolchainInfoApi extends StructApi {}

Improve the docs for ToolchainInfo and link to the main toolchains do?


package de.philipphager.disclosure.database.app.model;

import com.google.auto.value.AutoValue;

@AutoValue public abstract class AppReport implements AppModel.ReportModel {
  public static final AppModel.ReportMapper MAPPER = new AppModel.ReportMapper((App, libraryCount, permissionCount) -> create(App, libraryCount, permissionCount), App.FACTORY);

  public static AppReport create(AppModel app, long libraryCount, long permissionCount) {
    //TODO: Fix whe
    return new AutoValue_AppReport((App) app, libraryCount, permissionCount);
  }

  public abstract App App();

  public abstract long libraryCount();

  public abstract long permissionCount();

  public boolean librariesDetected() {
    return libraryCount() > 0;
  }

  public boolean wasAnalyzed() {
    return App().analyzedAt() != null;
  }
}

package de.philipphager.disclosure.database.app.model;

import com.google.auto.value.AutoValue;

@AutoValue public abstract class AppReport implements AppModel.ReportModel {
  public static final AppModel.ReportMapper MAPPER = new AppModel.ReportMapper((App, libraryCount, permissionCount) -> create(App, libraryCount, permissionCount), App.FACTORY);

  public static AppReport create(AppModel app, long libraryCount, long permissionCount) {
    //TODO: Fix whe
    return new AutoValue_AppReport((App) app, libraryCount, permissionCount);
  }

  /**
   * SqlDelight 0.6.0 alias bug in projection.
   * Tracked in Github issue 592.
   * Rename to lower case method name if fixed!
   * https://github.com/square/sqldelight/issues/592
   */
  @SuppressWarnings("PMD.MethodNamingConventions")
  public abstract App App();

  public abstract long libraryCount();

  public abstract long permissionCount();

  public boolean librariesDetected() {
    return libraryCount() > 0;
  }

  public boolean wasAnalyzed() {
    return App().analyzedAt() != null;
  }
}

Document uppercase method name bug


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

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import io.github.bonigarcia.wdm.WebDriverManager;

/**
 * Test with PhantomJS beta.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.4.0
 */
public class PhantomJsBetaTest {

    @BeforeEach
    public static void setupClass() {
        WebDriverManager.phantomjs().useBetaVersions().setup();
    }

    @Test
    public void testPhantomBeta() {
        String driverPath = WebDriverManager.phantomjs()
                .getDownloadedDriverPath();
        assertThat(driverPath).isNotNull();
    }
}

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

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import io.github.bonigarcia.wdm.WebDriverManager;

/**
 * Test with PhantomJS beta.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.4.0
 */
public class PhantomJsBetaTest {

    @BeforeAll
    public static void setupClass() {
        WebDriverManager.phantomjs().useBetaVersions().setup();
    }

    @Test
    public void testPhantomBeta() {
        String driverPath = WebDriverManager.phantomjs()
                .getDownloadedDriverPath();
        assertThat(driverPath).isNotNull();
    }
}

Fix setup of PhantomJS test


package org.swellrt.beta.client.rest.operations;

import org.swellrt.beta.client.ServiceContext;
import org.swellrt.beta.client.rest.ServerOperation;
import org.swellrt.beta.client.rest.ServiceOperation;
import org.swellrt.beta.client.rest.operations.params.Account;
import org.swellrt.beta.client.rest.operations.params.AccountImpl;
import org.swellrt.beta.client.rest.operations.params.Credential;
import org.swellrt.beta.common.SException;

public final class ResumeOperation
    extends ServerOperation<Credential, Account> {

  public ResumeOperation(ServiceContext context, Credential options,
      ServiceOperation.Callback<Account> callback) {
    super(context, options, callback, AccountImpl.class);
  }

  @Override
  public ServerOperation.Method getMethod() {
    return ServerOperation.Method.POST;
  }

  @Override
  protected void buildRestParams() throws SException {
    addPathElement("auth");
    addPathElement(options.getId());
  }

}

package org.swellrt.beta.client.rest.operations;

import org.swellrt.beta.client.ServiceContext;
import org.swellrt.beta.client.rest.ServerOperation;
import org.swellrt.beta.client.rest.ServiceOperation;
import org.swellrt.beta.client.rest.operations.params.Account;
import org.swellrt.beta.client.rest.operations.params.AccountImpl;
import org.swellrt.beta.client.rest.operations.params.Credential;
import org.swellrt.beta.common.SException;

public final class ResumeOperation
    extends ServerOperation<Credential, Account> {

  public ResumeOperation(ServiceContext context, Credential options,
      ServiceOperation.Callback<Account> callback) {
    super(context, options, callback, AccountImpl.class);
  }

  @Override
  public ServerOperation.Method getMethod() {
    return ServerOperation.Method.POST;
  }

  @Override
  protected void doSuccess(Account response) {
    context.initSession(response);
    super.doSuccess(response);
  }

  @Override
  protected void buildRestParams() throws SException {
    addPathElement("auth");
    addPathElement(options.getId());
  }

}

Fix resume operation, intialize session


package gr.demokritos.iit.ydsapi.model;

import java.util.HashSet;
import java.util.Set;

/**
 * accepted component types.
 *
 * @author George K. <gkiom@iit.demokritos.gr>
 */
public enum ComponentType {

    LINE("line"), SCATTER("scatter"), BUBBLE("bubble"), PIE("pie"), BAR("bar"), TREE("tree"), MAP("map"), GRID("grid"), INFO("info"), RESULT("result"), RESULTSET("resultset");
    private final String type;

    private ComponentType(String type) {
        this.type = type;
    }

    public String getDecl() {
        return type;
    }
    public static final Set<String> ACCEPTED = new HashSet();

    static {
        ACCEPTED.add(LINE.getDecl());
        ACCEPTED.add(SCATTER.getDecl());
        ACCEPTED.add(BUBBLE.getDecl());
        ACCEPTED.add(PIE.getDecl());
        ACCEPTED.add(BAR.getDecl());
        ACCEPTED.add(TREE.getDecl());
        ACCEPTED.add(MAP.getDecl());
        ACCEPTED.add(GRID.getDecl());
        ACCEPTED.add(INFO.getDecl());
        ACCEPTED.add(RESULT.getDecl());
        ACCEPTED.add(RESULTSET.getDecl());
    }
}

package gr.demokritos.iit.ydsapi.model;

import java.util.HashSet;
import java.util.Set;

/**
 * accepted component types.
 *
 * @author George K. <gkiom@iit.demokritos.gr>
 */
public enum ComponentType {
    LINE("line"), SCATTER("scatter"), BUBBLE("bubble"), PIE("pie"), BAR("bar"), TREE("tree"), MAP("map"), GRID("grid"),
    INFO("info"), BOX("box"), RESULT("result"), RESULTSET("resultset");
    private final String type;

    private ComponentType(String type) {
        this.type = type;
    }

    public String getDecl() {
        return type;
    }

    public static final Set<String> ACCEPTED = new HashSet();

    static {
        ACCEPTED.add(LINE.getDecl());
        ACCEPTED.add(SCATTER.getDecl());
        ACCEPTED.add(BUBBLE.getDecl());
        ACCEPTED.add(PIE.getDecl());
        ACCEPTED.add(BAR.getDecl());
        ACCEPTED.add(TREE.getDecl());
        ACCEPTED.add(MAP.getDecl());
        ACCEPTED.add(GRID.getDecl());
        ACCEPTED.add(INFO.getDecl());
        ACCEPTED.add(BOX.getDecl());
        ACCEPTED.add(RESULT.getDecl());
        ACCEPTED.add(RESULTSET.getDecl());
    }
}

Enable embedding/saving to basket "box" components in BackendUtils


package org.keycloak.examples.federation.properties;

import org.keycloak.models.KeycloakSession;
import org.keycloak.models.UserFederationProviderModel;

import java.io.InputStream;
import java.util.Properties;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class ClasspathPropertiesFederationFactory extends BasePropertiesFederationFactory {

    public static final String PROVIDER_NAME = "classpath-properties";

    @Override
    protected BasePropertiesFederationProvider createProvider(KeycloakSession session, UserFederationProviderModel model, Properties props) {
        return new ClasspathPropertiesFederationProvider(session, model, props);
    }

    protected InputStream getPropertiesFileStream(String path) {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
        if (is == null) {
            throw new IllegalStateException("Path not found for properties file");

        }
        return is;
    }

    @Override
    public String getId() {
        return PROVIDER_NAME;
    }
}

package org.keycloak.examples.federation.properties;

import org.keycloak.models.KeycloakSession;
import org.keycloak.models.UserFederationProviderModel;

import java.io.InputStream;
import java.util.Properties;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class ClasspathPropertiesFederationFactory extends BasePropertiesFederationFactory {

    public static final String PROVIDER_NAME = "classpath-properties";

    @Override
    protected BasePropertiesFederationProvider createProvider(KeycloakSession session, UserFederationProviderModel model, Properties props) {
        return new ClasspathPropertiesFederationProvider(session, model, props);
    }

    protected InputStream getPropertiesFileStream(String path) {
        InputStream is = getClass().getClassLoader().getResourceAsStream(path);
        if (is == null) {
            throw new IllegalStateException("Path not found for properties file");

        }
        return is;
    }

    @Override
    public String getId() {
        return PROVIDER_NAME;
    }
}

Fix federation provider example to load users file from it's own ClassLoader instead of Thread CL


package com.google.step.coffee.tasks;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.step.coffee.PermissionChecker;
import com.google.step.coffee.UserManager;
import com.google.step.coffee.data.RequestStore;
import com.google.step.coffee.entity.ChatRequest;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet triggered as cron job to match current chat requests together. Triggered periodically by
 * fetch.
 */
@WebServlet("/api/tasks/request-matching")
public class RequestMatchingTask extends HttpServlet {

  private RequestMatcher matcher = new RequestMatcher();

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String cronHeader = req.getHeader("X-Appengine-Cron");
    UserService userService = UserServiceFactory.getUserService();

    if (cronHeader == null || !Boolean.parseBoolean(cronHeader) || !userService.isUserAdmin()) {
      resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden action.");
      return;
    }

    RequestStore requestStore = new RequestStore();
    List<ChatRequest> requestList = requestStore.getUnmatchedRequests();

    matcher.matchRequests(requestList, requestStore);

    resp.setStatus(HttpServletResponse.SC_OK);
  }
}

package com.google.step.coffee.tasks;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.step.coffee.PermissionChecker;
import com.google.step.coffee.UserManager;
import com.google.step.coffee.data.RequestStore;
import com.google.step.coffee.entity.ChatRequest;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet triggered as cron job to match current chat requests together. Triggered periodically by
 * fetch.
 */
@WebServlet("/api/tasks/request-matching")
public class RequestMatchingTask extends HttpServlet {

  private RequestMatcher matcher = new RequestMatcher();

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String cronHeader = req.getHeader("X-Appengine-Cron");
    UserService userService = UserServiceFactory.getUserService();

    if (cronHeader == null || !Boolean.parseBoolean(cronHeader)) {
      resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden action.");
      return;
    }

    RequestStore requestStore = new RequestStore();
    List<ChatRequest> requestList = requestStore.getUnmatchedRequests();

    matcher.matchRequests(requestList, requestStore);

    resp.setStatus(HttpServletResponse.SC_OK);
  }
}

Change request matching cron to not allow admins to run directly


/*
 * Copyright 2015, Imtech Traffic & Infra
 * Copyright 2015, aVineas IT Consulting
 *
 * 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 osgi.extender.resource.impl;

import java.io.InputStream;
import java.net.URL;

import org.osgi.framework.Bundle;
import org.osgi.framework.wiring.BundleWiring;

import osgi.extender.resource.BundleResource;

/**
 * Our own implementation of a bundle resource. Simple wrapping.
 */
class OurBundleResource implements BundleResource {
    private Bundle bundle;
    private String path;

    OurBundleResource(Bundle bundle, String path) {
        this.bundle = bundle;
        this.path = path;
    }

    @Override
    public URL getURL() {
        return bundle.getEntry(path);
    }

    @Override
    public InputStream getInputStream() {
        return bundle.adapt(BundleWiring.class).getClassLoader().getResourceAsStream(path);
    }
}

/*
 * Copyright 2015, Imtech Traffic & Infra
 * Copyright 2015, aVineas IT Consulting
 *
 * 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 osgi.extender.resource.impl;

import java.io.InputStream;
import java.net.URL;

import org.osgi.framework.Bundle;

import osgi.extender.resource.BundleResource;

/**
 * Our own implementation of a bundle resource. Simple wrapping.
 */
class OurBundleResource implements BundleResource {
    private Bundle bundle;
    private String path;

    OurBundleResource(Bundle bundle, String path) {
        this.bundle = bundle;
        this.path = path;
    }

    @Override
    public URL getURL() {
        return bundle.getEntry(path);
    }

    @Override
    public InputStream getInputStream() {
        try {
            return getURL().openStream();
        } catch (Exception exc) {
            exc.printStackTrace();
        }
        return null;
    }
}

Use the URL to get the stream, not the class loader. Should not have made a different, but it does.


package com.google.configuration;

/** Retrieves the project configuration details. */
public final class ConfigurationFactory {
    private enum ProjectStatus {
        DEVELOPMENT,
        TEST,
        PRODUCTION
    }

    private static final ProjectStatus projectStatus = ProjectStatus.DEVELOPMENT;

    /**
     *
     * @return
     * @throws UnsupportedOperationException
     */
    public static final FireStoreConfiguration getFireStoreConfiguration() throws UnsupportedOperationException {
        FireStoreConfiguration fireStoreConfiguration = null;
        switch (projectStatus) {
            case PRODUCTION:
            case TEST:
                throw new UnsupportedOperationException("Not implemented");
            case DEVELOPMENT:
                fireStoreConfiguration = DevelopmentFireStoreConfiguration.getFireStoreConfiguration();
                break;
        }
        return fireStoreConfiguration;
    }
}

package com.google.configuration;

/** Retrieves the project configuration details. */
public final class ConfigurationFactory {
    private enum ProjectStatus {
        DEVELOPMENT,
        TEST,
        PRODUCTION
    }

    private static final ProjectStatus projectStatus = ProjectStatus.DEVELOPMENT;

    /**
     * Gets the configuration of the cloud firestore.
     *
     * @return Configuration details
     * @throws UnsupportedOperationException Cloud Firestore database is not created yet.
     */
    public static final FireStoreConfiguration getFireStoreConfiguration() throws UnsupportedOperationException {
        FireStoreConfiguration fireStoreConfiguration = null;
        switch (projectStatus) {
            case PRODUCTION:
            case TEST:
                throw new UnsupportedOperationException("Not implemented");
            case DEVELOPMENT:
                fireStoreConfiguration = DevelopmentFireStoreConfiguration.getFireStoreConfiguration();
                break;
        }
        return fireStoreConfiguration;
    }
}

Add javadoc for configuration factory


package se.jiderhamn.classloader.leak.prevention.cleanup;

import java.lang.reflect.Method;

import se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor;
import se.jiderhamn.classloader.leak.prevention.ClassLoaderPreMortemCleanUp;

/**
 * Clean up Reactor Netty resources
 * @author Mattias Jiderhamn
 */
public class ReactorNettyHttpResourcesCleanUp implements ClassLoaderPreMortemCleanUp {
  @Override
  public void cleanUp(ClassLoaderLeakPreventor preventor) {
    final Class<?> clazz = preventor.findClass("reactor.netty.http.HttpResources");
    if(preventor.isLoadedByClassLoader(clazz)) {
      final Method shutdown = preventor.findMethod(clazz, "shutdown");
      if(shutdown != null) {
        try {
          shutdown.invoke(null);
        }
        catch (Throwable e) {
          preventor.warn(e);
        }
      }
    }
  }
}

package se.jiderhamn.classloader.leak.prevention.cleanup;

import java.lang.reflect.Method;

import se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor;
import se.jiderhamn.classloader.leak.prevention.ClassLoaderPreMortemCleanUp;

/**
 * Clean up Reactor Netty resources
 * @author Mattias Jiderhamn
 */
public class ReactorNettyHttpResourcesCleanUp implements ClassLoaderPreMortemCleanUp {
  @Override
  public void cleanUp(ClassLoaderLeakPreventor preventor) {
    final Class<?> clazz = preventor.findClass("reactor.ipc.netty.http.HttpResources");
    if(preventor.isLoadedByClassLoader(clazz)) {
      final Method shutdown = preventor.findMethod(clazz, "shutdown");
      if(shutdown != null) {
        try {
          shutdown.invoke(null);
        }
        catch (Throwable e) {
          preventor.warn(e);
        }
      }
    }
  }
}

Correct qualified name of HttpResources


/*
 * Copyright 2014 satrapu.
 *
 * 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 ro.satrapu.churchmanagement.persistence;

import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

/**
 * Represents a {@link Person} who is available to act in a church as a discipleship teacher.
 *
 * @author satrapu
 */
@Entity
@Table(name = "Discipleship_Teachers")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class DiscipleshipTeacher extends ManagedEntityBase {

    private static final long serialVersionUID = 1L;

    @MapsId
    @OneToOne
    @JoinColumn(name = "Id")
    private Person person;
}

/*
 * Copyright 2014 satrapu.
 *
 * 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 ro.satrapu.churchmanagement.persistence;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

/**
 * Represents a {@link Person} who is available to act in a church as a discipleship teacher.
 *
 * @author satrapu
 */
@Entity
@Table(name = "Discipleship_Teachers")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class DiscipleshipTeacher extends ManagedEntityBase {

    private static final long serialVersionUID = 1L;

    @MapsId
    @OneToOne(optional = false, fetch = FetchType.EAGER)
    @JoinColumn(name = "Id")
    private Person person;
}

Enforce the fact that a discipleship teacher will always be associated with one person.


package com.atlassian.sal.api.net;

/**
 * @since   v2.2.0
 */
public interface ReturningResponseHandler<T extends Response, R>
{
    /**
     * Triggered when response from {@link Request#executeAndReturn(ReturningResponseHandler)}
     * method becomes available. Implementations of this method should handle the response.
     *
     * @param response a response object. Never {@code null}.
     * @throws ResponseException If the response cannot be retrieved
     */
    R handle(T response) throws ResponseException;
}

package com.atlassian.sal.api.net;

/**
 * Callback interface used by the {@link Request#executeAndReturn(ReturningResponseHandler)}
 * method. Implementation of this interface performs actual handling of the
 * response.
 * <p>
 * If no result will be produced, then instead of using this class, implement
 * {@link com.atlassian.sal.api.net.ResponseHandler} and pass it to
 * {@link Request#execute(ResponseHandler)}.
 *
 * @since   2.2
 */
public interface ReturningResponseHandler<T extends Response, R>
{
    /**
     * Triggered when response from {@link Request#executeAndReturn(ReturningResponseHandler)}
     * method becomes available. Implementations of this method should handle the response.
     *
     * @param response a response object. Never {@code null}.
     * @return the result produces by this handler.
     * @throws ResponseException If the response cannot be retrieved
     */
    R handle(T response) throws ResponseException;
}

Add a new Request.execute(ResponseHandler) method that returns a generic result Added more javadoc.


package de.philipphager.disclosure.feature.app.detail;

import de.philipphager.disclosure.database.library.model.Library;
import de.philipphager.disclosure.feature.navigation.Navigates;
import de.philipphager.disclosure.util.ui.components.ScoreView;
import java.util.List;

public interface DetailView extends Navigates {
  void notify(String message);

  void setToolbarTitle(String title);

  void setAppIcon(String packageName);

  void setLibraries(List<Library> libraries);

  void setScore(ScoreView.Score score);
}

package de.philipphager.disclosure.feature.app.detail;

import android.content.Intent;
import de.philipphager.disclosure.database.library.model.Library;
import de.philipphager.disclosure.feature.navigation.Navigates;
import de.philipphager.disclosure.util.ui.components.ScoreView;
import java.util.List;

public interface DetailView extends Navigates {
  void notify(String message);

  void setToolbarTitle(String title);

  void setAppIcon(String packageName);

  void setLibraries(List<Library> libraries);

  void setScore(ScoreView.Score score);

  void showEditPermissionsTutorial(String packageName);

  void showRuntimePermissionsTutorial(String packageName);

  void enableEditPermissions(boolean isEnabled);

  void startActivityForResult(Intent intent, int requestCode);

  void finish();
}

Update view interface for app detail activity


package ru.tulupov.nsuconnect.database.loader;

import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import android.util.Log;

import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;

import java.sql.SQLException;
import java.util.List;

import ru.tulupov.nsuconnect.database.DatabaseContract;
import ru.tulupov.nsuconnect.database.HelperFactory;
import ru.tulupov.nsuconnect.model.Chat;
import ru.tulupov.nsuconnect.model.Message;

public class ChatLoader extends AsyncTaskLoader<List<Chat>> {
    private static final String TAG = ChatLoader.class.getSimpleName();

    public ChatLoader(Context context) {
        super(context);
    }

    @Override
    public List<Chat> loadInBackground() {
        try {
            QueryBuilder<Chat, Integer> queryBuilder = HelperFactory.getHelper().getChatDao().queryBuilder();
            queryBuilder.orderBy(DatabaseContract.Chat.DATE, false);
            PreparedQuery<Chat> preparedQuery = queryBuilder.prepare();
            List<Chat> chats = HelperFactory.getHelper().getChatDao().query(preparedQuery);

            return chats;
        } catch (SQLException e) {
            Log.e(TAG, "Error", e);
        }
        return null;
    }

}

package ru.tulupov.nsuconnect.database.loader;

import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import android.util.Log;

import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;

import java.sql.SQLException;
import java.util.List;

import ru.tulupov.nsuconnect.database.DatabaseContract;
import ru.tulupov.nsuconnect.database.HelperFactory;
import ru.tulupov.nsuconnect.model.Chat;
import ru.tulupov.nsuconnect.model.Message;

public class ChatLoader extends AsyncTaskLoader<List<Chat>> {
    private static final String TAG = ChatLoader.class.getSimpleName();

    public ChatLoader(Context context) {
        super(context);
    }

    @Override
    public List<Chat> loadInBackground() {
        try {
            QueryBuilder<Chat, Integer> queryBuilder = HelperFactory.getHelper().getChatDao().queryBuilder();
            queryBuilder.orderBy(DatabaseContract.Chat.DATE, false);
            queryBuilder.orderBy(DatabaseContract.Chat.ACTIVE_FLAG, false);
            PreparedQuery<Chat> preparedQuery = queryBuilder.prepare();
            List<Chat> chats = HelperFactory.getHelper().getChatDao().query(preparedQuery);

            return chats;
        } catch (SQLException e) {
            Log.e(TAG, "Error", e);
        }
        return null;
    }

}

Change sort order in chat list


package com.github.solairerove.woodstock.repository;

import com.github.solairerove.woodstock.domain.base.BaseEntity;
import org.springframework.data.neo4j.repository.GraphRepository;

public interface GenericRepository<T extends BaseEntity> extends GraphRepository<T> {

}

package com.github.solairerove.woodstock.repository;

import com.github.solairerove.woodstock.domain.base.BaseEntity;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.data.repository.query.Param;

public interface GenericRepository<T extends BaseEntity> extends GraphRepository<T> {

    @Query("MATCH (task:Task)<-[:HAS_IN]-(tickets) WHERE id(task)={id1} RETURN tickets")
    Iterable<T> getTicketsThatHasInTaskFromId(@Param("id") Long id1);

    @Query("MATCH (task:Task)<-[:HAS_IN]-(ticket) WHERE id(task)={id1} AND id(ticket)={id2} RETURN ticket")
    T getTicketThatHasInTaskFromId(@Param("id1") Long id1, @Param("id2") Long id2);
}

Create generic repository stub: - how solve problem with entity


/*-
 * #%L
 * SciJava polyglot kernel for Jupyter.
 * %%
 * Copyright (C) 2017 Hadrien Mary
 * %%
 * 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%
 */

package org.scijava.notebook.converter;

import org.scijava.convert.ConvertService;
import org.scijava.notebook.converter.output.HTMLFriendlyNotebookOutput;
import org.scijava.notebook.converter.output.HTMLNotebookOutput;
import org.scijava.plugin.Parameter;

/**
 * Base class for converters to {@link HTMLNotebookOutput} and subclasses.
 *
 * @author Curtis Rueden
 */
public abstract class HTMLNotebookOutputConverter<I, O extends HTMLNotebookOutput>
    extends NotebookOutputConverter<I, O>
{

    @Parameter
    private ConvertService convertService;

    /** Gets an HTML string representing the given object. */
    protected String asHTML(final Object o) {
        return convertService.convert(o, HTMLFriendlyNotebookOutput.class).toHTML();
    }

}

/*-
 * #%L
 * SciJava polyglot kernel for Jupyter.
 * %%
 * Copyright (C) 2017 Hadrien Mary
 * %%
 * 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%
 */

package org.scijava.notebook.converter;

import org.scijava.convert.ConvertService;
import org.scijava.notebook.converter.output.HTMLFriendlyNotebookOutput;
import org.scijava.notebook.converter.output.HTMLNotebookOutput;
import org.scijava.plugin.Parameter;

/**
 * Base class for converters to {@link HTMLNotebookOutput} and subclasses.
 *
 * @author Curtis Rueden
 */
public abstract class HTMLNotebookOutputConverter<I, O extends HTMLNotebookOutput>
    extends NotebookOutputConverter<I, O>
{

    @Parameter
    private ConvertService convertService;

    /** Gets an HTML string representing the given object. */
    protected String asHTML(final Object o) {
        final HTMLFriendlyNotebookOutput converted = convertService.convert(o, HTMLFriendlyNotebookOutput.class);
        return converted == null ? "<none>" : converted.toHTML();
    }

}

Add null logic to asHTML(...)


package org.realityforge.arez.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Annotate the method that should return the Id for Arez container.
 *
 *
This annotation should appear at most once on a container and should
 * not be present if the {@link Container#singleton()} is set to true. The
 * annotation should be on a method that accepts no parameters and returns
 * a non-null value.

 *
 *
If this annotation is present, it indicates that the Annotation processor
 * should call this method to get the ID of the container. This ID should be
 * constant and unique (enough) to identify container. It is used when generating
 * debug names for observables nested within the container. If this annotation is
 * not present the Annotation processor will synthesize an ID by calling
 * ArezContext.nextNodeId()

 */
@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.METHOD )
public @interface ContainerId
{
}

package org.realityforge.arez.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Annotate the method that should return the Id for Arez container.
 *
 *
This annotation should appear at most once on a container and should
 * not be present if the {@link Container#singleton()} is set to true. The
 * annotation should be on a method that accepts no parameters and returns
 * a non-null value.

 *
 *
If this annotation is present, it indicates that the Annotation processor
 * should call this method to get the ID of the container. This ID should be
 * constant and unique (enough) to identify container. It is used when generating
 * debug names for observables nested within the container. If this annotation is
 * not present the Annotation processor will synthesize an ID as a
 * monotonically increasing integer for each instance of the type.

 */
@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.METHOD )
public @interface ContainerId
{
}

Correct the javadocs about how the id is generated


package com.bigcommerce.catalog.models;

import javax.xml.bind.annotation.XmlRootElement;
import java.util.LinkedList;
import java.util.List;

@XmlRootElement
public class CustomFieldResponse {
	private CustomField data;

	public CustomField getData() {
		return data;
	}

	public void setData(CustomField data) {
		this.data = data;
	}
}

package com.bigcommerce.catalog.models;

import javax.xml.bind.annotation.XmlRootElement;
import java.util.LinkedList;
import java.util.List;

@XmlRootElement
public class CustomFieldResponse {
	private CustomField data;
	private Meta meta = new Meta();

	public CustomField getData() {
		return data;
	}

	public void setData(CustomField data) {
		this.data = data;
	}

	public Meta getMeta() {
		return meta;
	}

	public void setMeta(final Meta meta) {
		this.meta = meta;
	}
}

Add meta field to custom field response


package grails.plugin.multitenant.core.filter;

import grails.plugin.multitenant.core.CurrentTenant;
import grails.plugin.multitenant.core.resolve.TenantResolver;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class CurrentTenantFilter implements Filter {

    private CurrentTenant currentTenant;
    private TenantResolver tenantResolver;

    @Override
    public void init(FilterConfig fc) throws ServletException {
        ServletContext servletContext = fc.getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        currentTenant = (CurrentTenant) ctx.getBean("currentTenant");
        tenantResolver = (TenantResolver) ctx.getBean("tenantResolver");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain filterChain) throws IOException, ServletException {

        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            int currentTenantId = tenantResolver.resolve(httpRequest);
            currentTenant.set(currentTenantId);
        }

        filterChain.doFilter(request, response);
        currentTenant.set(-1);
    }

    @Override
    public void destroy() {
    }

}

package grails.plugin.multitenant.core.filter;

import grails.plugin.multitenant.core.CurrentTenant;
import grails.plugin.multitenant.core.resolve.TenantResolver;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 *
 * @author Kim A. Betti
 */
public class CurrentTenantFilter implements Filter {

    private CurrentTenant currentTenant; // thread local storage
    private TenantResolver tenantResolver; // provided by implementation

    @Override
    public void init(FilterConfig fc) throws ServletException {
        ServletContext servletContext = fc.getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        currentTenant = (CurrentTenant) ctx.getBean("currentTenant");
        tenantResolver = (TenantResolver) ctx.getBean("tenantResolver");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
    		FilterChain filterChain) throws IOException, ServletException {

    	try {
	        if (request instanceof HttpServletRequest) {
	            HttpServletRequest httpRequest = (HttpServletRequest) request;
	            int currentTenantId = tenantResolver.resolve(httpRequest);
	            currentTenant.set(currentTenantId);
	        }

	        filterChain.doFilter(request, response);
    	} finally {
    		currentTenant.set(-1);
    	}
    }

    @Override
    public void destroy() {
    }

}

Make sure that current-tenant thread local storage is reset in the event of an exception


package com.github.aureliano.achmed.helper;

import java.lang.reflect.Method;

import com.github.aureliano.achmed.exception.AchmedException;

public final class ReflectionHelper {

	private ReflectionHelper() {
		throw new InstantiationError(this.getClass().getName() + " cannot be instantiated.");
	}

    public static Object callMethod(Object object, String methodName, Class<?>[] parametersType, Object[] methodParameters) {
    	Class<?> clazz = object.getClass();
    	try {
    		Method method = clazz.getMethod(methodName, parametersType);
    		return method.invoke(object, methodParameters);
    	} catch (Exception ex) {
    		throw new AchmedException(ex);
    	}
    }

    public static String getSimpleAccessMethodName(Method method) {
    	String name = method.getName().replaceFirst("^(get|is|set|with)", "");
    	return Character.toLowerCase(name.charAt(0)) + name.substring(1);
    }
}

package com.github.aureliano.achmed.helper;

import java.lang.reflect.Method;

import com.github.aureliano.achmed.exception.AchmedException;

public final class ReflectionHelper {

	private ReflectionHelper() {
		throw new InstantiationError(this.getClass().getName() + " cannot be instantiated.");
	}

    public static Object newInstance(Class<?> clazz) {
    	try {
    		return clazz.newInstance();
    	} catch (Exception ex) {
    		throw new AchmedException(ex);
    	}
    }

    public static Object callMethod(Object object, String methodName, Class<?>[] parametersType, Object[] methodParameters) {
    	Class<?> clazz = object.getClass();
    	try {
    		Method method = clazz.getMethod(methodName, parametersType);
    		return method.invoke(object, methodParameters);
    	} catch (Exception ex) {
    		throw new AchmedException(ex);
    	}
    }

    public static String getSimpleAccessMethodName(Method method) {
    	String name = method.getName().replaceFirst("^(get|is|set|with)", "");
    	return Character.toLowerCase(name.charAt(0)) + name.substring(1);
    }
}

Add method to instantiate object by reflection.


package com.musicocracy.fpgk.ioc.activity;

import com.musicocracy.fpgk.domain.spotify.Browser;
import com.musicocracy.fpgk.mvp.model.SongSelectModel;
import com.musicocracy.fpgk.mvp.presenter.SongSelectPresenter;

import dagger.Module;
import dagger.Provides;

@Module
public class SongSelectModule {
    @Provides
    public SongSelectModel provideSongSelectModel(Browser browser) {
        return new SongSelectModel(browser, api);
    }

    @Provides
    public SongSelectPresenter provideSongSelectPresenter(SongSelectModel model) {
        return new SongSelectPresenter(model);
    }
}

package com.musicocracy.fpgk.ioc.activity;

import com.musicocracy.fpgk.domain.spotify.Browser;
import com.musicocracy.fpgk.mvp.model.SongSelectModel;
import com.musicocracy.fpgk.mvp.presenter.SongSelectPresenter;

import dagger.Module;
import dagger.Provides;
import kaaes.spotify.webapi.android.SpotifyApi;

@Module
public class SongSelectModule {
    @Provides
    public SongSelectModel provideSongSelectModel(Browser browser, SpotifyApi api) {
        return new SongSelectModel(browser, api);
    }

    @Provides
    public SongSelectPresenter provideSongSelectPresenter(SongSelectModel model) {
        return new SongSelectPresenter(model);
    }
}

Set up dependency injection for spotify module including Spotify Api, Spotify Service, and the Browser.


package com.obidea.semantika.cli2.command;

import java.io.PrintStream;
import java.util.Map;

import com.obidea.semantika.cli2.runtime.ConsoleSession;

public class ShowPrefixesCommand extends Command
{
   private ConsoleSession mSession;

   public ShowPrefixesCommand(String command, ConsoleSession session)
   {
      mSession = session;
   }

   @Override
   public Object execute() throws Exception
   {
      return mSession.getPrefixMapper();
   }

   @Override
   public void printOutput(PrintStream out, Object output)
   {
      if (output instanceof Map<?, ?>) {
         @SuppressWarnings("unchecked")
         Map<String, String> map = (Map<String, String>) output;
         for (String prefix : map.keySet()) {
            out.println(prefix + ": " + map.get(prefix));
         }
      }
      out.println();
   }
}

package com.obidea.semantika.cli2.command;

import java.io.PrintStream;
import java.util.Map;

import com.obidea.semantika.cli2.runtime.ConsoleSession;
import com.obidea.semantika.util.StringUtils;

public class ShowPrefixesCommand extends Command
{
   private ConsoleSession mSession;

   public ShowPrefixesCommand(String command, ConsoleSession session)
   {
      mSession = session;
   }

   @Override
   public Object execute() throws Exception
   {
      return mSession.getPrefixMapper();
   }

   @Override
   public void printOutput(PrintStream out, Object output)
   {
      if (output instanceof Map<?, ?>) {
         @SuppressWarnings("unchecked")
         Map<String, String> map = (Map<String, String>) output;
         for (String key : map.keySet()) {
            String prefix = key;
            if (StringUtils.isEmpty(prefix)) {
               prefix = "(default)"; //
            }
            out.println(prefix + " = " + map.get(key));
         }
      }
      out.println();
   }
}

Change the show prefixes commmand output.


package no.stelar7.api.r4j.basic.constants.types.val;

import no.stelar7.api.r4j.basic.constants.types.CodedEnum;

import java.util.Optional;
import java.util.stream.Stream;

public enum GameQueueType implements CodedEnum<GameQueueType>
{

    COMPETITIVE("competitive"),
    DEATHMATCH("deathmatch"),
    SPIKE_RUSH("spikerush"),
    UNRATED("unrated"),
    CUSTOM_GAME(""),
    ;

    private final String queue;

    /**
     * Constructor for MapType
     *
     * @param code the mapId
     */
    GameQueueType(final String code)
    {
        this.queue = code;
    }

    /**
     * Gets from code.
     *
     * @param mapId the map id
     * @return the from code
     */
    public Optional<GameQueueType> getFromCode(final String mapId)
    {
        return Stream.of(GameQueueType.values()).filter(t -> t.queue.equals(mapId)).findFirst();
    }

    @Override
    public String prettyName()
    {
        switch (this)
        {
            default:
                return "This enum does not have a pretty name";
        }
    }

    /**
     * Gets id.
     *
     * @return the id
     */
    public String getId()
    {
        return this.queue;
    }

    /**
     * Used internaly in the api...
     *
     * @return the value
     */
    public String getValue()
    {
        return getId();
    }

}

package no.stelar7.api.r4j.basic.constants.types.val;

import no.stelar7.api.r4j.basic.constants.types.CodedEnum;

import java.util.Optional;
import java.util.stream.Stream;

public enum GameQueueType implements CodedEnum<GameQueueType>
{

    COMPETITIVE("competitive"),
    DEATHMATCH("deathmatch"),
    SPIKE_RUSH("spikerush"),
    UNRATED("unrated"),
    CUSTOM_GAME(""),
    TOURNAMENT_MODE("tournamentmode"),
    ;

    private final String queue;

    /**
     * Constructor for MapType
     *
     * @param code the mapId
     */
    GameQueueType(final String code)
    {
        this.queue = code;
    }

    /**
     * Gets from code.
     *
     * @param mapId the map id
     * @return the from code
     */
    public Optional<GameQueueType> getFromCode(final String mapId)
    {
        return Stream.of(GameQueueType.values()).filter(t -> t.queue.equals(mapId)).findFirst();
    }

    @Override
    public String prettyName()
    {
        switch (this)
        {
            default:
                return "This enum does not have a pretty name";
        }
    }

    /**
     * Gets id.
     *
     * @return the id
     */
    public String getId()
    {
        return this.queue;
    }

    /**
     * Used internaly in the api...
     *
     * @return the value
     */
    public String getValue()
    {
        return getId();
    }

}

Add tournamentmode to valorant recent games


package pl.tomaszdziurko.jvm_bloggers;

public class TimeConstants {

    public static final String EVERY_TEN_MINUTES = "0 10,20,30,40,50 * * * *";

    public static final String EVERY_FRIDAY_AT_12_OCLOCK = "0 12 0 * * FRI";

}

package pl.tomaszdziurko.jvm_bloggers;

public class TimeConstants {

    public static final String EVERY_TEN_MINUTES = "0 10,20,30,40,50 * * * *";

    public static final String EVERY_FRIDAY_AT_12_OCLOCK = "0 0 12 * * FRI";

}

Fix incorrect time to send mailing


package org.pikater.core.ontology.subtrees.metadata;

import java.util.List;

import jade.content.Concept;

public class Metadatas implements Concept {

	/**
	 *
	 */
	private static final long serialVersionUID = -7879865268316684239L;

	private List<Metadata> metadatas;

	public List<Metadata> getMetadatas() {
		return metadatas;
	}

	public void setMetadatas(List<Metadata> metadatas) {
		this.metadatas = metadatas;
	}

}

package org.pikater.core.ontology.subtrees.metadata;

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

import jade.content.Concept;

public class Metadatas implements Concept {

	/**
	 *
	 */
	private static final long serialVersionUID = -7879865268316684239L;

	private List<Metadata> metadatas;

	public Metadatas(){
		this.metadatas=new ArrayList<Metadata>();
	}

	public List<Metadata> getMetadatas() {
		return metadatas;
	}

	public void setMetadatas(List<Metadata> metadatas) {
		this.metadatas = metadatas;
	}

}

Fix NPE if no results are found


package am.app.mappingEngine.qualityEvaluation.metrics.ufl;

import java.util.List;

import am.app.mappingEngine.AbstractMatcher.alignType;
import am.app.mappingEngine.qualityEvaluation.AbstractQualityMetric;
import am.app.mappingEngine.similarityMatrix.SimilarityMatrix;
import static am.evaluation.disagreement.variance.VarianceComputation.computeVariance;

/**
 * Compute the disagreement between matching algorithms given their individual
 * similarity matrices. The constructor takes only one kind of matrix, either
 * the classes matrices or the properties matrices. You must instantiate a
 * separate object for each type of matrices.
 *
 * @author Cosmin Stroe
 *
 */
public class VarianceMatcherDisagreement extends AbstractQualityMetric {

	private SimilarityMatrix[] matrices;

	public VarianceMatcherDisagreement(List<SimilarityMatrix> matrices) {
		super();
		this.matrices = matrices.toArray(new SimilarityMatrix[0]);
	}

	/**
	 * @param type
	 *            This parameter is ignored.
	 */
	@Override
	public double getQuality(alignType type, int i, int j) {
		// create signature vector
		double[] signatureVector = new double[matrices.length];
		for(int k = 0; k < matrices.length; k++) {
			signatureVector[k] = matrices[k].getSimilarity(i, j);
		}

		// return the computed variance
		return computeVariance(signatureVector);
	}
}

package am.app.mappingEngine.qualityEvaluation.metrics.ufl;

import java.util.List;

import am.app.mappingEngine.AbstractMatcher.alignType;
import am.app.mappingEngine.qualityEvaluation.AbstractQualityMetric;
import am.app.mappingEngine.similarityMatrix.SimilarityMatrix;
import static am.evaluation.disagreement.variance.VarianceComputation.computeVariance;

/**
 * Compute the disagreement between matching algorithms given their individual
 * similarity matrices. The constructor takes only one kind of matrix, either
 * the classes matrices or the properties matrices. You must instantiate a
 * separate object for each type of matrices.
 *
 * @author Cosmin Stroe
 *
 */
public class VarianceMatcherDisagreement extends AbstractQualityMetric {

	private SimilarityMatrix[] matrices;

	public VarianceMatcherDisagreement(List<SimilarityMatrix> matrices) {
		super();
		this.matrices = matrices.toArray(new SimilarityMatrix[0]);
	}

	/**
	 * @param type
	 *            This parameter is ignored.
	 */
	@Override
	public double getQuality(alignType type, int i, int j) {
		// create signature vector
		double[] signatureVector = new double[matrices.length];
		for(int k = 0; k < matrices.length; k++) {
			signatureVector[k] = matrices[k].getSimilarity(i, j);
		}

		// return the computed variance
		// because variance of similarity values can be a maximum of 0.5, we
		// multiply by 2 to get a metric from 0 to 1.0
		return 2 * computeVariance(signatureVector);
	}
}

Normalize the variance to 1.0 (from 0.5)


package seedu.agendum.model.task;

import seedu.agendum.commons.exceptions.IllegalValueException;

/**
 * Represents a Task's name in the to do list.
 * Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
 */
public class Name {

    public static final String MESSAGE_NAME_CONSTRAINTS = "Task names should only conyain spaces or alphanumeric characters";
    public static final String NAME_VALIDATION_REGEX = "[\\p{Alnum} ]+";

    public final String fullName;

    /**
     * Validates given name.
     *
     * @throws IllegalValueException if given name string is invalid.
     */
    public Name(String name) throws IllegalValueException {
        assert name != null;
        name = name.trim();
        if (!isValidName(name)) {
            throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
        }
        this.fullName = name;
    }

    /**
     * Returns true if a given string is a valid task name.
     */
    public static boolean isValidName(String test) {
        return test.matches(NAME_VALIDATION_REGEX);
    }

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

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof Name // instanceof handles nulls
                && this.fullName.equals(((Name) other).fullName)); // state check
    }

    @Override
    public int hashCode() {
        return fullName.hashCode();
    }

}

package seedu.agendum.model.task;

import seedu.agendum.commons.exceptions.IllegalValueException;

/**
 * Represents a Task's name in the to do list.
 * Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
 */
public class Name {

    public static final String MESSAGE_NAME_CONSTRAINTS = "Task names should only contain spaces or alphanumeric characters";
    public static final String NAME_VALIDATION_REGEX = "[\\p{Alnum} ]+";

    public final String fullName;

    /**
     * Validates given name.
     *
     * @throws IllegalValueException if given name string is invalid.
     */
    public Name(String name) throws IllegalValueException {
        assert name != null;
        name = name.trim();
        if (!isValidName(name)) {
            throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
        }
        this.fullName = name;
    }

    /**
     * Returns true if a given string is a valid task name.
     */
    public static boolean isValidName(String test) {
        return test.matches(NAME_VALIDATION_REGEX);
    }

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

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof Name // instanceof handles nulls
                && this.fullName.equals(((Name) other).fullName)); // state check
    }

    @Override
    public int hashCode() {
        return fullName.hashCode();
    }

}

Fix typo in message name constraints


package tars.logic;

import org.junit.Test;

import tars.logic.commands.CdCommand;

/**
 * Logic command test for cd
 *
 * @@author A0124333U
 */
public class CdLogicCommandTest extends LogicCommandTest {
    @Test
    public void execute_cd_incorrectArgsFormatErrorMessageShown()
            throws Exception {
        assertCommandBehavior("cd ", CdCommand.MESSAGE_INVALID_FILEPATH);
    }

    @Test
    public void execute_cd_invalidFileTypeErrorMessageShown() throws Exception {
        assertCommandBehavior("cd invalidFileType",
                CdCommand.MESSAGE_INVALID_FILEPATH);
    }

    @Test
    public void execute_cd_success() throws Exception {
        String tempTestTarsFilePath =
                saveFolder.getRoot().getPath() + "TempTestTars.xml";
        assertCommandBehavior("cd " + tempTestTarsFilePath,
                String.format(CdCommand.MESSAGE_SUCCESS_NEW_FILE, tempTestTarsFilePath));
    }
}

package tars.logic;

import java.io.File;

import org.junit.Test;

import tars.commons.util.FileUtil;
import tars.logic.commands.CdCommand;
import tars.model.Tars;
import tars.storage.TarsStorage;
import tars.storage.XmlTarsStorage;

/**
 * Logic command test for cd
 *
 * @@author A0124333U
 */
public class CdLogicCommandTest extends LogicCommandTest {
  @Test
  public void execute_cd_incorrectArgsFormatErrorMessageShown() throws Exception {
    assertCommandBehavior("cd ", CdCommand.MESSAGE_INVALID_FILEPATH);
  }

  @Test
  public void execute_cd_invalidFileTypeErrorMessageShown() throws Exception {
    assertCommandBehavior("cd invalidFileType", CdCommand.MESSAGE_INVALID_FILEPATH);
  }

  @Test
  public void execute_cd_new_file_success() throws Exception {
    String tempTestTarsFilePath = saveFolder.getRoot().getPath() + "TempTestTars.xml";
    assertCommandBehavior("cd " + tempTestTarsFilePath,
        String.format(CdCommand.MESSAGE_SUCCESS_NEW_FILE, tempTestTarsFilePath));
  }

  @Test
  public void execute_cd_existing_file_failureToReadExistingFile() throws Exception {
    String existingFilePath = saveFolder.getRoot().getPath() + "TempTars.xml";
    File existingFile = new File(existingFilePath);
    FileUtil.createIfMissing(existingFile);
    assertCommandBehavior("cd " + existingFilePath, CdCommand.MESSAGE_FAILURE_READ_FILE);
  }

  @Test
  public void execute_cd_existing_file_success() throws Exception {
    String existingFilePath = saveFolder.getRoot().getPath() + "TempTars.xml";
    TarsStorage testStorage = new XmlTarsStorage(existingFilePath);
    testStorage.saveTars(Tars.getEmptyTars());
    assertCommandBehavior("cd " + existingFilePath,
        String.format(CdCommand.MESSAGE_SUCCESS_EXISTING_FILE, existingFilePath));
  }
}

Add logic tests for CdCommand


package info.u_team.u_team_test.data.provider;

import info.u_team.u_team_core.data.*;
import info.u_team.u_team_test.init.*;

public class TestItemModelsProvider extends CommonItemModelsProvider {

	public TestItemModelsProvider(GenerationData data) {
		super(data);
	}

	@Override
	protected void registerModels() {
		// Items
		simpleGenerated(TestItems.BASIC.get());
		simpleGenerated(TestItems.BASIC_FOOD.get());
		simpleGenerated(TestItems.BETTER_ENDERPEARL.get());
		iterateItems(TestItems.BASIC_ARMOR, this::simpleGenerated);
		iterateItems(TestItems.BASIC_TOOL, this::simpleHandheld);
		// Blocks
		simpleBlock(TestBlocks.BASIC.get());
		simpleBlock(TestBlocks.BASIC_TILEENTITY.get());
		simpleBlock(TestBlocks.BASIC_ENERGY_CREATOR.get());
		simpleBlock(TestBlocks.BASIC_FLUID_INVENTORY.get());
	}

}

package info.u_team.u_team_test.data.provider;

import info.u_team.u_team_core.data.*;
import info.u_team.u_team_test.init.*;

public class TestItemModelsProvider extends CommonItemModelsProvider {

	public TestItemModelsProvider(GenerationData data) {
		super(data);
	}

	@Override
	protected void registerModels() {
		// Items
		simpleGenerated(TestItems.BASIC.get());
		simpleGenerated(TestItems.BASIC_FOOD.get());
		simpleGenerated(TestItems.BETTER_ENDERPEARL.get());
//		iterateItems(TestItems.BASIC_ARMOR, this::simpleGenerated); // TODO
//		iterateItems(TestItems.BASIC_TOOL, this::simpleHandheld); // TODO
		// Blocks
		simpleBlock(TestBlocks.BASIC.get());
		simpleBlock(TestBlocks.BASIC_TILEENTITY.get());
		simpleBlock(TestBlocks.BASIC_ENERGY_CREATOR.get());
		simpleBlock(TestBlocks.BASIC_FLUID_INVENTORY.get());
	}

}

Comment so it can compile for testing


package swift.crdt.interfaces;

import swift.clocks.CausalityClock;
import swift.exceptions.InvalidParameterException;

/**
 * Source for generating new timestamps.
 *
 * @author nmp
 */
public interface TimestampSource<T> {

    /**
     * Generates a new timestamp.
     *
     * @return
     */
    <V extends CausalityClock<V>> T generateNew();

}

package swift.crdt.interfaces;

/**
 * Source for generating new timestamps.
 *
 * @author nmp
 */
public interface TimestampSource<T> {

    /**
     * Generates a new timestamp.
     *
     * @return
     */
    T generateNew();

}

Remove unnecessary generic - does it help to compile?


package org.ensembl.healthcheck.testcase.eg_core;

import java.sql.Connection;

import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.Team;

/**
 * @author mnuhn
 *
 * <p>
 * 	Test for correctness of variation schemas, suggests a patch, if the schemas
 * differ.
 * </p>
 *
 */
public class EGCompareVariationSchema extends EGAbstractCompareSchema {

	public EGCompareVariationSchema() {
		setTeamResponsible(Team.ENSEMBL_GENOMES);
		addAppliesToType(DatabaseType.VARIATION);
	}

	@Override
	protected String getDefinitionFileKey() {
		return "variation_schema.file";
	}

	@Override
	protected String getMasterSchemaKey() {
		return "master.variation_schema";
	}

	@Override
	protected boolean assertSchemaCompatibility(
			Connection masterCon,
			Connection checkCon
	) {
		return
			assertSchemaTypesCompatible(masterCon, checkCon);
	}
}

package org.ensembl.healthcheck.testcase.eg_core;

import java.sql.Connection;

import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.Team;

/**
 * @author mnuhn
 *
 * <p>
 * 	Test for correctness of variation schemas, suggests a patch, if the schemas
 * differ.
 * </p>
 *
 */
public class EGCompareVariationSchema extends EGAbstractCompareSchema {

	public EGCompareVariationSchema() {
		setTeamResponsible(Team.ENSEMBL_GENOMES);
	}

	@Override
	public void types() {
		addAppliesToType(DatabaseType.VARIATION);
	}

	@Override
	protected String getDefinitionFileKey() {
		return "variation_schema.file";
	}

	@Override
	protected String getMasterSchemaKey() {
		return "master.variation_schema";
	}

	@Override
	protected boolean assertSchemaCompatibility(
			Connection masterCon,
			Connection checkCon
	) {
		return
			assertSchemaTypesCompatible(masterCon, checkCon);
	}
}

Make it apply only to variation databases


package org.col.dw.cors;

import org.hibernate.validator.constraints.NotEmpty;

public class CorsConfiguration {
  public static final String ANY_ORIGIN = "*";

  @NotEmpty
  public String origins = ANY_ORIGIN;

  @NotEmpty
  public String methods = "OPTIONS, GET, POST, PUT, DELETE";

  @NotEmpty
  public String headers = "Authorization";

  public boolean anyOrigin() {
    return ANY_ORIGIN.equals(origins);
  }

}

package org.col.dw.cors;

import org.hibernate.validator.constraints.NotEmpty;

public class CorsConfiguration {
  public static final String ANY_ORIGIN = "*";

  @NotEmpty
  public String origins = ANY_ORIGIN;

  @NotEmpty
  public String methods = "OPTIONS, HEAD, GET, POST, PUT, DELETE";

  @NotEmpty
  public String headers = "Authorization, Content-Type";

  public boolean anyOrigin() {
    return ANY_ORIGIN.equals(origins);
  }

}

Add Content-Type to allowed default headers


package com.lloydtorres.stately.dto;

/**
 * Created by Lloyd on 2016-07-24.
 * A holder for data in the main nation overview card.
 */
public class NationOverviewCardData {
    public String category;
    public String region;
    public String inflDesc;
    public int inflScore;
    public String population;
    public String motto;
    public String established;

    public String waState;
    public String endorsements;
    public String gaVote;
    public String scVote;

    public NationOverviewCardData() { super(); }
}

package com.lloydtorres.stately.dto;

/**
 * Created by Lloyd on 2016-07-24.
 * A holder for data in the main nation overview card.
 */
public class NationOverviewCardData {
    public String category;
    public String region;
    public String inflDesc;
    public int inflScore;
    public String population;
    public String motto;
    public String established;
    public String lastSeen;

    public String waState;
    public String endorsements;
    public String gaVote;
    public String scVote;

    public NationOverviewCardData() { super(); }
}

Add last seen parameter to nation overview card DTO


package jp.ac.nii.prl.mape.autoscaling.model;

import jp.ac.nii.prl.mape.autoscaling.model.dto.InstanceDTO;

public class InstanceFactory {

	public static Instance createInstance(InstanceDTO dto, Deployment deployment) {

		Instance instance = new Instance();

		instance.setInstID(dto.getInstID());
		instance.setDeployment(deployment);

		return instance;
	}

	public static Instance createInstance(InstanceDTO dto,
			Deployment deployment,
			InstanceType instanceType) {

		Instance instance = createInstance(dto, deployment);
		instance.setInstanceType(instanceType);

		return instance;
	}

	public static InstanceDTO createDTO(Instance instance) {

		InstanceDTO dto = new InstanceDTO();

		dto.setInstID(instance.getInstID());
		dto.setInstLoad(instance.getInstLoad());
		dto.setInstType(instance.getInstanceType().getTypeID());

		return dto;
	}

}

package jp.ac.nii.prl.mape.autoscaling.model;

import jp.ac.nii.prl.mape.autoscaling.model.dto.InstanceDTO;

public class InstanceFactory {

	public static Instance createInstance(InstanceDTO dto, Deployment deployment) {

		Instance instance = new Instance();

		instance.setInstID(dto.getInstID());
		instance.setDeployment(deployment);
		instance.setInstLoad(dto.getInstLoad());

		return instance;
	}

	public static Instance createInstance(InstanceDTO dto,
			Deployment deployment,
			InstanceType instanceType) {

		Instance instance = createInstance(dto, deployment);
		instance.setInstanceType(instanceType);

		return instance;
	}

	public static InstanceDTO createDTO(Instance instance) {

		InstanceDTO dto = new InstanceDTO();

		dto.setInstID(instance.getInstID());
		dto.setInstLoad(instance.getInstLoad());
		dto.setInstType(instance.getInstanceType().getTypeID());

		return dto;
	}

}

Set instance load in instance creation


package com.yammer.dropwizard.json;

import ch.qos.logback.classic.Level;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.*;
import org.codehaus.jackson.map.annotate.JsonCachable;
import org.codehaus.jackson.type.JavaType;

import java.io.IOException;

class LogbackModule extends Module {
    @JsonCachable
    private static class LevelDeserializer extends JsonDeserializer<Level> {
        @Override
        public Level deserialize(JsonParser jp,
                                 DeserializationContext ctxt) throws IOException {

            final String text = jp.getText();

            if ("false".equalsIgnoreCase(text)) {
                return Level.OFF;
            }

            if ("true".equalsIgnoreCase(text)) {
                return Level.ALL;
            }

            return Level.toLevel(text, Level.INFO);
        }
    }

    private static class LogbackDeserializers extends Deserializers.Base {
        @Override
        public JsonDeserializer<?> findBeanDeserializer(JavaType type,
                                                        DeserializationConfig config,
                                                        DeserializerProvider provider,
                                                        BeanDescription beanDesc,
                                                        BeanProperty property) throws JsonMappingException {
            if (Level.class.isAssignableFrom(type.getRawClass())) {
                return new LevelDeserializer();
            }

            return super.findBeanDeserializer(type, config, provider, beanDesc, property);
        }
    }

    @Override
    public String getModuleName() {
        return "log4j";
    }

    @Override
    public Version version() {
        return Version.unknownVersion();
    }

    @Override
    public void setupModule(SetupContext context) {
        context.addDeserializers(new LogbackDeserializers());
    }
}

package com.yammer.dropwizard.json;

import ch.qos.logback.classic.Level;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.*;
import org.codehaus.jackson.map.annotate.JsonCachable;
import org.codehaus.jackson.type.JavaType;

import java.io.IOException;

class LogbackModule extends Module {
    @JsonCachable
    private static class LevelDeserializer extends JsonDeserializer<Level> {
        @Override
        public Level deserialize(JsonParser jp,
                                 DeserializationContext ctxt) throws IOException {

            final String text = jp.getText();

            if ("false".equalsIgnoreCase(text)) {
                return Level.OFF;
            }

            if ("true".equalsIgnoreCase(text)) {
                return Level.ALL;
            }

            return Level.toLevel(text, Level.INFO);
        }
    }

    private static class LogbackDeserializers extends Deserializers.Base {
        @Override
        public JsonDeserializer<?> findBeanDeserializer(JavaType type,
                                                        DeserializationConfig config,
                                                        DeserializerProvider provider,
                                                        BeanDescription beanDesc,
                                                        BeanProperty property) throws JsonMappingException {
            if (Level.class.isAssignableFrom(type.getRawClass())) {
                return new LevelDeserializer();
            }

            return super.findBeanDeserializer(type, config, provider, beanDesc, property);
        }
    }

    @Override
    public String getModuleName() {
        return "LogbackModule";
    }

    @Override
    public Version version() {
        return Version.unknownVersion();
    }

    @Override
    public void setupModule(SetupContext context) {
        context.addDeserializers(new LogbackDeserializers());
    }
}

Replace log4j reference with Logback.


package io.bisq.gui.components;

import de.jensd.fx.fontawesome.AwesomeDude;
import de.jensd.fx.fontawesome.AwesomeIcon;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;

public class HyperlinkWithIcon extends Hyperlink {

    public HyperlinkWithIcon(String text) {
        this(text, AwesomeIcon.INFO_SIGN);
    }

    public HyperlinkWithIcon(String text, AwesomeIcon awesomeIcon) {

        super(text);

        Label icon = new Label();
        AwesomeDude.setIcon(icon, awesomeIcon);
        icon.setMinWidth(20);
        icon.setOpacity(0.7);
        icon.getStyleClass().add("hyperlink");

        setGraphic(icon);
        setContentDisplay(ContentDisplay.RIGHT);
    }
}

package io.bisq.gui.components;

import de.jensd.fx.fontawesome.AwesomeDude;
import de.jensd.fx.fontawesome.AwesomeIcon;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;

public class HyperlinkWithIcon extends Hyperlink {

    public HyperlinkWithIcon(String text) {
        this(text, AwesomeIcon.INFO_SIGN);
    }

    public HyperlinkWithIcon(String text, AwesomeIcon awesomeIcon) {

        super(text);

        Label icon = new Label();
        AwesomeDude.setIcon(icon, awesomeIcon);
        icon.setMinWidth(20);
        icon.setOpacity(0.7);
        icon.getStyleClass().add("hyperlink");

        setGraphic(icon);
        setContentDisplay(ContentDisplay.RIGHT);

        tooltipProperty().addListener((observable, oldValue, newValue) -> newValue.setStyle("-fx-text-fill: -bs-black"));
    }
}

Fix hierarchical/inherit issue with styles for Tooltip


/*
 * ReturnExporter.java
 *
 */

package de.uni_stuttgart.vis.vowl.owl2vowl.export.types;

/**
 * Simple exporter that saves the
 */
public class BackupExporter implements Exporter {
	@Override
	public void write(String text) throws Exception {
		// TODO
	}
}

/*
 * ReturnExporter.java
 *
 */

package de.uni_stuttgart.vis.vowl.owl2vowl.export.types;

/**
 * Simple exporter that saves the given text.
 */
public class BackupExporter implements Exporter {
	protected String convertedJson;

	public String getConvertedJson() {
		return convertedJson;
	}

	@Override
	public void write(String text) throws Exception {
		convertedJson = text;
	}
}

Add new exporter with method for direct integration in other projects.


package natlab;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;

import beaver.Parser;

import natlab.ast.Root;

public class Interpreter {
	private Interpreter() {}

	public static void main(String[] args) throws IOException {
		System.out.println("Welcome to the Natlab Interpreter!");
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		while(true) {
			System.out.print("> ");
			System.out.flush();

			String line = in.readLine();
			if(line == null) {
				break;
			}

			try {
				NatlabScanner scanner = new NatlabScanner(new StringReader(line));
				NatlabParser parser = new NatlabParser();
				Root original = (Root) parser.parse(scanner);

				if(parser.hasError()) {
					System.out.println("**ERROR**");
					for(String error : parser.getErrors()) {
						System.out.println(error);
					}
				} else {
					System.out.println(original.getStructureString());
				}
			} catch(Parser.Exception e) {
				System.out.println("**ERROR**");
				System.out.println(e.getMessage());
			}
		}
		System.out.println("Goodbye!");
	}
}

package natlab;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;

import natlab.ast.Root;
import beaver.Parser;

public class Interpreter {
	private Interpreter() {}

	public static void main(String[] args) throws IOException {
		System.out.println("Welcome to the Natlab Interpreter!");
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		while(true) {
			System.out.print("> ");
			System.out.flush();

			String line = in.readLine();
			if(line == null) {
				break;
			}

			NatlabParser parser = new NatlabParser();
			try {
				NatlabScanner scanner = new NatlabScanner(new StringReader(line));
				Root original = (Root) parser.parse(scanner);
				if(parser.hasError()) {
					System.out.println("**ERROR**");
					for(String error : parser.getErrors()) {
						System.out.println(error);
					}
				} else {
					System.out.println(original.getStructureString());
				}
			} catch(Parser.Exception e) {
				System.out.println("**ERROR**");
				System.out.println(e.getMessage());
				for(String error : parser.getErrors()) {
					System.out.println(error);
				}
			}
		}
		System.out.println("Goodbye!");
	}
}

Print error list in exception case.


package org.purl.wf4ever.robundle;

import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;

import org.purl.wf4ever.robundle.fs.BundleFileSystem;

public class Bundle implements AutoCloseable {

    private boolean deleteOnClose;
    private final Path root;

    public Bundle(Path root, boolean deleteOnClose) {
        this.root = root;
        this.setDeleteOnClose(deleteOnClose);
    }

    @Override
    public void close() throws IOException {
        close(isDeleteOnClose());
    }

    protected void close(boolean deleteOnClose) throws IOException {
        getFileSystem().close();
        if (deleteOnClose) {
            Files.deleteIfExists(getSource());
        }
    }

    public FileSystem getFileSystem() {
        return getRoot().getFileSystem();
    }

    public Path getRoot() {
        return root;
    }

    public Path getSource() {
        BundleFileSystem fs = (BundleFileSystem) getFileSystem();
        return fs.getSource();
    }

    public boolean isDeleteOnClose() {
        return deleteOnClose;
    }

    public void setDeleteOnClose(boolean deleteOnClose) {
        this.deleteOnClose = deleteOnClose;
    }

}

package org.purl.wf4ever.robundle;

import java.io.Closeable;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;

import org.purl.wf4ever.robundle.fs.BundleFileSystem;

public class Bundle implements Closeable {

    private boolean deleteOnClose;
    private final Path root;

    public Bundle(Path root, boolean deleteOnClose) {
        this.root = root;
        this.setDeleteOnClose(deleteOnClose);
    }

    @Override
    public void close() throws IOException {
        close(isDeleteOnClose());
    }

    protected void close(boolean deleteOnClose) throws IOException {
        if (! getFileSystem().isOpen()) {
            return;
        }
        getFileSystem().close();
        if (deleteOnClose) {
            Files.deleteIfExists(getSource());
        }
    }

    public FileSystem getFileSystem() {
        return getRoot().getFileSystem();
    }

    public Path getRoot() {
        return root;
    }

    public Path getSource() {
        BundleFileSystem fs = (BundleFileSystem) getFileSystem();
        return fs.getSource();
    }

    public boolean isDeleteOnClose() {
        return deleteOnClose;
    }

    public void setDeleteOnClose(boolean deleteOnClose) {
        this.deleteOnClose = deleteOnClose;
    }

}

Make close() idempotent and implement Closable rather than AutoClosable


package agoodfriendalwayspayshisdebts.web.actions.expense;

import agoodfriendalwayspayshisdebts.command.expense.DeleteExpenseCommand;
import com.vter.command.CommandBus;
import com.vter.infrastructure.bus.ExecutionResult;
import com.vter.web.actions.BaseAction;
import net.codestory.http.annotations.Delete;
import net.codestory.http.annotations.Resource;
import net.codestory.http.constants.HttpStatus;
import net.codestory.http.payload.Payload;

import javax.inject.Inject;
import java.util.UUID;

@Resource
public class DeleteExpense extends BaseAction {

  @Inject
  public DeleteExpense(CommandBus commandBus) {
    this.commandBus = commandBus;
  }

  @Delete("/events/:stringifiedEventUuid/expenses/:stringifiedExpenseUuid")
  public Payload delete(String stringifiedEventId, String stringifiedExpenseUuid) {
    final DeleteExpenseCommand command = new DeleteExpenseCommand();
    command.eventId = UUID.fromString(stringifiedEventId);
    command.expenseId = UUID.fromString(stringifiedExpenseUuid);
    final ExecutionResult<Void> result = commandBus.sendAndWaitResponse(command);
    return getDataAsPayloadOrFail(result, HttpStatus.NO_CONTENT);
  }

  private final CommandBus commandBus;
}

package agoodfriendalwayspayshisdebts.web.actions.expense;

import agoodfriendalwayspayshisdebts.command.expense.DeleteExpenseCommand;
import com.vter.command.CommandBus;
import com.vter.infrastructure.bus.ExecutionResult;
import com.vter.web.actions.BaseAction;
import net.codestory.http.annotations.Put;
import net.codestory.http.annotations.Resource;
import net.codestory.http.constants.HttpStatus;
import net.codestory.http.payload.Payload;

import javax.inject.Inject;
import java.util.UUID;

@Resource
public class DeleteExpense extends BaseAction {

  @Inject
  public DeleteExpense(CommandBus commandBus) {
    this.commandBus = commandBus;
  }

  @Put("/events/:stringifiedEventUuid/expenses/:stringifiedExpenseUuid")
  public Payload delete(String stringifiedEventId, String stringifiedExpenseUuid) {
    final DeleteExpenseCommand command = new DeleteExpenseCommand();
    command.eventId = UUID.fromString(stringifiedEventId);
    command.expenseId = UUID.fromString(stringifiedExpenseUuid);
    final ExecutionResult<Void> result = commandBus.sendAndWaitResponse(command);
    return getDataAsPayloadOrFail(result, HttpStatus.NO_CONTENT);
  }

  private final CommandBus commandBus;
}

Set delete expense action as HTTP Put


package org.apollo.net.codec.game;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.util.List;

import org.apollo.game.event.Event;
import org.apollo.net.release.EventDecoder;
import org.apollo.net.release.Release;

/**
 * A {@link OneToOneDecoder} that decodes {@link GamePacket}s into {@link Event}s.
 *
 * @author Graham
 */
public final class GameEventDecoder extends MessageToMessageDecoder<GamePacket> {

	/**
	 * The current release.
	 */
	private final Release release;

	/**
	 * Creates the game event decoder with the specified release.
	 *
	 * @param release The release.
	 */
	public GameEventDecoder(Release release) {
		this.release = release;
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, GamePacket msg, List<Object> out) {
		GamePacket packet = (GamePacket) msg;
		EventDecoder<?> decoder = release.getEventDecoder(packet.getOpcode());
		if (decoder != null) {
			out.add(decoder.decode(packet));
		} else {
			System.out.println("Unidentified packet received - opcode: " + packet.getOpcode() + ".");
		}
	}

}

package org.apollo.net.codec.game;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.util.List;

import org.apollo.game.event.Event;
import org.apollo.net.release.EventDecoder;
import org.apollo.net.release.Release;

/**
 * A {@link OneToOneDecoder} that decodes {@link GamePacket}s into {@link Event}s.
 *
 * @author Graham
 */
public final class GameEventDecoder extends MessageToMessageDecoder<GamePacket> {

	/**
	 * The current release.
	 */
	private final Release release;

	/**
	 * Creates the game event decoder with the specified release.
	 *
	 * @param release The release.
	 */
	public GameEventDecoder(Release release) {
		this.release = release;
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, GamePacket packet, List<Object> out) {
		EventDecoder<?> decoder = release.getEventDecoder(packet.getOpcode());
		if (decoder != null) {
			out.add(decoder.decode(packet));
		} else {
			System.out.println("Unidentified packet received - opcode: " + packet.getOpcode() + ".");
		}
	}

}

Remove unnecessary cast left over from netty 4 conversion.


package com.miguelgaeta.media_picker;

import android.os.Environment;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@SuppressWarnings("UnusedDeclaration")
public class MediaPickerFile {

    /**
     * Create a file in the devices external storage.
     *
     * @param directory Target directory.
     * @param name Target file name.
     * @param suffix Target file suffix.
     *
     * @return Created file.
     *
     * @throws IOException
     */
    public static File create(final String directory, final String name, final String suffix) throws IOException {

        final File dir = new File(Environment.getExternalStorageDirectory() + File.separator + directory);

        if (!dir.exists()) {

            boolean result = dir.mkdirs();

            if (!result) {

                throw new IOException("Unable to create directory.");
            }
        }

        return File.createTempFile(name, suffix, dir);
    }

    /**
     * @see #create(String, String, String)
     */
    public static File create(final String directory, final String name) throws IOException {

        return create(directory, name, null);
    }

    /**
     * @see #create(String, String)
     */
    public static File create(final String directory) throws IOException {

        return create(directory, UUID.randomUUID().toString());
    }

    /**
     * @see #create(String)
     */
    public static File create() throws IOException {

        return create("media_picker");
    }
}

package com.miguelgaeta.media_picker;

import android.os.Environment;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@SuppressWarnings("UnusedDeclaration")
public class MediaPickerFile {

    /**
     * Create a file in the devices external storage.
     *
     * @param directory Target directory.
     * @param name Target file name.
     * @param suffix Target file suffix.
     *
     * @return Created file.
     *
     * @throws IOException
     */
    public static File create(final String directory, final String name, final String suffix) throws IOException {

        final File dir = new File(Environment.getExternalStorageDirectory() + File.separator + directory);

        if (!dir.exists()) {

            boolean result = dir.mkdirs();

            if (!result) {

                throw new IOException("Unable to create directory.");
            }
        }

        final File file = File.createTempFile(name, suffix, dir);

        if (!file.exists()) {

            throw new IOException("Unable to create temporary file, does not exist.");
        }

        return File.createTempFile(name, suffix, dir);
    }

    /**
     * @see #create(String, String, String)
     */
    public static File create(final String directory, final String name) throws IOException {

        return create(directory, name, null);
    }

    /**
     * @see #create(String, String)
     */
    public static File create(final String directory) throws IOException {

        return create(directory, UUID.randomUUID().toString());
    }

    /**
     * @see #create(String)
     */
    public static File create() throws IOException {

        return create("media_picker");
    }
}

Check to make sure created file actually exists.


package peergos.server.net;

import com.sun.net.httpserver.*;

import java.io.*;

public class RedirectHandler implements HttpHandler
{
    private final String target;

    public RedirectHandler(String target) {
        this.target = target;
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        exchange.getResponseHeaders().add("Location", target);
        exchange.sendResponseHeaders(301, 0);
        exchange.close();
    }
}

package peergos.server.net;

import com.sun.net.httpserver.*;

import java.io.*;

public class RedirectHandler implements HttpHandler
{
    private final String target;

    public RedirectHandler(String target) {
        this.target = target;
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        exchange.getResponseHeaders().add("Location", target);
        exchange.sendResponseHeaders(302, 0);
        exchange.close();
    }
}

Make redirect to https do the same thing as google.com


/*
  Copyright 2016, Google, Inc.

  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.example.translate;

// [START translate_quickstart]
// Imports the Google Cloud client library
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translate.TranslateOption;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Translate translate = TranslateOptions.builder().apiKey("YOUR_API_KEY").build().service();

    // The text to translate
    String text = "Hello, world!";

    // Translates some text into Russian
    Translation translation = translate.translate(
      text,
      TranslateOption.sourceLanguage("en"),
      TranslateOption.targetLanguage("ru")
    );

    System.out.printf("Text: %s%n", text);
    System.out.printf("Translation: %s%n", translation.translatedText());
  }
}
// [END translate_quickstart]

/*
  Copyright 2016, Google, Inc.

  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.example.translate;

// [START translate_quickstart]
// Imports the Google Cloud client library
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translate.TranslateOption;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Translate translate = TranslateOptions.builder().apiKey("YOUR_API_KEY").build().service();

    // The text to translate
    String text = "Hello, world!";

    // Translates some text into Russian
    Translation translation =
        translate.translate(
            text,
            TranslateOption.sourceLanguage("en"),
            TranslateOption.targetLanguage("ru"));

    System.out.printf("Text: %s%n", text);
    System.out.printf("Translation: %s%n", translation.translatedText());
  }
}
// [END translate_quickstart]

Add quickstarts to root module.


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

import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;

public class KotlinPerspectiveFactory implements IPerspectiveFactory {

    @Override
    public void createInitialLayout(IPageLayout layout) {

    }

}

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

import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;

public class KotlinPerspectiveFactory implements IPerspectiveFactory {

    @Override
    public void createInitialLayout(IPageLayout layout) {
        layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET);
        layout.addActionSet(JavaUI.ID_ACTION_SET);
    }
}

Set action set's for Kotlin perspective: open type, launch configurations