package com.dtolabs.rundeck.core.dispatcher;

/**
 * Created by greg on 5/26/16.
 */
public interface MutableDataContext extends DataContext, Mergable<DataContext> {
    void merge(DataContext item);
}

package com.dtolabs.rundeck.core.dispatcher;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by greg on 5/26/16.
 */
public interface MutableDataContext extends DataContext, Mergable<DataContext> {
    void merge(DataContext item);

    /**
     * Put value
     *
     * @param group
     * @param key
     * @param value
     *
     * @return
     */
    public default String put(String group, String key, String value) {
        return group(group).put(key, value);
    }

    default Map<String, String> group(final String group) {
        if (null == get(group)) {
            put(group, new HashMap<>());
        }
        return get(group);
    }
}

Add utility methods for interface

Add utility methods for interface


package org.qtrp.nadir.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;

import org.qtrp.nadir.R;

public class RollActivity extends AppCompatActivity {

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

        Intent intent = getIntent();
        Integer roll_id = intent.getIntExtra("roll_id", -1);

        Log.i("Roll id: ", roll_id.toString());
    }

    @Override
    public void onBackPressed(){
        super.onBackPressed();
        finish();
    }
}

package org.qtrp.nadir.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;

import org.qtrp.nadir.R;

public class RollActivity extends AppCompatActivity {

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

        Intent intent = getIntent();
        Long roll_id = intent.getLongExtra("roll_id", -1);

        Log.i("Roll id: ", roll_id.toString());
    }

    @Override
    public void onBackPressed(){
        super.onBackPressed();
        finish();
    }
}

Change int to long to pass id correctly

Change int to long to pass id correctly


/*
 * algorithms  Copyright (C) 2015 Ratchet Robotics
 *     This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
 *     This is free software, and you are welcome to redistribute it
 *     under certain conditions; type `show c' for details.
 */

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

import org.ratchetrobotics.algorithms.util.CartesianCoordinate;

public class CartesianCoordinateTest {
    @Test
    public void storesXCoordinates() {
        CartesianCoordinate coordinate = new CartesianCoordinate(1,3);
        assertEquals("getX should return 1 when x in the constructor was 1", 1, coordinate.getX(), 0.0/*ε, a small fudge for doubles*/);
    }
}

/*
 * algorithms  Copyright (C) 2015 Ratchet Robotics
 *     This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
 *     This is free software, and you are welcome to redistribute it
 *     under certain conditions; type `show c' for details.
 */

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

import org.ratchetrobotics.algorithms.util.CartesianCoordinate;

public class CartesianCoordinateTest {
    @Test
    public void storesXCoordinates() {
        CartesianCoordinate coordinate = new CartesianCoordinate(1,3);
        assertEquals("getX should return 1 when x in the constructor was 1", 1, coordinate.getX(), 0.0/*ε, a small fudge for doubles*/);
    }

    @Test
    public void storesYCoordinates() {
        CartesianCoordinate coordinate = new CartesianCoordinate(1,3);
        assertEquals("gety should return 2 when y in the constructor was 2", 2, coordinate.getY(), 0.0/*ε, a small fudge for doubles*/);
    }
}

Add second test for Y

Add second test for Y


package uk.ac.ic.wlgitbridge.snapshot.base;

import com.google.gson.JsonElement;
import uk.ac.ic.wlgitbridge.git.exception.SnapshotAPIException;

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

public class MissingRepositoryException extends SnapshotAPIException {

    public static final String GENERIC_REASON =
        "This Overleaf project currently has no git access.\n" +
        "\n" +
        "If this problem persists, please contact us.";

    public static final String EXPORTED_TO_V2 =
        "This Overleaf project has been moved to Overleaf v2, and git access is temporarily unsupported.\n" +
        "\n" +
        "See https://www.overleaf.com/help/342 for more information.";

    private String message = "";

    public MissingRepositoryException() {
    }

    public MissingRepositoryException(String message) {
        this.message = message;
    }

    @Override
    public void fromJSON(JsonElement json) {}

    @Override
    public String getMessage() {
        return message;
    }

    @Override
    public List<String> getDescriptionLines() {
        return Arrays.asList(getMessage());
    }

}

package uk.ac.ic.wlgitbridge.snapshot.base;

import com.google.gson.JsonElement;
import uk.ac.ic.wlgitbridge.git.exception.SnapshotAPIException;

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

public class MissingRepositoryException extends SnapshotAPIException {

    public static final List<String> GENERIC_REASON = Arrays.asList(
        "This Overleaf project currently has no git access.",
        "",
        "If this problem persists, please contact us."
    );

    public static final List<String> EXPORTED_TO_V2 = Arrays.asList(
        "This Overleaf project has been moved to Overleaf v2, and git access is temporarily unsupported.",
        "",
        "See https://www.overleaf.com/help/342 for more information."
    );

    private List<String> descriptionLines;

    public MissingRepositoryException() {
        descriptionLines = new ArrayList<String>();
    }

    public MissingRepositoryException(String message) {
        this.descriptionLines = Arrays.asList(message);
    }

    public MissingRepositoryException(List<String> descriptionLines) {
        this.descriptionLines = descriptionLines;
    }

    @Override
    public void fromJSON(JsonElement json) {}

    @Override
    public String getMessage() {
        return String.join("\n", this.descriptionLines);
    }

    @Override
    public List<String> getDescriptionLines() {
        return this.descriptionLines;
    }

}

Use a List<String> rather than hard-coding newlines


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

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

public class CMModeOverlay extends JavaScriptObject {

    protected CMModeOverlay() {
    }

    public final native String getName() /*-{
        return this.name;
    }-*/;
}

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

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

public class CMModeOverlay extends JavaScriptObject {

    protected CMModeOverlay() {
    }

}

Remove (nonexistant) method getname on mode objects


/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2019 Axelor (<http://axelor.com>).
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.axelor.apps.stock.translation;

public interface ITranslation {

  public static final String STOCK_APP_NAME = /*$$(*/ "value:Stock"; /*)*/

  public static final String ABC_ANALYSIS_STOCK_LOCATION = /*$$(*/
      "AbcAnalysis.stockLocation"; /*)*/

  public static final String PICKING_STOCK_MOVE_NOTE = /*$$(*/
      "PickingStockMove.note"; /*)*/
}

Apply spotless java google code format

Apply spotless java google code format


package com.github.sormuras.bach.project;

import java.util.List;
import java.util.Map;

/** A nominal space for modules. */
public interface Space {

  /**
   * Returns the list of module names in this space.
   *
   * @return the list of module names
   */
  List<String> modules();

  /**
   * Returns the list of module source paths.
   *
   * @return the list of module source paths
   */
  List<String> moduleSourcePaths();

  /**
   * Returns the possibly empty name of this space.
   *
   * @return an empty string for the main space, else a non-empty name
   * @see #title()
   */
  String name();

  /**
   * Returns the additional arguments to be passed on a per-tool basis.
   *
   * @return the additional arguments to be passed on a per-tool basis
   */
  Map<String, List<String>> tweaks();

  /**
   * Returns the title of this space.
   *
   * @return The string {@code "main"} for the main space, else the non-empty name
   * @see #name()
   */
  default String title() {
    return name().isEmpty() ? "main" : name();
  }

  /** @return {@code true} if at least one module name is present in this space */
  default boolean isPresent() {
    return modules().size() >= 1;
  }
}

package com.github.sormuras.bach.project;

import java.util.List;
import java.util.Map;

/** A nominal space for modules. */
public /*sealed*/ interface Space /*permits MainSpace, TestSpace, PreviewSpace*/ {

  /**
   * Returns the list of module names in this space.
   *
   * @return the list of module names
   */
  List<String> modules();

  /**
   * Returns the list of module source paths.
   *
   * @return the list of module source paths
   */
  List<String> moduleSourcePaths();

  /**
   * Returns the possibly empty name of this space.
   *
   * @return an empty string for the main space, else a non-empty name
   * @see #title()
   */
  String name();

  /**
   * Returns the additional arguments to be passed on a per-tool basis.
   *
   * @return the additional arguments to be passed on a per-tool basis
   */
  Map<String, List<String>> tweaks();

  /**
   * Returns the title of this space.
   *
   * @return The string {@code "main"} for the main space, else the non-empty name
   * @see #name()
   */
  default String title() {
    return name().isEmpty() ? "main" : name();
  }

  /** @return {@code true} if at least one module name is present in this space */
  default boolean isPresent() {
    return modules().size() >= 1;
  }
}

Add commented-out sealed and permits clause


/*
 * FindBugs - Find Bugs in Java programs
 * Copyright (C) 2006, University of Maryland
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston MA 02111-1307, USA
 */

package edu.umd.cs.findbugs.gui2;

import java.io.File;

public final class FindBugsAnalysisFileFilter extends FindBugsFileFilter {

    public static final FindBugsAnalysisFileFilter INSTANCE = new FindBugsAnalysisFileFilter();

    @Override
    public boolean accept(File arg0) {
        boolean accept = arg0.getName().endsWith(".xml") || arg0.getName().endsWith(".xml.gz");
        return accept;
    }

    @Override
    public String getDescription() {
        return "FindBugs analysis results (.xml)";
    }

    @Override
    SaveType getSaveType() {
        return SaveType.XML_ANALYSIS;
    }
}

/*
 * FindBugs - Find Bugs in Java programs
 * Copyright (C) 2006, University of Maryland
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston MA 02111-1307, USA
 */

package edu.umd.cs.findbugs.gui2;

import java.io.File;

public final class FindBugsAnalysisFileFilter extends FindBugsFileFilter {

    public static final FindBugsAnalysisFileFilter INSTANCE = new FindBugsAnalysisFileFilter();

    @Override
    public boolean accept(File arg0) {
        return arg0.getName().endsWith(".xml") || arg0.getName().endsWith(".xml.gz") || arg0.isDirectory();
    }

    @Override
    public String getDescription() {
        return "FindBugs analysis results (.xml, *.xml.gz)";
    }

    @Override
    SaveType getSaveType() {
        return SaveType.XML_ANALYSIS;
    }
}

Fix bug where folders don't show up in "save as" dialog, preventing navigation into subfolders

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@13067 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


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

import com.github.danzx.zekke.message.MessageSource;

/**
 * @author Daniel Pedraza-Arcega
 */
public class MessageSourceFactory {

    public static MessageSource defaultSource() {
        return InstanceHolder.INSTANCE;
    }

    private static class InstanceHolder {
        private static final String MESSAGES_BASENAME = "com.github.danzx.zekke.Messages";
        private static final MessageSource INSTANCE = new DefaultMessageDecorator(new ResourceBundleMessageSource(MESSAGES_BASENAME));
    }
}

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

import com.github.danzx.zekke.message.MessageSource;

/**
 * Creates message sources.
 *
 * @author Daniel Pedraza-Arcega
 */
public class MessageSourceFactory {

    private MessageSourceFactory() {
        throw new AssertionError();
    }

    /** @return the default message source for this application. */
    public static MessageSource defaultSource() {
        return InstanceHolder.INSTANCE;
    }

    private static class InstanceHolder {
        private static final String MESSAGES_BASENAME = "com.github.danzx.zekke.Messages";
        private static final MessageSource INSTANCE = new DefaultMessageDecorator(new ResourceBundleMessageSource(MESSAGES_BASENAME));

        private InstanceHolder() {
            throw new AssertionError();
        }
    }
}

Add missing javadoc and block constructors


package org.stevewinfield.suja.idk.storage;

public class HSQLDBStorageDriver implements StorageDriver {
    @Override
    public String getDriverName() {
        return "hsqldb";
    }

    @Override
    public String getDriverClass() {
        return "org.hsqldb.jdbc.JDBCDriver";
    }

    @Override
    public String getConnectionString() {
        return "jdbc:hsqldb:mem:hallo";
    }

    @Override
    public String getUsername() {
        return "sa";
    }

    @Override
    public String getPassword() {
        return "";
    }
}

package org.stevewinfield.suja.idk.storage;

import org.stevewinfield.suja.idk.Bootloader;

public class HSQLDBStorageDriver implements StorageDriver {
    @Override
    public String getDriverName() {
        return "hsqldb";
    }

    @Override
    public String getDriverClass() {
        return "org.hsqldb.jdbc.JDBCDriver";
    }

    @Override
    public String getConnectionString() {
        return "jdbc:hsqldb:file:" + Bootloader.getSettings().getProperty("idk.hsqldb.path");
    }

    @Override
    public String getUsername() {
        return "sa";
    }

    @Override
    public String getPassword() {
        return "";
    }
}

Allow HSQLDB to specify file path

Allow HSQLDB to specify file path


/*
 * Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
 */

package org.jsimpledb.cli.cmd;

import java.io.File;
import java.util.EnumSet;
import java.util.Map;

import org.jsimpledb.SessionMode;
import org.jsimpledb.cli.CliSession;
import org.jsimpledb.parse.Parser;
import org.jsimpledb.util.ParseContext;

public class SetHistoryFileCommand extends AbstractCommand {

    public SetHistoryFileCommand() {
        super("set-history-file file.txt:file");
    }

    @Override
    public String getHelpSummary() {
        return "Configures the history file used for command line tab-completion.";
    }

    @Override
    protected Parser<?> getParser(String typeName) {
        return "file".equals(typeName) ? new InputFileParser() : super.getParser(typeName);
    }

    @Override
    public EnumSet<SessionMode> getSessionModes() {
        return EnumSet.allOf(SessionMode.class);
    }

    @Override
    public CliSession.Action getAction(CliSession session, ParseContext ctx, boolean complete, Map<String, Object> params) {
        final File file = (File)params.get("file.txt");
        return new CliSession.TransactionalAction() {
            @Override
            public void run(CliSession session) throws Exception {
                session.getConsole().setHistoryFile(file);
                session.getWriter().println("Updated history file to " + file);
            }
        };
    }
}

/*
 * Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
 */

package org.jsimpledb.cli.cmd;

import java.io.File;
import java.util.EnumSet;
import java.util.Map;

import org.jsimpledb.SessionMode;
import org.jsimpledb.cli.CliSession;
import org.jsimpledb.parse.Parser;
import org.jsimpledb.util.ParseContext;

public class SetHistoryFileCommand extends AbstractCommand {

    public SetHistoryFileCommand() {
        super("set-history-file file.txt:file");
    }

    @Override
    public String getHelpSummary() {
        return "Configures the history file used for command line tab-completion.";
    }

    @Override
    protected Parser<?> getParser(String typeName) {
        return "file".equals(typeName) ? new OutputFileParser() : super.getParser(typeName);
    }

    @Override
    public EnumSet<SessionMode> getSessionModes() {
        return EnumSet.allOf(SessionMode.class);
    }

    @Override
    public CliSession.Action getAction(CliSession session, ParseContext ctx, boolean complete, Map<String, Object> params) {
        final File file = (File)params.get("file.txt");
        return new CliSession.TransactionalAction() {
            @Override
            public void run(CliSession session) throws Exception {
                session.getConsole().setHistoryFile(file);
                session.getWriter().println("Updated history file to " + file);
            }
        };
    }
}

Fix history file parser to allow nonexistent file.


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

package org.springframework.core.task;

/**
 * A no-op Runnable implementation.
 *
 * @author Rick Evans
 */
public class NoOpRunnable implements Runnable {

	@Override
	public void run() {
		// explicit no-op
		System.out.println("Running");
	}

}

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

package org.springframework.core.task;

/**
 * A no-op {@link Runnable} implementation.
 *
 * @author Rick Evans
 */
public class NoOpRunnable implements Runnable {

	@Override
	public void run() {
		// explicit no-op
	}

}

Stop to writing to STD_OUT in tests

Stop to writing to STD_OUT in tests


package io.collap.bryg.compiler.ast.expression;

import io.collap.bryg.compiler.ast.AccessMode;
import io.collap.bryg.compiler.parser.BrygMethodVisitor;
import io.collap.bryg.compiler.parser.StandardVisitor;
import io.collap.bryg.compiler.expression.Variable;

import static org.objectweb.asm.Opcodes.*;

public class VariableExpression extends Expression {

    private Variable variable;
    private AccessMode mode;

    public VariableExpression (StandardVisitor visitor, Variable variable, AccessMode mode, int line) {
        super (visitor);
        this.mode = mode;
        setLine (line);

        this.variable = variable;
        setType (variable.getType ());
    }

    @Override
    public void compile () {
        BrygMethodVisitor method = visitor.getMethod ();
        if (mode == AccessMode.get) {
            method.visitVarInsn (type.getAsmType ().getOpcode (ILOAD), variable.getId ());
            // -> T
        }else {
            method.visitVarInsn (type.getAsmType ().getOpcode (ISTORE), variable.getId ());
            // T ->
        }
    }

    public Variable getVariable () {
        return variable;
    }

    public AccessMode getMode () {
        return mode;
    }

}

package io.collap.bryg.compiler.ast.expression;

import io.collap.bryg.compiler.ast.AccessMode;
import io.collap.bryg.compiler.parser.BrygMethodVisitor;
import io.collap.bryg.compiler.parser.StandardVisitor;
import io.collap.bryg.compiler.expression.Variable;

import static org.objectweb.asm.Opcodes.*;

public class VariableExpression extends Expression {

    private Variable variable;
    private AccessMode mode;

    public VariableExpression (StandardVisitor visitor, Variable variable, AccessMode mode, int line) {
        super (visitor);
        this.mode = mode;
        setLine (line);

        this.variable = variable;
        setType (variable.getType ());
    }

    @Override
    public void compile () {
        BrygMethodVisitor method = visitor.getMethod ();
        if (mode == AccessMode.get) {
            method.visitVarInsn (type.getAsmType ().getOpcode (ILOAD), variable.getId ());
            // -> T
        }else { /* AccessMode.set */
            method.visitVarInsn (type.getAsmType ().getOpcode (ISTORE), variable.getId ());
            // T ->
        }
    }

    public Variable getVariable () {
        return variable;
    }

    public AccessMode getMode () {
        return mode;
    }

}

Clarify AccessMode alternative in else.

Clarify AccessMode alternative in else.


/*
 * Copyright 2020 ThoughtWorks, 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.thoughtworks.gocd;

import java.util.Arrays;
import java.util.TreeSet;

public class AssertJava {
    private static TreeSet<JavaVersion> SUPPORTED_VERSIONS = new TreeSet<>(Arrays.asList(
            JavaVersion.VERSION_11,
            JavaVersion.VERSION_12,
            JavaVersion.VERSION_13
    ));

    public static void assertVMVersion() {
        checkSupported(JavaVersion.current());
    }

    private static void checkSupported(JavaVersion currentJavaVersion) {
        if (!SUPPORTED_VERSIONS.contains(currentJavaVersion)) {
            System.err.println("Running GoCD requires Java version >= " + SUPPORTED_VERSIONS.first().name() +
                    " and <= " + SUPPORTED_VERSIONS.last() +
                    ". You are currently running with Java version " + currentJavaVersion + ". GoCD will now exit!");
            System.exit(1);
        }
    }
}

/*
 * Copyright 2020 ThoughtWorks, 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.thoughtworks.gocd;

import java.util.Arrays;
import java.util.TreeSet;

public class AssertJava {
    private static TreeSet<JavaVersion> SUPPORTED_VERSIONS = new TreeSet<>(Arrays.asList(
            JavaVersion.VERSION_11,
            JavaVersion.VERSION_12,
            JavaVersion.VERSION_13,
            JavaVersion.VERSION_14
    ));

    public static void assertVMVersion() {
        checkSupported(JavaVersion.current());
    }

    private static void checkSupported(JavaVersion currentJavaVersion) {
        if (!SUPPORTED_VERSIONS.contains(currentJavaVersion)) {
            System.err.println("Running GoCD requires Java version >= " + SUPPORTED_VERSIONS.first().name() +
                    " and <= " + SUPPORTED_VERSIONS.last() +
                    ". You are currently running with Java version " + currentJavaVersion + ". GoCD will now exit!");
            System.exit(1);
        }
    }
}

Allow GoCD to run on JDK 14

Allow GoCD to run on JDK 14


package com.youcruit.onfido.api.serialization;

import java.lang.reflect.Type;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.neovisionaries.i18n.CountryCode;

public class CountryCodeTypeAdapter implements JsonSerializer<CountryCode>, JsonDeserializer<CountryCode> {

    @Override
    public CountryCode deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
	return CountryCode.valueOf(json.getAsString());
    }

    @Override
    public JsonElement serialize(CountryCode src, Type typeOfSrc, JsonSerializationContext context) {
	return context.serialize(src.getAlpha3());
    }
}

package com.youcruit.onfido.api.serialization;

import java.lang.reflect.Type;
import java.util.Locale;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.neovisionaries.i18n.CountryCode;

public class CountryCodeTypeAdapter implements JsonSerializer<CountryCode>, JsonDeserializer<CountryCode> {

    @Override
    public CountryCode deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
	if (json.isJsonNull()) {
	    return null;
	}
	return CountryCode.getByCode(json.getAsString().toUpperCase(Locale.US));
    }

    @Override
    public JsonElement serialize(CountryCode src, Type typeOfSrc, JsonSerializationContext context) {
	return context.serialize(src.getAlpha3());
    }
}

Use correct method for retrieving country code

also work around bug in CountryCode related to e.g. turkish locales


package dk.statsbiblioteket.newspaper.md5checker;

import dk.statsbiblioteket.medieplatform.autonomous.Batch;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.TreeIterator;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.filesystem.transforming.TransformingIteratorForFileSystems;

import java.io.File;
import java.util.Properties;
import java.util.regex.Pattern;

public class MockupIteratorSuper extends MD5CheckerComponent {
    /**
     * Constructor matching super. Super requires a properties to be able to initialise the tree iterator, if needed.
     * If you do not need the tree iterator, ignore properties.
     *
     * You can use properties for your own stuff as well
     *
     * @param properties properties
     */
    public MockupIteratorSuper(Properties properties) {
        super(properties);
    }

    /**
     * We override this method to be able to inject our own tree iterator
     * @param batch the batch to iterate on
     * @return a tree iterator
     */
    @Override
    protected TreeIterator createIterator(Batch batch) {
        File dataDir = new File(Thread.currentThread().getContextClassLoader().getResource("scratch").getFile());
        File batchDir = new File(dataDir, batch.getFullID());
        return new TransformingIteratorForFileSystems(batchDir, Pattern.quote("."),".*\\.jp2$",".md5");
    }
}

package dk.statsbiblioteket.newspaper.md5checker;

import dk.statsbiblioteket.medieplatform.autonomous.Batch;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.TreeIterator;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.filesystem.transforming.TransformingIteratorForFileSystems;

import java.io.File;
import java.util.Arrays;
import java.util.Properties;
import java.util.regex.Pattern;

public class MockupIteratorSuper extends MD5CheckerComponent {
    /**
     * Constructor matching super. Super requires a properties to be able to initialise the tree iterator, if needed.
     * If you do not need the tree iterator, ignore properties.
     *
     * You can use properties for your own stuff as well
     *
     * @param properties properties
     */
    public MockupIteratorSuper(Properties properties) {
        super(properties);
    }

    /**
     * We override this method to be able to inject our own tree iterator
     * @param batch the batch to iterate on
     * @return a tree iterator
     */
    @Override
    protected TreeIterator createIterator(Batch batch) {
        File dataDir = new File(Thread.currentThread().getContextClassLoader().getResource("scratch").getFile());
        File batchDir = new File(dataDir, batch.getFullID());
        return new TransformingIteratorForFileSystems(batchDir, Pattern.quote("."),".*\\.jp2$",".md5",
                                                      Arrays.asList("transfer_complete", "transfer_acknowledged"));
    }
}

MAke list of ignored files by file iterator configurable


/*
 * Copyright (C) 2015 Index Data
 *
 * 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 okapi.bean;

/**
 * Tells how a module is to be deployed. Either my exec'ing a command (and
 * killing the process afterwards), or by using command lines to start and
 * stop it.
 */
public class ProcessDeploymentDescriptor {

  private String cmdlineStart;
  private String cmdlineStop;
  private String exec;

  public ProcessDeploymentDescriptor() {
  }

  public String getCmdlineStart() {
    return cmdlineStart;
  }

  public void setCmdlineStart(String cmdlineStart) {
    this.cmdlineStart = cmdlineStart;
  }

  public String getCmdlineStop() {
    return cmdlineStop;
  }

  public void setCmdlineStop(String cmdlineStop) {
    this.cmdlineStop = cmdlineStop;
  }

  public String getExec() {
    return exec;
  }

  public void setExec(String exec) {
    this.exec = exec;
  }
}

/*
 * Copyright (C) 2015 Index Data
 *
 * 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 okapi.bean;

/**
 * Tells how a module is to be deployed. Either by exec'ing a command (and
 * killing the process afterwards), or by using command lines to start and
 * stop it.
 */
public class ProcessDeploymentDescriptor {

  private String cmdlineStart;
  private String cmdlineStop;
  private String exec;

  public ProcessDeploymentDescriptor() {
  }

  public String getCmdlineStart() {
    return cmdlineStart;
  }

  public void setCmdlineStart(String cmdlineStart) {
    this.cmdlineStart = cmdlineStart;
  }

  public String getCmdlineStop() {
    return cmdlineStop;
  }

  public void setCmdlineStop(String cmdlineStop) {
    this.cmdlineStop = cmdlineStop;
  }

  public String getExec() {
    return exec;
  }

  public void setExec(String exec) {
    this.exec = exec;
  }
}

Fix text typo in javadoc

Fix text typo in javadoc


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

/**
 * @author bjorncs
 */
public interface AthenzIdentity {
    AthenzDomain getDomain();
    String getName();
    default String getFullName() {
        return getDomain().getName() + "." + getName();
    }
}

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

/**
 * @author bjorncs
 */
public interface AthenzIdentity {
    AthenzDomain getDomain();
    String getName();
    default String getFullName() {
        return getDomain().getName() + "." + getName();
    }
    default String getDomainName() { return getDomain().getName(); }
}

Add helper method to return domain name

Add helper method to return domain name


package net.rebworks.lunchy.domain.places;

import net.rebworks.lunchy.domain.Place;
import net.rebworks.lunchy.resources.LunchResource;

import javax.inject.Inject;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;

public class BynsBistro implements Place {

    private static final TreeSet<String> ALIASES = new TreeSet<>(Arrays.asList("byns", "bynsbistro"));
    public static final String NAME = ALIASES.first();
    final UriInfo uriInfo;

    @Inject
    public BynsBistro(@Context final UriInfo uriInfo) {
        this.uriInfo = uriInfo;
    }

    @Override
    public String getName() {
        return "Byns Bistro";
    }

    @Override
    public SortedSet<String> getAliases() {
        return ALIASES;
    }

    @Override
    public URI getWebsite() {
        return URI.create("http://www.bynsbistro.nu/veckans-lunch.aspx");
    }

    @Override
    public URI getUri() {
        return LunchResource.getPlaceURI(uriInfo, NAME);
    }

}

package net.rebworks.lunchy.domain.places;

import net.rebworks.lunchy.domain.Place;
import net.rebworks.lunchy.resources.LunchResource;

import javax.inject.Inject;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;

public class BynsBistro implements Place {

    private static final TreeSet<String> ALIASES = new TreeSet<>(Arrays.asList("byns", "bynsbistro"));
    public static final String NAME = ALIASES.first();
    final UriInfo uriInfo;

    @Inject
    public BynsBistro(@Context final UriInfo uriInfo) {
        this.uriInfo = uriInfo;
    }

    @Override
    public String getName() {
        return "Byns Bistro";
    }

    @Override
    public SortedSet<String> getAliases() {
        return ALIASES;
    }

    @Override
    public URI getWebsite() {
        return URI.create("https://www.bynsbistro.se/menyer");
    }

    @Override
    public URI getUri() {
        return LunchResource.getPlaceURI(uriInfo, NAME);
    }

}

Fix the lunch URL for Byns Bistro

Fix the lunch URL for Byns Bistro

No change to the parser, the page format is completely changed so I
will handle it separately.


package com.khmelenko.lab.travisclient.util;

import android.util.Base64;

/**
 * Provides util methods related with encryption/decryption
 *
 * @author Dmytro Khmelenko
 */
public final class EncryptionUtils {

    // denied constructor
    private EncryptionUtils() {

    }

    /**
     * Encodes input string to Base64
     *
     * @param input Input string
     * @return Base64 string
     */
    public static String toBase64(String input) {
        String base64Str = Base64.encodeToString(input.getBytes(), Base64.DEFAULT);
        return base64Str;
    }

    /**
     * Decodes base64 string to original
     *
     * @param base64 Base64 string
     * @return Original string
     */
    public static String fromBase64(String base64) {
        byte[] data = Base64.decode(base64, Base64.DEFAULT);
        String origin = new String(data);
        return origin;
    }

    /**
     * Generates string for Basic authorization
     *
     * @param username Username
     * @param password Password
     * @return Basic authorization string
     */
    public static String generateBasicAuthorization(String username, String password) {
        String credentials = String.format("%1$s:%2$s", username, password);
        String basic = String.format("Basic %1$s", toBase64(credentials));
        return basic;
    }
}

package com.khmelenko.lab.travisclient.util;

import android.util.Base64;

/**
 * Provides util methods related with encryption/decryption
 *
 * @author Dmytro Khmelenko
 */
public final class EncryptionUtils {

    // denied constructor
    private EncryptionUtils() {

    }

    /**
     * Encodes input string to Base64
     *
     * @param input Input string
     * @return Base64 string
     */
    public static String toBase64(String input) {
        String base64Str = Base64.encodeToString(input.getBytes(), Base64.DEFAULT);
        return base64Str;
    }

    /**
     * Decodes base64 string to original
     *
     * @param base64 Base64 string
     * @return Original string
     */
    public static String fromBase64(String base64) {
        byte[] data = Base64.decode(base64, Base64.DEFAULT);
        String origin = new String(data);
        return origin;
    }

    /**
     * Generates string for Basic authorization
     *
     * @param username Username
     * @param password Password
     * @return Basic authorization string
     */
    public static String generateBasicAuthorization(String username, String password) {
        String credentials = String.format("%1$s:%2$s", username, password);
        String basic = String.format("Basic %1$s", toBase64(credentials)).trim();
        return basic;
    }
}

Remove 0x0a char at the end of authorization header value


package hrv.band.aurora.view.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;

import hrv.band.aurora.R;

/**
 * Created by Julian on 15.11.2016.
 */

public class DisclaimerDialogFragment extends DialogFragment {

    public static final String DISCLAIMER_AGREEMENT = "DisclaimerAgreementAccepted";

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        builder.setTitle(R.string.disclaimer)
            .setMessage(R.string.disclaimerText)
            .setPositiveButton(R.string.agree, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
                    SharedPreferences.Editor prefsEditor = mPrefs.edit();
                    prefsEditor.putBoolean(DISCLAIMER_AGREEMENT, true);
                    prefsEditor.commit();
                }
            })
            .setNegativeButton(R.string.disagree, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    System.exit(0);
                }
            });

        return builder.create();
    }
}

package hrv.band.aurora.view.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;

import hrv.band.aurora.R;

/**
 * Created by Julian on 15.11.2016.
 */

public class DisclaimerDialogFragment extends DialogFragment {

    public static final String DISCLAIMER_AGREEMENT = "DisclaimerAgreementAccepted";

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        builder.setTitle(R.string.disclaimer)
            .setMessage(R.string.disclaimerText)
            .setPositiveButton(R.string.agree, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
                    SharedPreferences.Editor prefsEditor = mPrefs.edit();
                    prefsEditor.putBoolean(DISCLAIMER_AGREEMENT, true);
                    prefsEditor.apply();
                }
            })
            .setNegativeButton(R.string.disagree, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    System.exit(0);
                }
            });

        return builder.create();
    }
}

Change commit to apply (SharedPreferences)


package me.st28.flexseries.flexcore.debug;

import me.st28.flexseries.flexcore.message.MessageReference;

/**
 * Represents the output of {@link DebugTest#runTest(org.bukkit.command.CommandSender, String, String[])}.
 */
public final class DebugTestOutput {

    private final boolean isSuccess;
    private final MessageReference message;

    public DebugTestOutput(boolean isSuccess, String message) {
        this(isSuccess, MessageReference.createPlain(message));
    }

    public DebugTestOutput(boolean isSuccess, MessageReference message) {
        this.isSuccess = isSuccess;
        this.message = message;
    }

    public boolean isSuccess() {
        return isSuccess;
    }

    public MessageReference getMessage() {
        return message;
    }

}

package me.st28.flexseries.flexcore.debug;

import me.st28.flexseries.flexcore.message.MessageReference;

/**
 * Represents the output of {@link DebugTest#runTest(org.bukkit.command.CommandSender, String, String[])}.
 */
public final class DebugTestOutput {

    private final boolean isSuccess;
    private final MessageReference message;

    public DebugTestOutput(boolean isSuccess, String message) {
        this(isSuccess, message == null ? null : MessageReference.createPlain(message));
    }

    public DebugTestOutput(boolean isSuccess, MessageReference message) {
        this.isSuccess = isSuccess;
        this.message = message;
    }

    public boolean isSuccess() {
        return isSuccess;
    }

    public MessageReference getMessage() {
        return message;
    }

}

Set message to null rather than creating an empty MessageReference. Fixes a NPE.


package sizebay.catalog.client.model;

import lombok.*;

@Getter
@Setter
@EqualsAndHashCode
@ToString
public class ModelingSizeMeasures   {

  String sizeName = null;
  ModelingMeasureRange chest = null;
  ModelingMeasureRange hip = null;
  ModelingMeasureRange waist = null;
  ModelingMeasureRange sleeve = null;
  ModelingMeasureRange length = null;
  ModelingMeasureRange insideLeg = null;
  ModelingMeasureRange biceps = null;
  ModelingMeasureRange height = null;
  ModelingMeasureRange fist = null;
  ModelingMeasureRange neck = null;
  ModelingMeasureRange thigh = null;
  ModelingMeasureRange centralSeam = null;
  ModelingMeasureRange underBust = null;
  ModelingMeasureRange shoulderWidth = null;
  ModelingMeasureRange insoleLength = null;
  ModelingMeasureRange insoleWidth = null;
  ModelingMeasureRange waistUpper = null;
  ModelingMeasureRange waistLower = null;

  ModelingMeasureRange label1 = null;
  ModelingMeasureRange label2 = null;
  ModelingMeasureRange label3 = null;

  ModelingMeasureRange ageChart = null;
  ModelingMeasureRange weightChart = null;
  ModelingMeasureRange equivalence = null;
  ModelingMeasureRange headCircumference = null;

}

package sizebay.catalog.client.model;

import lombok.*;

@Getter
@Setter
@EqualsAndHashCode
@ToString
public class ModelingSizeMeasures   {

  String sizeName = null;
  ModelingMeasureRange chest = null;
  ModelingMeasureRange hip = null;
  ModelingMeasureRange waist = null;
  ModelingMeasureRange sleeve = null;
  ModelingMeasureRange length = null;
  ModelingMeasureRange insideLeg = null;
  ModelingMeasureRange biceps = null;
  ModelingMeasureRange height = null;
  ModelingMeasureRange fist = null;
  ModelingMeasureRange neck = null;
  ModelingMeasureRange thigh = null;
  ModelingMeasureRange centralSeam = null;
  ModelingMeasureRange underBust = null;
  ModelingMeasureRange shoulderWidth = null;
  ModelingMeasureRange insoleLength = null;
  ModelingMeasureRange insoleWidth = null;
  ModelingMeasureRange waistUpper = null;
  ModelingMeasureRange waistLower = null;

  ModelingMeasureRange label1 = null;
  ModelingMeasureRange label2 = null;
  ModelingMeasureRange label3 = null;

  ModelingMeasureRange ageChart = null;
  ModelingMeasureRange weightChart = null;
  ModelingMeasureRange equivalence = null;

}

Revert "Fix: Add new measure -> headCircumference"

This reverts commit 152b8e73235be97cd989e9b39498fc351a71fc8c.


package org.ovirt.engine.core.bll.network.dc;

import org.ovirt.engine.core.bll.validator.NetworkValidator;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.action.AddNetworkStoragePoolParameters;
import org.ovirt.engine.core.common.errors.VdcBllMessages;

public class RemoveNetworkCommand<T extends AddNetworkStoragePoolParameters> extends NetworkCommon<T> {
    public RemoveNetworkCommand(T parameters) {
        super(parameters);
    }

    @Override
    protected void executeCommand() {
        getNetworkDAO().remove(getNetwork().getId());
        setSucceeded(true);
    }

    @Override
    protected void setActionMessageParameters() {
        super.setActionMessageParameters();
        addCanDoActionMessage(VdcBllMessages.VAR__ACTION__REMOVE);
    }

    @Override
    protected boolean canDoAction() {
        NetworkValidator validator = new NetworkValidator(getNetworkDAO().get(getNetwork().getId()));
        return validate(validator.networkIsSet())
                && validate(validator.notManagementNetwork())
                && validate(validator.networkNotUsedByVms())
                && validate(validator.networkNotUsedByTemplates());
    }

    @Override
    public AuditLogType getAuditLogTypeValue() {
        return getSucceeded() ? AuditLogType.NETWORK_REMOVE_NETWORK : AuditLogType.NETWORK_REMOVE_NETWORK_FAILED;
    }
}

package org.ovirt.engine.core.bll.network.dc;

import org.ovirt.engine.core.bll.validator.NetworkValidator;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.action.AddNetworkStoragePoolParameters;
import org.ovirt.engine.core.common.errors.VdcBllMessages;

public class RemoveNetworkCommand<T extends AddNetworkStoragePoolParameters> extends NetworkCommon<T> {
    public RemoveNetworkCommand(T parameters) {
        super(parameters);
    }

    @Override
    protected void executeCommand() {
        removeVnicProfiles();
        getNetworkDAO().remove(getNetwork().getId());
        setSucceeded(true);
    }

    @Override
    protected void setActionMessageParameters() {
        super.setActionMessageParameters();
        addCanDoActionMessage(VdcBllMessages.VAR__ACTION__REMOVE);
    }

    @Override
    protected boolean canDoAction() {
        NetworkValidator validator = new NetworkValidator(getNetworkDAO().get(getNetwork().getId()));
        return validate(validator.networkIsSet())
                && validate(validator.notManagementNetwork())
                && validate(validator.networkNotUsedByVms())
                && validate(validator.networkNotUsedByTemplates());
    }

    @Override
    public AuditLogType getAuditLogTypeValue() {
        return getSucceeded() ? AuditLogType.NETWORK_REMOVE_NETWORK : AuditLogType.NETWORK_REMOVE_NETWORK_FAILED;
    }
}

engine: Delete vnic profiles when removing a network

The patch removes vnic profiles when the network is
being deleted from the system.

Change-Id: I6472fb81262d7eb2cf6886a42ba17a637c804b22
Signed-off-by: Moti Asayag <da1debb83a8e12b6e8822edf2c275f55cc51b720@redhat.com>


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

package com.akexorcist.mvpsimple.common;

public interface BasePresenter {

    void start();

}

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

package com.akexorcist.mvpsimple.common;

public interface BasePresenter {

    void start();

    void stop();

}

Add stop for unregister event bus

Add stop for unregister event bus


package net.contargo.iris.config;

import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
import com.mangofactory.swagger.models.dto.ApiInfo;
import com.mangofactory.swagger.plugin.EnableSwagger;
import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;

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

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.ui.Model;

/**
 * @author  Sandra Thieme - thieme@synyx.de
 */
@Configuration
@EnableSwagger
public class SwaggerConfig {

    private SpringSwaggerConfig springSwaggerConfig;

    @Autowired
    public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {

        this.springSwaggerConfig = springSwaggerConfig;
    }

    @Bean
    public SwaggerSpringMvcPlugin customImplementation() {

        this.springSwaggerConfig.defaultSwaggerPathProvider().setApiResourcePrefix("api");

        return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(apiInfo()).ignoredParameterTypes(
                Model.class);
    }

    private ApiInfo apiInfo() {

        return new ApiInfo("IRIS Backend Api", null, null, null, null, null);
    }
}

package net.contargo.iris.config;

import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
import com.mangofactory.swagger.models.dto.ApiInfo;
import com.mangofactory.swagger.plugin.EnableSwagger;
import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;

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

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.ui.Model;

/**
 * @author  Sandra Thieme - thieme@synyx.de
 * @author  David Schilling - schilling@synyx.de
 */
@Configuration
@EnableSwagger
public class SwaggerConfig {

    private String[] includePattern = new String[] {
        "\\/geocodes.*", "\\/osmaddresses.*", "\\/places.*", "\\/reversegeocode.*", "\\/airlineDistance.*",
        "\\/countries.*", "\\/distancecloudaddress.*", "\\/connections.*", "\\/routedetails.*", "\\/routerevisions.*",
        "\\/routes.*", "\\/seaports.*", "\\/staticaddresses.*", "\\/terminals.*", "\\/simplegeocodes.*"
    };

    private SpringSwaggerConfig springSwaggerConfig;

    @Autowired
    public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {

        this.springSwaggerConfig = springSwaggerConfig;
    }

    @Bean
    public SwaggerSpringMvcPlugin customImplementation() {

        springSwaggerConfig.defaultSwaggerPathProvider().setApiResourcePrefix("api");

        return new SwaggerSpringMvcPlugin(springSwaggerConfig).apiInfo(apiInfo())
            .includePatterns(includePattern)
            .ignoredParameterTypes(Model.class);
    }

    private ApiInfo apiInfo() {

        return new ApiInfo("IRIS Backend Api", null, null, null, null, null);
    }
}

Use include patterns for swagger to avoid unintended includes

References #14379


package org.jusecase.properties.ui;

import javax.swing.*;

public class KeyListMenu extends JPopupMenu {
    public KeyListMenu() {
        JMenuItem newKey = new JMenuItem("New");
        add(newKey);

        JMenuItem duplicateKey = new JMenuItem("Duplicate");
        add(duplicateKey);
    }
}

package org.jusecase.properties.ui;

import javax.swing.*;

public class KeyListMenu extends JPopupMenu {
    public KeyListMenu() {
        JMenuItem newKey = new JMenuItem("New");
        add(newKey);

        JMenuItem duplicateKey = new JMenuItem("Duplicate");
        add(duplicateKey);

        JMenuItem renameKey = new JMenuItem("Rename");
        add(renameKey);
    }
}

Add rename key option so that its not forgotten later


package com.zyeeda.framework.cxf;

import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.SerializationConfig.Feature;

public class JacksonJsonProvider extends JacksonJaxbJsonProvider {

	public JacksonJsonProvider() {
		ObjectMapper m = this._mapperConfig.getConfiguredMapper();
		if (m == null) {
			m = this._mapperConfig.getDefaultMapper();
		}
		m.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
		m.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
	}

}

package com.zyeeda.framework.cxf;

import java.text.SimpleDateFormat;

import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.SerializationConfig.Feature;

public class JacksonJsonProvider extends JacksonJaxbJsonProvider {

	public JacksonJsonProvider() {
		ObjectMapper m = this._mapperConfig.getConfiguredMapper();
		if (m == null) {
			m = this._mapperConfig.getDefaultMapper();
		}
		SerializationConfig sc = m.getSerializationConfig().withDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
		sc.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
		sc.set(Feature.FAIL_ON_EMPTY_BEANS, false);
		m.setSerializationConfig(sc);
		/*
		m.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
		m.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
		m.setSerializationConfig(m.getSerializationConfig().withDateFormat(new SimpleDateFormat("yyyy-MM-dd")));
		*/
	}

}

Make CXF serialize date type in pre-defined format.


package ru.nsu.ccfit.bogush.factory.thing.periodical;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class SimplePeriodical implements Periodical {
	private long period;

	private static final String LOGGER_NAME = "SimplePeriodical";
	private static final Logger logger = LogManager.getLogger(LOGGER_NAME);

	public SimplePeriodical(long period) {
		this.period = period;
	}

	private final Object lock = new Object();

	@Override
	public void setPeriod(long period) {
		logger.trace("set period " + period + " milliseconds");
		if (period < 0) {
			logger.error("period < 0");
			throw new IllegalArgumentException("period must be greater than or equal to 0");
		}
		this.period = period;
	}

	@Override
	public void waitPeriod() {
		long timeToWait = period;
		long time = System.currentTimeMillis();
		try {
			synchronized (lock) {
				while (timeToWait > 0) {
					lock.wait(timeToWait);
					long newTime = System.currentTimeMillis();
					timeToWait -= newTime - time;
					time = newTime;
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
			logger.error(e);
			System.exit(1);
		}
	}

	@Override
	public long getPeriod() {
		return period;
	}
}

package ru.nsu.ccfit.bogush.factory.thing.periodical;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class SimplePeriodical implements Periodical {
	private long period;

	private static final String LOGGER_NAME = "SimplePeriodical";
	private static final Logger logger = LogManager.getLogger(LOGGER_NAME);

	public SimplePeriodical(long period) {
		this.period = period;
	}

	private final Object lock = new Object();

	@Override
	public void setPeriod(long period) {
		logger.trace("set period " + period + " milliseconds");
		if (period < 0) {
			logger.error("period < 0");
			throw new IllegalArgumentException("period must be greater than or equal to 0");
		}
		this.period = period;
		lock.notifyAll();
	}

	@Override
	public void waitPeriod() {
		long timeToWait = period;
		long time = System.currentTimeMillis();
		try {
			synchronized (lock) {
				while (timeToWait > 0) {
					lock.wait(timeToWait);
					long newTime = System.currentTimeMillis();
					timeToWait -= newTime - time;
					time = newTime;
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
			logger.error(e);
			System.exit(1);
		}
	}

	@Override
	public long getPeriod() {
		return period;
	}
}

Use notifyAll() to update the period in blocked waitPeriod


package com.hubspot.mesos.protos;

public enum  MesosTaskStatusReason {
  REASON_COMMAND_EXECUTOR_FAILED, REASON_CONTAINER_LAUNCH_FAILED, REASON_CONTAINER_LIMITATION, REASON_CONTAINER_LIMITATION_DISK,
  REASON_CONTAINER_LIMITATION_MEMORY, REASON_CONTAINER_PREEMPTED, REASON_CONTAINER_UPDATE_FAILED, REASON_EXECUTOR_REGISTRATION_TIMEOUT,
  REASON_EXECUTOR_REREGISTRATION_TIMEOUT, REASON_EXECUTOR_TERMINATED, REASON_EXECUTOR_UNREGISTERED, REASON_FRAMEWORK_REMOVED, REASON_GC_ERROR,
  REASON_INVALID_FRAMEWORKID, REASON_INVALID_OFFERS, REASON_IO_SWITCHBOARD_EXITED, REASON_MASTER_DISCONNECTED, REASON_RECONCILIATION,
  REASON_RESOURCES_UNKNOWN, REASON_SLAVE_DISCONNECTED, REASON_SLAVE_REMOVED, REASON_SLAVE_REMOVED_BY_OPERATOR, REASON_SLAVE_RESTARTED,
  REASON_SLAVE_UNKNOWN, REASON_TASK_CHECK_STATUS_UPDATED, REASON_TASK_GROUP_INVALID, REASON_TASK_GROUP_UNAUTHORIZED,
  REASON_TASK_HEALTH_CHECK_STATUS_UPDATED, REASON_TASK_INVALID, REASON_TASK_KILLED_DURING_LAUNCH, REASON_TASK_UNAUTHORIZED,
  REASON_TASK_UNKNOWN
}

package com.hubspot.mesos.protos;

public enum  MesosTaskStatusReason {
  REASON_COMMAND_EXECUTOR_FAILED,
  REASON_CONTAINER_LAUNCH_FAILED,
  REASON_CONTAINER_LIMITATION,
  REASON_CONTAINER_LIMITATION_DISK,
  REASON_CONTAINER_LIMITATION_MEMORY,
  REASON_CONTAINER_PREEMPTED,
  REASON_CONTAINER_UPDATE_FAILED,
  REASON_EXECUTOR_REGISTRATION_TIMEOUT,
  REASON_EXECUTOR_REREGISTRATION_TIMEOUT,
  REASON_EXECUTOR_TERMINATED,
  REASON_EXECUTOR_UNREGISTERED,
  REASON_FRAMEWORK_REMOVED,
  REASON_GC_ERROR,
  REASON_INVALID_FRAMEWORKID,
  REASON_INVALID_OFFERS,
  REASON_IO_SWITCHBOARD_EXITED,
  REASON_MASTER_DISCONNECTED,
  REASON_RECONCILIATION,
  REASON_RESOURCES_UNKNOWN,
  REASON_SLAVE_DISCONNECTED,
  REASON_SLAVE_REMOVED,
  REASON_SLAVE_REMOVED_BY_OPERATOR,
  REASON_SLAVE_RESTARTED,
  REASON_SLAVE_UNKNOWN,
  REASON_AGENT_DISCONNECTED,
  REASON_AGENT_REMOVED,
  REASON_AGENT_REMOVED_BY_OPERATOR,
  REASON_AGENT_RESTARTED,
  REASON_AGENT_UNKNOWN,
  REASON_TASK_KILLED_DURING_LAUNCH,
  REASON_TASK_CHECK_STATUS_UPDATED,
  REASON_TASK_HEALTH_CHECK_STATUS_UPDATED,
  REASON_TASK_GROUP_INVALID,
  REASON_TASK_GROUP_UNAUTHORIZED,
  REASON_TASK_INVALID,
  REASON_TASK_UNAUTHORIZED,
  REASON_TASK_UNKNOWN
}

Add REASON_AGENT status update reasons

Add REASON_AGENT status update reasons


package com.alapshin.arctor.delegate;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;

import com.alapshin.arctor.presenter.Presenter;
import com.alapshin.arctor.view.MvpView;

import javax.annotation.Nonnull;

public interface FragmentMvpDelegate<V extends MvpView, P extends Presenter<V>> {
    public void onCreate(@Nonnull P presenter, @Nullable Bundle savedInstanceState);
    public void onViewCreated(V view, @Nullable Bundle savedInstanceState);
    public void onStart();
    public void onResume();
    public void onPause();
    public void onSaveInstanceState(Bundle outState);
    public void onStop();
    public void onDestroyView();
    public void onDestroy();
}

package com.alapshin.arctor.delegate;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;

import com.alapshin.arctor.presenter.Presenter;
import com.alapshin.arctor.view.MvpView;

import javax.annotation.Nonnull;

public interface FragmentMvpDelegate<V extends MvpView, P extends Presenter<V>> {
    public void onCreate(@Nullable Bundle savedInstanceState);
    public void onViewCreated(@Nullable Bundle savedInstanceState);
    public void onStart();
    public void onResume();
    public void onPause();
    public void onSaveInstanceState(Bundle outState);
    public void onStop();
    public void onDestroyView();
    public void onDestroy();
}

Remove unused parameters from FramgentMvpDelegate


package nl.gmta.btrfs.structure.stream;

enum BtrfsValueType {
    BTRFS_TLV_U8       (0x00),
    BTRFS_TLV_U16      (0x01),
    BTRFS_TLV_U32      (0x02),
    BTRFS_TLV_U64      (0x03),
    BTRFS_TLV_BINARY   (0x04),
    BTRFS_TLV_STRING   (0x05),
    BTRFS_TLV_UUID     (0x06),
    BTRFS_TLV_TIMESPEC (0x07);

    private int value;

    BtrfsValueType(int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }
}

package nl.gmta.btrfs.structure.stream;

enum BtrfsValueType {
    U8       (0x00),
    U16      (0x01),
    U32      (0x02),
    U64      (0x03),
    BINARY   (0x04),
    STRING   (0x05),
    UUID     (0x06),
    TIMESPEC (0x07);

    private int value;

    BtrfsValueType(int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }
}

Remove common prefix from value type enum values


package org.opennms.netmgt.dao.support;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.opennms.netmgt.rrd.RrdConfig;
import org.opennms.netmgt.rrd.RrdException;
import org.opennms.netmgt.rrd.RrdUtils;
import org.opennms.netmgt.rrd.jrobin.JRobinRrdStrategy;

public class RrdTestUtils {
    // Reference the class name this way so that it is refactoring resistant
    private static final String RRD_CONFIG = "org.opennms.rrd.strategyClass=" + JRobinRrdStrategy.class.getName();

    /**
     * This class cannot be instantiated.  Use static methods.
     */
    private RrdTestUtils() {

    }

    public static void initialize() throws IOException, RrdException {
        RrdConfig.loadProperties(new ByteArrayInputStream(RRD_CONFIG.getBytes()));
        RrdUtils.initialize();
    }
}

package org.opennms.netmgt.dao.support;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.opennms.netmgt.rrd.RrdConfig;
import org.opennms.netmgt.rrd.RrdException;
import org.opennms.netmgt.rrd.RrdUtils;
import org.opennms.netmgt.rrd.jrobin.JRobinRrdStrategy;

public class RrdTestUtils {
    // Reference the class name this way so that it is refactoring resistant
    private static final String RRD_CONFIG = "org.opennms.rrd.strategyClass=" + JRobinRrdStrategy.class.getName()
        + "\norg.opennms.rrd.usequeue=false";

    /**
     * This class cannot be instantiated.  Use static methods.
     */
    private RrdTestUtils() {

    }

    public static void initialize() throws IOException, RrdException {
        RrdConfig.loadProperties(new ByteArrayInputStream(RRD_CONFIG.getBytes()));
        RrdUtils.initialize();
    }
}

Disable RRD queue feature when testing so files are actually written when we write to them. :-)


package io.dropwizard.views;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

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

/**
 * An {@link ExceptionMapper} that returns a 500 error response with a generic
 * HTML error page when a {@link ViewRenderException} is thrown.
 *
 * @since 1.1.0
 */
@Provider
public class ViewRenderExceptionMapper implements ExceptionMapper<WebApplicationException> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ViewRenderExceptionMapper.class);

    /**
     * The generic HTML error page template.
     */
    public static final String TEMPLATE_ERROR_MSG =
            "" +
                "<title>Template Error</title>" +
                "
Template Error

Something went wrong rendering the page
" +
            "";

    @Override
    public Response toResponse(WebApplicationException exception) {
        Throwable cause = exception.getCause();
        if (cause instanceof ViewRenderException) {
            LOGGER.error("Template Error", cause);
            return Response.serverError()
                    .type(MediaType.TEXT_HTML_TYPE)
                    .entity(TEMPLATE_ERROR_MSG)
                    .build();
        }
        return exception.getResponse();
    }

}

package io.dropwizard.views;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.glassfish.jersey.spi.ExtendedExceptionMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * An {@link ExtendedExceptionMapper} that returns a 500 error response with a generic
 * HTML error page when a {@link ViewRenderException} is the cause.
 *
 * @since 1.1.0
 */
@Provider
public class ViewRenderExceptionMapper implements ExtendedExceptionMapper<WebApplicationException> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ViewRenderExceptionMapper.class);

    /**
     * The generic HTML error page template.
     */
    public static final String TEMPLATE_ERROR_MSG =
            "" +
                "<title>Template Error</title>" +
                "
Template Error

Something went wrong rendering the page
" +
            "";

    @Override
    public Response toResponse(WebApplicationException exception) {
        LOGGER.error("Template Error", exception);
        return Response.serverError()
                .type(MediaType.TEXT_HTML_TYPE)
                .entity(TEMPLATE_ERROR_MSG)
                .build();
    }

    @Override
    public boolean isMappable(WebApplicationException e) {
        return ExceptionUtils.indexOfThrowable(e, ViewRenderException.class) != -1;
    }
}

Move ViewExceptionMapper to an ExtendedExceptionMapper


package com.bignerdranch.android.photogallery;

import android.os.HandlerThread;
import android.util.Log;

public class ThumbnailDownloader<T> extends HandlerThread {

    private static final String TAG = "ThumbnailDownloader";

    public ThumbnailDownloader() {
        super(TAG);
    }

    public void queueThumbnail(T target, String url) {
        Log.i(TAG, "Gor a URL: " + url);
    }
}

package com.bignerdranch.android.photogallery;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class ThumbnailDownloader<T> extends HandlerThread {

    private static final String TAG = "ThumbnailDownloader";

    private static final int MESSAGE_DOWNLOAD = 0;

    private Handler mRequestHandler;
    private ConcurrentMap<T, String> mRequestMap = new ConcurrentHashMap<T, String>();
    private Handler mResponseHandler;
    private ThumbnailDownloadListener<T> mThumbnailDownloadListener;

    public interface ThumbnailDownloadListener<T> {
        void onThumbnailDownload(T target, Bitmap thumbnail);
    }

    public void setThumbnailDownloadListener(ThumbnailDownloadListener<T> listener) {
        mThumbnailDownloadListener = listener;
    }

    public ThumbnailDownloader(Handler responseHandler) {
        super(TAG);
        mRequestHandler = responseHandler;
    }

    public void queueThumbnail(T target, String url) {
        Log.i(TAG, "Gor a URL: " + url);

        if (url == null) {
            mRequestMap.remove(target);
        }
        else {
            mRequestMap.put(target, url);
            mRequestHandler.obtainMessage(MESSAGE_DOWNLOAD, target).sendToTarget();
        }
    }

    private void handleRequest(final T target) {
        try {
            final String url = mRequestMap.get(target);

            if (url == null) {
                return;
            }

            byte[] bitmapBytes = new FlickrFetcher().getUrlBytes(url);

            final Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length);
            Log.i(TAG, "Bitmap created");

            mResponseHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (mRequestMap.get(target) != url) {
                        return;
                    }

                    mRequestMap.remove(target);
                    mThumbnailDownloadListener.onThumbnailDownload(target, bitmap);
                }
            });

        }
        catch (IOException ioe) {
            Log.e(TAG, "Error downloading image", ioe);
        }
    }

    public void clearQueue() {
        mRequestHandler.removeMessages(MESSAGE_DOWNLOAD);
    }
}

Complete the implementation of the Downloader, what a horrible thing :facepalm:


package io.tjeubaoit.android.mvc.annotation;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import io.tjeubaoit.android.mvc.message.Message;

/**
 * TODO: Class description here.
 *
 * @author tjeubaoit
 */
public class OnActionScanner {

    public static Map<String, Method> getMethodsAnnotatedAsAction(Object obj) {
        Message msg = new Message.Builder().build();
        Map<String, Method> methodMap = new HashMap<>();

        // scan methods for mapping
        for (Method method : obj.getClass().getDeclaredMethods()) {
            if (!method.isAnnotationPresent(OnAction.class)) continue;

            Class<?>[] paramTypes = method.getParameterTypes();
            if (paramTypes.length != 1 || !paramTypes[0].isInstance(msg)) continue;

            for (String action : method.getAnnotation(OnAction.class).value()) {
                methodMap.put(action, method);
            }
        }

        return methodMap;
    }
}

package io.tjeubaoit.android.mvc.annotation;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import io.tjeubaoit.android.mvc.message.Message;
import io.tjeubaoit.android.mvc.util.Logger;

/**
 * TODO: Class description here.
 *
 * @author tjeubaoit
 */
public class OnActionScanner {

    private static final Logger LOGGER = Logger.getLogger(OnActionScanner.class);

    public static Map<String, Method> getMethodsAnnotatedAsAction(Object obj) {
        Message msg = new Message.Builder().build();
        Map<String, Method> methodMap = new HashMap<>();

        // scan methods for mapping
        for (Method method : obj.getClass().getDeclaredMethods()) {
            if (!method.isAnnotationPresent(OnAction.class)) continue;

            Class<?>[] paramTypes = method.getParameterTypes();
            if (paramTypes.length == 0 || (paramTypes.length == 1 && paramTypes[0].isInstance(msg))) {
                for (String action : method.getAnnotation(OnAction.class).value()) {
                    methodMap.put(action, method);
                    LOGGER.debug(String.format("Map action %s with method %s", action, method.getName()));
                }
            } else {
                throw new RuntimeException("Parameters invalid for method: " + method);
            }
        }

        return methodMap;
    }
}

Throw exception if target method marked with OnAction has invalid parameters


package org.synyx.urlaubsverwaltung.calendar;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
import java.util.stream.Stream;

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

class CalendarPropertiesTest {

    private Validator validator;

    @BeforeEach
    void setUp() {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    @Test
    void organizerIsAnEmail() {
        final CalendarProperties calendarProperties = new CalendarProperties();
        calendarProperties.setOrganizer("email@example.org");
        final Set<ConstraintViolation<CalendarProperties>> violations = validator.validate(calendarProperties);

        assertThat(violations.size()).isZero();
    }

    static Stream<String> organizerStrings() {
        return Stream.of("", "NotAnEmail", null);
    }

    @ParameterizedTest
    @MethodSource("organizerStrings")
    void organizerIsWrong(String input) {
        final CalendarProperties calendarProperties = new CalendarProperties();
        calendarProperties.setOrganizer(input);
        final Set<ConstraintViolation<CalendarProperties>> violations = validator.validate(calendarProperties);

        assertThat(violations.size()).isOne();
    }
}

package org.synyx.urlaubsverwaltung.calendar;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

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

class CalendarPropertiesTest {

    private Validator validator;

    @BeforeEach
    void setUp() {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    @Test
    void organizerIsAnEmail() {
        final CalendarProperties calendarProperties = new CalendarProperties();
        calendarProperties.setOrganizer("email@example.org");
        final Set<ConstraintViolation<CalendarProperties>> violations = validator.validate(calendarProperties);

        assertThat(violations.size()).isZero();
    }

    @ParameterizedTest
    @ValueSource(strings = {"", " ", "NotAnEmail"})
    @NullSource
    void organizerIsWrong(String input) {
        final CalendarProperties calendarProperties = new CalendarProperties();
        calendarProperties.setOrganizer(input);
        final Set<ConstraintViolation<CalendarProperties>> violations = validator.validate(calendarProperties);

        assertThat(violations.size()).isOne();
    }
}

Improve parameterized test with sources

Improve parameterized test with sources


package org.camunda.bpm.demo.orderconfirmation.config;

import org.camunda.bpm.demo.orderconfirmation.bean.RuleEntryDAO;
import org.camunda.bpm.demo.orderconfirmation.model.DiscountRuleEntry;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
import java.util.List;
import java.util.logging.Logger;

/*
 * Helper class to create an initial set of discount rules
 */
@Singleton
@Startup
public class DiscountRuleEntryConfig {

  private final static Logger log = Logger.getLogger(DiscountRuleEntryConfig.class.getCanonicalName());

  @Inject
  private RuleEntryDAO rulesDAO;

  /*
   * If no discount rules are present in the database, we create some initial ones
   */
  @PostConstruct
  public void initializeDiscountRules() {
    List<DiscountRuleEntry> rules = rulesDAO.findAllDiscountRuleEntries();
    if ((rules == null) || (rules.size() == 0)) {
      log.info("Creating initial sample discount rules: ...");
      rulesDAO.save(new DiscountRuleEntry("Small orders", 100, 500, 5));
      rulesDAO.save(new DiscountRuleEntry("Mediun orders", 501, 1000, 7));
      rulesDAO.save(new DiscountRuleEntry("Big orders", 1001, 5000, 10));
    }
  }
}

package org.camunda.bpm.demo.orderconfirmation.config;

import org.camunda.bpm.demo.orderconfirmation.bean.RuleEntryDAO;
import org.camunda.bpm.demo.orderconfirmation.model.DiscountRuleEntry;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
import java.util.List;
import java.util.logging.Logger;

/*
 * Helper class to create an initial set of discount rules
 */
@Singleton
@Startup
public class DiscountRuleEntryConfig {

  private final static Logger log = Logger.getLogger(DiscountRuleEntryConfig.class.getCanonicalName());

  @Inject
  private RuleEntryDAO rulesDAO;

  /*
   * If no discount rules are present in the database, we create some initial ones
   */
  @PostConstruct
  public void initializeDiscountRules() {
    List<DiscountRuleEntry> rules = rulesDAO.findAllDiscountRuleEntries();
    if ((rules == null) || (rules.size() == 0)) {
      log.info("Creating initial sample discount rules: ...");
      rulesDAO.save(new DiscountRuleEntry("Small orders", 0, 500, 5));
      rulesDAO.save(new DiscountRuleEntry("Mediun orders", 501, 1000, 7));
      rulesDAO.save(new DiscountRuleEntry("Big orders", 1001, 5000, 10));
    }
  }
}

Fix "amount from" for "Small orders"

Fix "amount from" for "Small orders"


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

package com.adaptris.util.text;

/**
 * Interface for handling null parameters.
 *
 * @author lchan
 *
 */
public interface NullConverter {

  /**
   * Convert a null into something more meaningful.
   *
   */
  <T> T convert(T t);
}

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

package com.adaptris.util.text;

/**
 * Interface for handling null parameters.
 *
 * @author lchan
 *
 */
@FunctionalInterface
public interface NullConverter {

  /**
   * Convert a null into something more meaningful.
   *
   */
  <T> T convert(T t);
}

Make NC a functional interface.

Make NC a functional interface.


package org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons;

import org.telegram.telegrambots.meta.api.interfaces.Validable;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;

import java.util.ArrayList;

/**
 * @author Ruben Bermudez
 * @version 1.0
 * @brief Row for ReplyKeyBoardMarkup
 * @date 10 of April of 2016
 */
public class KeyboardRow extends ArrayList<KeyboardButton> implements Validable {
    public boolean add(String text) {
        return super.add(new KeyboardButton(text));
    }

    public void add(int index, String text) {
        super.add(index, new KeyboardButton(text));
    }

    public boolean contains(String text) {
        return super.contains(new KeyboardButton(text));
    }

    public int lastIndexOf(String text) {
        return super.lastIndexOf(new KeyboardButton(text));
    }

    public int indexOf(String text) {
        return super.indexOf(new KeyboardButton(text));
    }

    public KeyboardButton set(int index, String text) {
        return super.set(index, new KeyboardButton(text));
    }

    public boolean remove(String text) {
        return super.remove(new KeyboardButton(text));
    }

    @Override
    public void validate() throws TelegramApiValidationException {
        for (KeyboardButton keyboardButton : this) {
            keyboardButton.validate();
        }
    }
}

package org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons;

import org.telegram.telegrambots.meta.api.interfaces.Validable;
import org.telegram.telegrambots.meta.exceptions.TelegramApiValidationException;

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

/**
 * @author Ruben Bermudez
 * @version 1.0
 * @brief Row for ReplyKeyBoardMarkup
 * @date 10 of April of 2016
 */
public class KeyboardRow extends ArrayList<KeyboardButton> implements Validable {
    public boolean add(String text) {
        return super.add(new KeyboardButton(text));
    }

    public void add(int index, String text) {
        super.add(index, new KeyboardButton(text));
    }

    public void addAll(List<String> buttonNames) {
        buttonNames.forEach(KeyboardButton::new);
    }

    public boolean contains(String text) {
        return super.contains(new KeyboardButton(text));
    }

    public int lastIndexOf(String text) {
        return super.lastIndexOf(new KeyboardButton(text));
    }

    public int indexOf(String text) {
        return super.indexOf(new KeyboardButton(text));
    }

    public KeyboardButton set(int index, String text) {
        return super.set(index, new KeyboardButton(text));
    }

    public boolean remove(String text) {
        return super.remove(new KeyboardButton(text));
    }

    @Override
    public void validate() throws TelegramApiValidationException {
        for (KeyboardButton keyboardButton : this) {
            keyboardButton.validate();
        }
    }
}

Add addAll method for keyboardrow

Add addAll method for keyboardrow


/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
package com.facebook.imagepipeline.memory;

import android.graphics.Bitmap;
import com.facebook.common.memory.MemoryTrimType;
import com.facebook.imageutils.BitmapUtil;

public class DummyBitmapPool implements BitmapPool {

  @Override
  public void trim(MemoryTrimType trimType) {
    // nop
  }

  @Override
  public Bitmap get(int size) {
    return Bitmap.createBitmap(
        1,
        (int) Math.ceil(size / (double) BitmapUtil.RGB_565_BYTES_PER_PIXEL),
        Bitmap.Config.RGB_565);
  }

  @Override
  public void release(Bitmap value) {
    value.recycle();
  }
}

/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
package com.facebook.imagepipeline.memory;

import android.graphics.Bitmap;
import com.facebook.common.internal.Preconditions;
import com.facebook.common.memory.MemoryTrimType;
import com.facebook.imageutils.BitmapUtil;

public class DummyBitmapPool implements BitmapPool {

  @Override
  public void trim(MemoryTrimType trimType) {
    // nop
  }

  @Override
  public Bitmap get(int size) {
    return Bitmap.createBitmap(
        1,
        (int) Math.ceil(size / (double) BitmapUtil.RGB_565_BYTES_PER_PIXEL),
        Bitmap.Config.RGB_565);
  }

  @Override
  public void release(Bitmap value) {
    Preconditions.checkNotNull(value);
    value.recycle();
  }
}

Add Preconditions NPE check to pool release method

Reviewed By: oprisnik

Differential Revision: D14706933

fbshipit-source-id: 5ef5a1dbee73ce1ec11533efeb61845fa15a61a5


package com.wkovacs64.mtorch;

import android.app.Application;

import timber.log.Timber;

public class CustomApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        if (BuildConfig.DEBUG) {
            // Initialize Timber logging library
            Timber.plant(new Timber.DebugTree());
        }
    }
}

package com.wkovacs64.mtorch;

import android.app.Application;
import android.os.Build;
import android.os.StrictMode;

import timber.log.Timber;

public class CustomApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        if (BuildConfig.DEBUG) {
            // Initialize Timber logging library
            Timber.plant(new Timber.DebugTree());

            // Enable StrictMode for debug builds
            enabledStrictMode();
        }
    }

    private void enabledStrictMode() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectAll()
                    .penaltyLog()
                    .penaltyDialog()
                    .build());
        }
    }
}

Enable StrictMode for debug builds

Enable StrictMode for debug builds


package cgeo.geocaching.connector.trackable;

import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.R;

import org.eclipse.jdt.annotation.NonNull;

public enum TrackableBrand {
    TRAVELBUG(1, R.drawable.trackable_travelbug, R.string.trackable_travelbug),
    GEOKRETY(2, R.drawable.trackable_geokrety, R.string.trackable_geokrety),
    SWAGGIE(2, R.drawable.trackable_swaggie, R.string.trackable_swaggie),
    UNKNOWN(0, R.drawable.trackable_all, R.string.trackable_unknown); // Trackable not initialized yet

    private final int id;
    private final int stringId;
    private final int markerId;

    TrackableBrand(final int id, final int markerId, final int stringId) {
        this.id = id;
        this.markerId = markerId;
        this.stringId = stringId;
    }

    public int getId() {
        return id;
    }

    public int getIconResource() {
        return markerId;
    }

    public String getLabel() {
        return CgeoApplication.getInstance().getString(stringId);
    }

    @NonNull
    public static TrackableBrand getById(final int id) {
        for (final TrackableBrand brand : values()) {
            if (brand.id == id) {
                return brand;
            }
        }
        return UNKNOWN;
    }

}

package cgeo.geocaching.connector.trackable;

import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.R;

import org.eclipse.jdt.annotation.NonNull;

public enum TrackableBrand {
    TRAVELBUG(1, R.drawable.trackable_travelbug, R.string.trackable_travelbug),
    GEOKRETY(2, R.drawable.trackable_geokrety, R.string.trackable_geokrety),
    SWAGGIE(3, R.drawable.trackable_swaggie, R.string.trackable_swaggie),
    UNKNOWN(0, R.drawable.trackable_all, R.string.trackable_unknown); // Trackable not initialized yet

    private final int id;
    private final int stringId;
    private final int markerId;

    TrackableBrand(final int id, final int markerId, final int stringId) {
        this.id = id;
        this.markerId = markerId;
        this.stringId = stringId;
    }

    public int getId() {
        return id;
    }

    public int getIconResource() {
        return markerId;
    }

    public String getLabel() {
        return CgeoApplication.getInstance().getString(stringId);
    }

    @NonNull
    public static TrackableBrand getById(final int id) {
        for (final TrackableBrand brand : values()) {
            if (brand.id == id) {
                return brand;
            }
        }
        return UNKNOWN;
    }

}

Set a unique id to each Trackable Brand

Set a unique id to each Trackable Brand


/**
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 */

package com.microsoft.azure;

import com.microsoft.azure.annotations.AzureHost;
import com.microsoft.rest.annotations.GET;
import com.microsoft.rest.annotations.HostParam;
import com.microsoft.rest.annotations.PathParam;

public class AzureTests {

    @AzureHost("{vaultBaseUrl}")
    public interface HttpBinService {
        @GET("secrets/{secretName}")
        String getSecret(@HostParam String vaultBaseUrl, @PathParam("secretName") String secretName);
    }

// @AzureHost not yet supported.
//    @Test
//    public void getBytes() throws Exception {
//        RestClient client = new RestClient.Builder()
//                .withBaseUrl("http://localhost")
//                .withSerializerAdapter(new JacksonAdapter())
//                .withResponseBuilderFactory(new ServiceResponseBuilder.Factory())
//                .build();
//        HttpBinService service = RestProxy.create(HttpBinService.class, client);
//
//        Assert.assertEquals("http://vault1.vault.azure.net/secrets/{secretName}", service.getSecret("http://vault1.vault.azure.net", "secret1"));
//    }
}

/**
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 */

package com.microsoft.azure;

import com.microsoft.azure.annotations.AzureHost;
import com.microsoft.rest.annotations.GET;
import com.microsoft.rest.annotations.HostParam;
import com.microsoft.rest.annotations.PathParam;

public class AzureTests {

    @AzureHost("{vaultBaseUrl}")
    public interface HttpBinService {
        @GET("secrets/{secretName}")
        String getSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, @PathParam("secretName") String secretName);
    }

// @AzureHost not yet supported.
//    @Test
//    public void getBytes() throws Exception {
//        RestClient client = new RestClient.Builder()
//                .withBaseUrl("http://localhost")
//                .withSerializerAdapter(new JacksonAdapter())
//                .withResponseBuilderFactory(new ServiceResponseBuilder.Factory())
//                .build();
//        HttpBinService service = RestProxy.create(HttpBinService.class, client);
//
//        Assert.assertEquals("http://vault1.vault.azure.net/secrets/{secretName}", service.getSecret("http://vault1.vault.azure.net", "secret1"));
//    }
}

Fix build error in test

Fix build error in test


package authoring.data;

import com.syntacticsugar.vooga.util.ResourceManager;

public class TileData {

	private static final String PATH = ResourceManager.getString("Path_name");
	private static final String SCENERY = ResourceManager.getString("Scenery_name");

	private String myImagePath;
	private String myImplementation;
	private boolean isDestination;

	public TileData(String imagePath) {
		setImagePath(imagePath);
		setImplementation(PATH);
		setDestination(false);
	}

	public void setImagePath(String path) {
		this.myImagePath = path;
	}

	public void setImplementation(String impl) {
		this.myImplementation = (impl.equals("Path")) ? PATH : SCENERY;
	}

	public void setDestination(boolean isDestination) {
		this.isDestination = isDestination;
	}

	public String getImagePath() {
		return this.myImagePath;
	}

	public String getImplementation() {
		return this.myImplementation;
	}

	public boolean isDestination() {
		return this.isDestination;
	}
}

package authoring.data;

import com.syntacticsugar.vooga.util.ResourceManager;

public class TileData {

	private static final String PATH = ResourceManager.getString("Path_name");
	private static final String SCENERY = ResourceManager.getString("Scenery_name");

	private String myImagePath;
	private String myImplementation;
	private boolean isDestination;

	public TileData(String imagePath) {
		setImagePath(imagePath);
		setImplementation("Path");
		setDestination(false);
	}

	public void setImagePath(String path) {
		this.myImagePath = path;
	}

	public void setImplementation(String impl) {
		this.myImplementation = (impl.equals("Path")) ? PATH : SCENERY;
	}

	public void setDestination(boolean isDestination) {
		this.isDestination = isDestination;
	}

	public String getImagePath() {
		return this.myImagePath;
	}

	public String getImplementation() {
		return this.myImplementation;
	}

	public boolean isDestination() {
		return this.isDestination;
	}
}

Change the implementation string to "Path"