package org.dstadler.commoncrawl;

/**
 * Which extensions we are interested in.
 *
 * @author dominik.stadler
 */
public class Extensions {

    private static final String[] EXTENSIONS = new String[] {
        // Excel
        ".xls",
        ".xlsx",
        ".xlsm",
        ".xltx",
        ".xlsb",

        // Word
        ".doc",
        ".docx",
        ".dotx",
        ".docm",
        ".ooxml",

        // Powerpoint
        ".ppt",
        ".pot",
        ".pptx",
        ".pptm",
        ".ppsm",
        ".ppsx",
        ".thmx",
        ".potx",

        // Outlook
        ".msg",

        // Publisher
        ".pub",

        // Visio - binary
        ".vsd",
        ".vss",
        ".vst",
        ".vsw",

        // Visio - ooxml (currently unsupported)
        ".vsdm",
        ".vsdx",
        ".vssm",
        ".vssx",
        ".vstm",
        ".vstx",

        // POIFS
        ".ole2",

        // Microsoft Admin Template?
        ".adm",

        // Microsoft TNEF
        // ".dat", new HMEFFileHandler());
    };

    public static boolean matches(String url) {
        for(String ext : EXTENSIONS) {
            if(url.endsWith(ext)) {
                return true;
            }
        }

        return false;
    }
}

package org.dstadler.commoncrawl;

/**
 * Which extensions we are interested in.
 *
 * If you want to change which files are downloaded, just can
 * set a different list of file-extensions here, e.g.
 *
 * <pre>
           ".pdf"
 </pre>
 *
 * would find and download PDF documents.
 */
public class Extensions {

    private static final String[] EXTENSIONS = new String[] {
        // Excel
        ".xls",
        ".xlsx",
        ".xlsm",
        ".xltx",
        ".xlsb",

        // Word
        ".doc",
        ".docx",
        ".dotx",
        ".docm",
        ".ooxml",

        // Powerpoint
        ".ppt",
        ".pot",
        ".pptx",
        ".pptm",
        ".ppsm",
        ".ppsx",
        ".thmx",
        ".potx",

        // Outlook
        ".msg",

        // Publisher
        ".pub",

        // Visio - binary
        ".vsd",
        ".vss",
        ".vst",
        ".vsw",

        // Visio - ooxml (currently unsupported)
        ".vsdm",
        ".vsdx",
        ".vssm",
        ".vssx",
        ".vstm",
        ".vstx",

        // POIFS
        ".ole2",

        // Microsoft Admin Template?
        ".adm",

        // Microsoft TNEF
        // ".dat", new HMEFFileHandler());
    };

    public static boolean matches(String url) {
        for(String ext : EXTENSIONS) {
            if(url.endsWith(ext)) {
                return true;
            }
        }

        return false;
    }
}

Add a bit more JavaDoc

Add a bit more JavaDoc


/**
 * This file is part of Frames, licensed under the MIT License (MIT).
 *
 * Copyright (c) 2014 ObsidianBox <http://obsidianbox.org/>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.obsidianbox.frames;

public interface IMaskedField extends ITextField {
    /**
     * Gets the current character used to mask text input. Defaults to an asterisk (*).
     *
     * @return the mask character.
     */
    char getMaskCharacter();

    /**
     * Sets the character to use to mask text that is put into this field.
     *
     * @param character the mask character.
     * @return the masked field.
     */
    IMaskedField setMaskCharacter(char character);
}

Add license header to IMaskedTextField

Add license header to IMaskedTextField

Signed-off-by: Steven Downer <e51bce9123e792aec8a98724fb48684dc936521f@outlook.com>


package org.clubrockisen.dao;

import java.sql.Connection;

import org.clubrockisen.connection.MySQLConnection;
import org.clubrockisen.entities.Member;

/**
 * The factory for the MySQL DAO classes.
 * @author Alex
 */
public class MySQLDAOFactory extends AbstractDAOFactory {
	protected static final Connection connection = MySQLConnection.getInstance();

	/* (non-Javadoc)
	 * @see org.clubrockisen.dao.AbstractDAOFactory#getMemberDAO()
	 */
	@Override
	public DAO<Member> getMemberDAO () {
		return new MySQLMemberDAO();
	}
}

package org.clubrockisen.dao;

import java.sql.Connection;

import org.clubrockisen.connection.MySQLConnection;
import org.clubrockisen.entities.Member;

/**
 * The factory for the MySQL DAO classes.
 * @author Alex
 */
public class MySQLDAOFactory extends AbstractDAOFactory {
	protected static final Connection CONNECTION = MySQLConnection.getInstance();

	/* (non-Javadoc)
	 * @see org.clubrockisen.dao.AbstractDAOFactory#getMemberDAO()
	 */
	@Override
	public DAO<Member> getMemberDAO () {
		return new MySQLMemberDAO();
	}
}

Change the name of the constant use the correct casing.


package co.phoenixlab.discord.commands;

import co.phoenixlab.discord.MessageContext;
import co.phoenixlab.discord.api.DiscordApiClient;
import co.phoenixlab.discord.api.entities.Channel;
import co.phoenixlab.discord.api.entities.Message;
import co.phoenixlab.discord.api.entities.User;

public class CommandUtil {

    static User findUser(MessageContext context, String username) {
        Message message = context.getMessage();
        User user;
        Channel channel = context.getApiClient().getChannelById(message.getChannelId());
        //  Attempt to find the given user
        //  If the user is @mentioned, try that first
        if (message.getMentions() != null && message.getMentions().length > 0) {
            user = message.getMentions()[0];
        } else {
            user = context.getApiClient().findUser(username, channel.getParent());
        }
        //  Try matching by ID
        if (user == DiscordApiClient.NO_USER) {
            user = context.getApiClient().getUserById(username, channel.getParent());
        }
        return user;
    }
}

package co.phoenixlab.discord.commands;

import co.phoenixlab.discord.MessageContext;
import co.phoenixlab.discord.api.entities.Channel;
import co.phoenixlab.discord.api.entities.Message;
import co.phoenixlab.discord.api.entities.User;

public class CommandUtil {

    static User findUser(MessageContext context, String username) {
        Message message = context.getMessage();
        User user;
        Channel channel = context.getApiClient().getChannelById(message.getChannelId());
        //  Attempt to find the given user
        //  If the user is @mentioned, try that first
        if (message.getMentions() != null && message.getMentions().length > 0) {
            user = message.getMentions()[0];
        } else {
            //  Try exact match, frontal match, ID match, and fuzzy match
            user = context.getApiClient().findUser(username, channel.getParent());
        }
        return user;
    }
}

Remove duplicate funct in CmdUtil.findUser()


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

package org.mskcc.cbio.oncokb.util;

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

/**
 *
 * @author jgao
 */
public final class PropertiesUtils {
    private static Properties PROPERTIES;
    private PropertiesUtils() {
        throw new AssertionError();
    }

    public static String getProperties(String name) throws IOException {
        if(name == null) {
            return null;
        }

        if(PROPERTIES == null) {
            String propFileName = "properties/config.properties";
            PROPERTIES = new Properties();
            InputStream inputStream = PropertiesUtils.class.getClassLoader().getResourceAsStream(propFileName);

            if (inputStream != null) {
                PROPERTIES.load(inputStream);
            } else {
                throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
            }
            inputStream.close();
        }

        return PROPERTIES.get(name) == null ? null : (String)PROPERTIES.get(name);
    }
}

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

package org.mskcc.cbio.oncokb.util;

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

/**
 *
 * @author jgao
 */
public final class PropertiesUtils {
    private static Properties PROPERTIES;
    private PropertiesUtils() {
        throw new AssertionError();
    }

    public static String getProperties(String name) throws IOException {
        if(name == null) {
            return null;
        }

        if(PROPERTIES == null) {
            String propFileName = "properties/config.properties";
            PROPERTIES = new Properties();
            InputStream inputStream = PropertiesUtils.class.getClassLoader().getResourceAsStream(propFileName);

            if (inputStream != null) {
                PROPERTIES.load(inputStream);
            } else {
                throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
            }
            inputStream.close();
        }

        // use system property if available, otherwise get from file
        return System.getProperty(name, PROPERTIES.get(name) == null ? null : (String)PROPERTIES.get(name));
    }
}

Allow setting properties with java system props

Set properties with e.g. -Ddata.version=12345


package es.sandbox.spikes.java8.interfaces;

import es.sandbox.spikes.java8.InvocationSpy;
import org.junit.Before;
import org.junit.Test;

import static es.sandbox.spikes.java8.InvocationSpy.spy;
import static org.assertj.core.api.Assertions.assertThat;

/**
 * Created by jeslopalo on 30/12/15.
 */
public class FunctionalInterfaceSpecs {

    private InvocationSpy spy;

    private static final void callFunctionalInterface(SimpleFunctionalInterface functionalInterface) {
        functionalInterface.doWork();
    }

    @Before
    public void setup() {
        this.spy = spy();
    }

    @Test
    public void has_one_callable_method() {
        callFunctionalInterface(() -> this.spy.invocation());

        assertThat(this.spy.invoked()).isTrue();
    }
}

package es.sandbox.spikes.java8.interfaces;

import es.sandbox.spikes.java8.InvocationSpy;
import org.junit.Before;
import org.junit.Test;

import static es.sandbox.spikes.java8.FunctionalInterfaceCaller.call;
import static es.sandbox.spikes.java8.InvocationSpy.spy;
import static org.assertj.core.api.Assertions.assertThat;

/**
 * Created by jeslopalo on 30/12/15.
 */
public class FunctionalInterfaceSpecs {

    private InvocationSpy spy;

    @Before
    public void setup() {
        this.spy = spy();
    }

    @Test
    public void has_one_callable_method() {
        call(() -> this.spy.invocation());

        assertThat(this.spy.invoked()).isTrue();
    }
}

Refactor utility method to FunctionalInterfaceCaller


/**
 *
 */
package org.opennms.dashboard.client;

import com.google.gwt.user.client.ui.FlexTable;

class NotificationView extends PageableTableView {

    private Notification[] m_notifications;

    NotificationView() {
        super(new String[] { "Node", "Service", "Sent Time", "Responder", "Response Time" });
    }

    public void setNotifications(Notification[] notifications) {
        m_notifications = notifications;
        refresh();

    }

	protected void setRow(FlexTable table, int row, int elementIndex) {
		Notification notif = m_notifications[elementIndex];
        table.setText(row, 0, notif.getNodeLabel());
        table.setText(row, 1, notif.getServiceName());
        table.setText(row, 2, ""+notif.getSentTime());
        table.setText(row, 3, notif.getResponder());
        table.setText(row, 4, ""+notif.getRespondTime());
        table.getRowFormatter().setStyleName(row, notif.getSeverity());
    }

    public int getElementCount() {
        return (m_notifications == null ? 0 : m_notifications.length);
    }

}

/**
 *
 */
package org.opennms.dashboard.client;

import com.google.gwt.user.client.ui.FlexTable;

class NotificationView extends PageableTableView {

    private Notification[] m_notifications;

    NotificationView() {
        super(new String[] { "Node", "Service", "Sent Time", "Responder", "Response Time" });
    }

    public void setNotifications(Notification[] notifications) {
        m_notifications = notifications;
        refresh();

    }

	protected void setRow(FlexTable table, int row, int elementIndex) {
		Notification notif = m_notifications[elementIndex];
        table.setText(row, 0, notif.getNodeLabel());
        table.setText(row, 1, notif.getServiceName());
        table.setText(row, 2, ""+notif.getSentTime());
        table.setText(row, 3, notif.getResponder());
        table.setText(row, 4, (notif.getRespondTime() != null) ? notif.getRespondTime().toString() : "");
        table.getRowFormatter().setStyleName(row, notif.getSeverity());
    }

    public int getElementCount() {
        return (m_notifications == null ? 0 : m_notifications.length);
    }

}

Fix the case where respond time is null

Fix the case where respond time is null


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

/**
 * @author traff
 */
public interface XReferrersProvider<T extends XValue> {
  T getReferringObjectsValue();
}

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

/**
 * @author traff
 */
public abstract class XReferrersProvider<T extends XValue> {
  public abstract T getReferringObjectsValue();
}

Make abstract class instead of interface.


package de.retest.recheck.printer.leaf;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

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

import de.retest.ui.diff.DurationDifference;

class DurationDifferencePrinterTest {

	DurationDifferencePrinter cut;

	@BeforeEach
	void setUp() {
		cut = new DurationDifferencePrinter();
	}

	@Test
	void toString_should_print_difference() {
		final DurationDifference difference = mock( DurationDifference.class );
		when( difference.getExpected() ).thenReturn( 0L );
		when( difference.getActual() ).thenReturn( 1L );

		final String string = cut.toString( difference );

		assertThat( string ).isEqualTo( "0.001 s" );
	}

	@Test
	void toString_should_respect_indent() {
		final DurationDifference difference = mock( DurationDifference.class );
		when( difference.getExpected() ).thenReturn( 0L );
		when( difference.getActual() ).thenReturn( 1L );

		final String string = cut.toString( difference, "____" );

		assertThat( string ).startsWith( "____" );
	}
}

package de.retest.recheck.printer.leaf;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

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

import de.retest.ui.diff.DurationDifference;

class DurationDifferencePrinterTest {

	DurationDifferencePrinter cut;

	@BeforeEach
	void setUp() {
		cut = new DurationDifferencePrinter();
	}

	@Test
	void toString_should_handle_positive_difference() {
		final DurationDifference difference = mock( DurationDifference.class );
		when( difference.getExpected() ).thenReturn( 0L );
		when( difference.getActual() ).thenReturn( 1L );

		final String string = cut.toString( difference );

		assertThat( string ).isEqualTo( "0.001 s" );
	}

	@Test
	void toString_should_handle_negative_difference() {
		final DurationDifference difference = mock( DurationDifference.class );
		when( difference.getExpected() ).thenReturn( 1L );
		when( difference.getActual() ).thenReturn( 0L );

		final String string = cut.toString( difference );

		assertThat( string ).isEqualTo( "-0.001 s" );
	}

	@Test
	void toString_should_respect_indent() {
		final DurationDifference difference = mock( DurationDifference.class );
		when( difference.getExpected() ).thenReturn( 0L );
		when( difference.getActual() ).thenReturn( 1L );

		final String string = cut.toString( difference, "____" );

		assertThat( string ).startsWith( "____" );
	}
}

Add tests for positive and negative duration differences


package com.github.tnerevival.core;

import com.github.tnerevival.core.version.ReleaseType;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

public class UpdateChecker {
  private String url;
  private String build;
  private String currentBuild;

  public UpdateChecker(String url, String currentBuild) {
    this.url = url;
    this.currentBuild = currentBuild;
    getLatestBuild();
  }

  public void getLatestBuild() {
    build = currentBuild;
    try {
        URL url = new URL(this.url);
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        build = in.readLine();
        in.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public ReleaseType getRelease() {
    Integer latest = Integer.valueOf(build.replace(".", ""));
    Integer current = Integer.valueOf(currentBuild.replace(".", ""));

    if(latest < current) return ReleaseType.PRERELEASE;
    if(latest.equals(current)) return ReleaseType.LATEST;
    return ReleaseType.OUTDATED;
  }
}

package com.github.tnerevival.core;

import com.github.tnerevival.core.version.ReleaseType;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

public class UpdateChecker {
  private String url;
  private String build;
  private String currentBuild;

  public UpdateChecker(String url, String currentBuild) {
    this.url = url;
    this.currentBuild = currentBuild;
    getLatestBuild();
  }

  public void getLatestBuild() {
    build = currentBuild;
    try {
        URL url = new URL(this.url);
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        this.build = in.readLine();
        in.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public ReleaseType getRelease() {
    Integer latest = Integer.valueOf(build.replace(".", ""));
    Integer current = Integer.valueOf(currentBuild.replace(".", ""));

    if(latest < current) return ReleaseType.PRERELEASE;
    if(latest.equals(current)) return ReleaseType.LATEST;
    return ReleaseType.OUTDATED;
  }

  public String getBuild() {
    return build;
  }

  public String getCurrentBuild() {
    return currentBuild;
  }
}

Add get methods for updater variables.

Add get methods for updater variables.


package lego;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.ResourceIterator;
import org.neo4j.logging.Log;
import org.neo4j.procedure.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class Degree {
    @Context
    public GraphDatabaseService db;

    @Context
    public Log log;

    /**
     * Calculate degree of vertex
     *
     * @param label label name
     */
    @Procedure(value = "lego.degree", mode = Mode.READ)
    @Description("Calculate degree of vertex")
    public Stream<DegreeResults> degree(@Name("label") String label) {
        final Label ind = Label.label(label);
        ResourceIterator<Node> nodes = db.findNodes(ind);

        List<DegreeResults> a = new ArrayList<>();

        while (nodes.hasNext()) {
            final Node recordNode = nodes.next();
            DegreeResults t = new DegreeResults(recordNode.getId(), recordNode.getDegree());
            a.add(t);
        }

        if (a.isEmpty()) {
            log.debug("Skipping since index does not exist: `%s`", label);
            return Stream.empty();
        }

        return a.stream();
    }

    public class DegreeResults {
        public final long nodes;
        public final long degree;

        /**
         * @param nodes  node id
         * @param degree node degree
         */
        public DegreeResults(long nodes, long degree) {
            this.degree = degree;
            this.nodes = nodes;
        }

    }
}

package lego;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.ResourceIterator;
import org.neo4j.logging.Log;
import org.neo4j.procedure.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class Degree {
    @Context
    public GraphDatabaseService db;

    @Context
    public Log log;

    /**
     * Calculate degree of vertex
     *
     * @param label label name
     */
    @Procedure(value = "lego.degree", mode = Mode.READ)
    @Description("Calculate degree of vertex")
    public Stream<DegreeResults> degree(@Name("label") String label) {
        final Label ind = Label.label(label);
        ResourceIterator<Node> nodes = db.findNodes(ind);

        return nodes.stream().map((n) -> new DegreeResults(n.getId(), n.getDegree()));
    }

    public class DegreeResults {
        public final long nodes;
        public final long degree;

        /**
         * @param nodes  node id
         * @param degree node degree
         */
        public DegreeResults(long nodes, long degree) {
            this.degree = degree;
            this.nodes = nodes;
        }

    }
}

Replace List with Stream API

Replace List with Stream API


package org.camsrobotics.frc2016;

import org.camsrobotics.lib.NerdyJoystick;

/**
 * Driver Station Interface
 *
 * @author Wesley
 *
 */
public class DriverInput {

	public static NerdyJoystick m_driveLeftJoy = new NerdyJoystick(0);
	public static NerdyJoystick m_driveRightJoy = new NerdyJoystick(1);
	public static NerdyJoystick m_buttonBox = new NerdyJoystick(2);

	// Prevents initialization
	private DriverInput()	{}

}

package org.camsrobotics.frc2016;

import org.camsrobotics.lib.NerdyButton;
import org.camsrobotics.lib.NerdyJoystick;

/**
 * Driver Interface
 *
 * @author Wesley
 *
 */
public class DriverInput {

	// Driver Functions
	public static final NerdyJoystick kDriverLeftStick	= new NerdyJoystick(0);
	public static final NerdyJoystick kDriverRightStick	= new NerdyJoystick(1);

	public static final NerdyButton kSnapToVisionTarget	= kDriverRightStick.getButton(99);

	// Operator Functions
	public static final NerdyJoystick kButtonBox		= new NerdyJoystick(2);

	public static final NerdyButton kShooterShortRange	= kButtonBox.getButton(99);
	public static final NerdyButton kShooterMediumRange	= kButtonBox.getButton(99);
	public static final NerdyButton kShooterLongRange	= kButtonBox.getButton(99);
	public static final NerdyButton kShooterVision		= kButtonBox.getButton(99);
	public static final NerdyButton kShoot				= kButtonBox.getButton(99);

}

Add some of the buttons

Add some of the buttons


/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.nanos.boot;

import foam.core.*;
import foam.dao.*;
import foam.nanos.*;

public class Boot {
  protected DAO serviceDAO_;
  protected X   root_ = new ProxyX();

  public Boot() {
    serviceDAO_ = new MapDAO();
    ((MapDAO) serviceDAO_).setOf(NSpec.getOwnClassInfo());
    ((MapDAO) serviceDAO_).setX(root_);
    loadTestData();

    ((AbstractDAO) serviceDAO_).select(new AbstractSink() {
      public void put(FObject obj, Detachable sub) {
        NSpec sp = (NSpec) obj;
        System.out.println("NSpec: " + sp.getName());

        try {
          // NanoService ns = sp.createService();

          // ((ContextAwareSupport) ns).setX(root_);
          // ns.start();

          root_.putFactory(sp.getName(), new SingletonFactory(new NSpecFactory(sp)));
        } catch (ClassNotFoundException e) {
           e.printStackTrace();
        } catch (InstantiationException e) {
           e.printStackTrace();
        } catch (IllegalAccessException e) {
           e.printStackTrace();
        }
      }
    });
  }

  protected void loadTestData() {
    NSpec s = new NSpec();
    s.setName("http");
    s.setServiceClass("foam.nanos.http.NanoHttpServer");
    serviceDAO_.put(s);
  }

  public static void main (String[] args) throws Exception {
    new Boot();
  }

}

/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.nanos.boot;

import foam.core.*;
import foam.dao.*;
import foam.nanos.*;

public class Boot {
  protected DAO serviceDAO_;
  protected X   root_ = new ProxyX();

  public Boot() {
    serviceDAO_ = new MapDAO();
    ((MapDAO) serviceDAO_).setOf(NSpec.getOwnClassInfo());
    ((MapDAO) serviceDAO_).setX(root_);
    loadTestData();

    ((AbstractDAO) serviceDAO_).select(new AbstractSink() {
      public void put(FObject obj, Detachable sub) {
        NSpec sp = (NSpec) obj;
        System.out.println("NSpec: " + sp.getName());

        root_.putFactory(sp.getName(), new SingletonFactory(new NSpecFactory(sp)));
      }
    });
  }

  protected void loadTestData() {
    NSpec s = new NSpec();
    s.setName("http");
    s.setServiceClass("foam.nanos.http.NanoHttpServer");
    serviceDAO_.put(s);
  }

  public static void main (String[] args) throws Exception {
    new Boot();
  }

}

Remove try/catch statement from boot constructor


package com.ljs.scratch.ootp.rating;

import com.fasterxml.jackson.annotation.JsonTypeInfo;

/**
 *
 * @author lstephen
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
public interface Scale<T> {

    Rating<T, ? extends Scale<T>> ratingOf(T value);

    Rating<T, ? extends Scale<T>> parse(String s);

    Rating<Integer, OneToOneHundred> normalize(T value);

}

package com.ljs.scratch.ootp.rating;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.ljs.scratch.ootp.ootp5.site.ZeroToTen;

/**
 *
 * @author lstephen
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
@JsonSubTypes({
    @Type(ZeroToTen.class)
})
public interface Scale<T> {

    Rating<T, ? extends Scale<T>> ratingOf(T value);

    Rating<T, ? extends Scale<T>> parse(String s);

    Rating<Integer, OneToOneHundred> normalize(T value);

}

Fix error in draft pool deserialization

Fix error in draft pool deserialization


/*
 * Parse command-line options and run the SNPrank algorithm.
 * Authors:  Brett McKinney and Nick Davis
 * Email:  brett.mckinney@gmail.com, nick@nickdavis.name
 */
public class snprank {
	public static void main(String[] args) {

		if(args.length != 3) {
			System.out.println("Usage: java snprank matrix.txt gamma output.txt");
			System.exit(1);
		}

		SNPrank full_data = new SNPrank(args[0]);
		full_data.snprank(full_data.getHeader(), full_data.getData(), args[1], args[2]);
	}
}

/*
 * Parse command-line options and run the SNPrank algorithm.
 * Authors:  Brett McKinney and Nick Davis
 * Email:  brett.mckinney@gmail.com, nick@nickdavis.name
 */
public class snprank {
	public static void main(String[] args) {

		if(args.length != 3) {
			System.out.println("Usage: java snprank matrix.txt gamma output.txt");
			System.exit(1);
		}

		SNPrankData full_data = new SNPrankData(args[0]);
		full_data.snprank(full_data.getHeader(), full_data.getData(), args[1], args[2]);
	}
}

Update SNPrank -> SNPrankData in main class


package se.hyperlab.tigcm;

import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import org.appcelerator.kroll.common.Log;

import org.appcelerator.titanium.TiApplication;

import java.util.HashMap;

public class NotificationActivity extends Activity {

    private static final String TAG = "NotificationActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        HashMap<String, Object> data = (HashMap)intent.getSerializableExtra(TiGCMModule.NTF_KEY_DATA);

        TiGCMModule module = TiGCMModule.getInstance();
        TiApplication instance = TiApplication.getInstance();

        if(module != null) {
            module.fireMessage(data, false);
        } else {
            TiApplication.getInstance().getAppProperties().setString(TiGCMModule.PROPERTY_PENDING_DATA, data.toString());
            Log.d(TAG, "Saving data in props: " + data.toString());
        }

        String pkg = instance.getApplicationContext().getPackageName();
        Intent launcherIntent = instance.getApplicationContext().getPackageManager().getLaunchIntentForPackage(pkg);

        startActivity(launcherIntent);
        finish();
    }
}

package se.hyperlab.tigcm;

import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import org.appcelerator.kroll.common.Log;

import org.appcelerator.titanium.TiApplication;
import org.appcelerator.kroll.KrollDict;

import java.util.HashMap;

public class NotificationActivity extends Activity {

    private static final String TAG = "NotificationActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        HashMap<String, Object> data = (HashMap)intent.getSerializableExtra(TiGCMModule.NTF_KEY_DATA);

        TiGCMModule module = TiGCMModule.getInstance();
        TiApplication instance = TiApplication.getInstance();

        if(module != null) {
            module.fireMessage(data, false);
        } else {
            KrollDict kdata = new KrollDict(data);

            TiApplication.getInstance().getAppProperties().setString(TiGCMModule.PROPERTY_PENDING_DATA, kdata.toString());
            Log.d(TAG, "Saving data in props: " + kdata.toString());
        }

        String pkg = instance.getApplicationContext().getPackageName();
        Intent launcherIntent = instance.getApplicationContext().getPackageManager().getLaunchIntentForPackage(pkg);

        startActivity(launcherIntent);
        finish();
    }
}

Fix data serialization causing app not to receive data when launched from notification


package br.com.bloder.blorm;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

import br.com.bloder.blormlib.Blorm;

import static br.com.bloder.blormlib.validation.Validations.*;

public class MainActivity extends AppCompatActivity {

  private EditText editTextFilled;
  private Button submit;

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

    editTextFilled = (EditText) findViewById(R.id.edit_text_filled);
    submit = (Button) findViewById(R.id.submit);

    new Blorm.Builder().field(editTextFilled).is(filled).onSubmit(submit);
  }
}

package br.com.bloder.blorm;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

import br.com.bloder.blormlib.Blorm;
import br.com.bloder.blormlib.validation.Validate;

import static br.com.bloder.blormlib.validation.Validations.*;

public class MainActivity extends AppCompatActivity {

  private EditText editTextFilled;
  private Button submit;

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

    editTextFilled = (EditText) findViewById(R.id.edit_text_filled);
    submit = (Button) findViewById(R.id.submit);

    new Blorm.Builder().field(editTextFilled).is(filled).onSubmit(submit);

    new Blorm.Builder().field(editTextFilled).is(new Validate() {
      @Override
      public boolean validate() {
        return false;
      }

      @Override
      public void onError() {

      }
    }).onSubmit(submit);
  }
}

Add custom on error example in main activity


package org.concord.otrunk.user;

import org.concord.framework.otrunk.OTObjectInterface;
import org.concord.framework.otrunk.OTObjectList;
import org.concord.otrunk.view.OTClassMember;
import org.concord.otrunk.view.document.OTDocument;

public interface OTWorkgroupMemberChooser
    extends OTObjectInterface
{
	/**
	 * The current user
	 * @return
	 */
	public void setLeadMember(OTClassMember member);
	public OTClassMember getLeadMember();

	/**
	 * A List of OTClassMember objects, all of which are copied from the OTClassListManager
	 * @return
	 */
	public OTObjectList getOtherWorkgroupMembers();

	/**
	 * A List of OTClassMember objects, all of which were dynamically created on the fly by the current user
	 * @return
	 */
	public OTObjectList getCustomWorkgroupMembers();

	public static final boolean DEFAULT_usePopup = true;
	public boolean getUsePopup();

	/**
	 * This Document is a template for the header text in the view. The text will be run through a simple substitution engine prior to being rendered.
	 * Valid substitution variables are:
	 *   #{user_name}
	 * @return
	 */
	public OTDocument getTextTemplate();
}

package org.concord.otrunk.user;

import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.OTObjectInterface;
import org.concord.framework.otrunk.OTObjectList;
import org.concord.otrunk.view.OTClassMember;

public interface OTWorkgroupMemberChooser
    extends OTObjectInterface
{
	/**
	 * The current user
	 * @return
	 */
	public void setLeadMember(OTClassMember member);
	public OTClassMember getLeadMember();

	/**
	 * A List of OTClassMember objects, all of which are copied from the OTClassListManager
	 * @return
	 */
	public OTObjectList getOtherWorkgroupMembers();

	/**
	 * A List of OTClassMember objects, all of which were dynamically created on the fly by the current user
	 * @return
	 */
	public OTObjectList getCustomWorkgroupMembers();

	public static final boolean DEFAULT_usePopup = true;
	public boolean getUsePopup();

	/**
	 * This Document is a template for the header text in the view. The text will be run through a simple substitution engine prior to being rendered.
	 * Valid substitution variables are:
	 *   #{user_name}
	 * The type of this object is set to OTObject to remove its dependency on OTDocument which
	 * is no longer in the OTrunk project.  The view now casts this to OTDocument.
	 * This class should probably be moved to another package/project.
	 * @return
	 */
	public OTObject getTextTemplate();
}

Change the workgroupmemberchooser so it doesn't directly depend on OTDocument.  This change is to facilitate moving OTDocument out of the otrunk project.

git-svn-id: 8ebed0c25533aaea68ca43268d4d516467f97e6a@16773 6e01202a-0783-4428-890a-84243c50cc2b


package org.asteriskjava.manager.event;

import static org.junit.Assert.assertEquals;

import java.util.TimeZone;

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

public class CdrEventTest
{
    CdrEvent cdrEvent;
    TimeZone defaultTimeZone;

    @Before
    public void setUp()
    {
        cdrEvent = new CdrEvent(this);
        cdrEvent.setStartTime("2006-05-19 11:54:48");
        defaultTimeZone = TimeZone.getDefault();
        TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
    }

    @Before
    public void tearDown()
    {
        TimeZone.setDefault(defaultTimeZone);
    }

    @Test
    public void testGetStartTimeAsDate()
    {
        assertEquals(1148039688000L, cdrEvent.getStartTimeAsDate().getTime());
    }

    @Test
    public void testGetStartTimeAsDateWithTimeZone()
    {
        TimeZone tz = TimeZone.getTimeZone("GMT+2");
        assertEquals(1148032488000L, cdrEvent.getStartTimeAsDate(tz).getTime());
    }

    @Test
    public void testBug()
    {
        TimeZone.setDefault(TimeZone.getTimeZone("Europe/Monaco"));

        cdrEvent.setStartTime("2006-05-29 13:17:21");
        assertEquals("Mon May 29 13:17:21 CEST 2006", cdrEvent.getStartTimeAsDate().toString());
    }
}

package org.asteriskjava.manager.event;

import static org.junit.Assert.assertEquals;

import java.util.TimeZone;

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

public class CdrEventTest
{
    CdrEvent cdrEvent;
    TimeZone defaultTimeZone;

    @Before
    public void setUp()
    {
        cdrEvent = new CdrEvent(this);
        cdrEvent.setStartTime("2006-05-19 11:54:48");
        defaultTimeZone = TimeZone.getDefault();
        TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
    }

    @After
    public void tearDown()
    {
        TimeZone.setDefault(defaultTimeZone);
    }

    @Test
    public void testGetStartTimeAsDate()
    {
        assertEquals(1148039688000L, cdrEvent.getStartTimeAsDate().getTime());
    }

    @Test
    public void testGetStartTimeAsDateWithTimeZone()
    {
        TimeZone tz = TimeZone.getTimeZone("GMT+2");
        assertEquals(1148032488000L, cdrEvent.getStartTimeAsDate(tz).getTime());
    }

    @Test
    public void testBug()
    {
        TimeZone.setDefault(TimeZone.getTimeZone("Europe/Monaco"));

        cdrEvent.setStartTime("2006-05-29 13:17:21");
        assertEquals("Mon May 29 13:17:21 CEST 2006", cdrEvent.getStartTimeAsDate().toString());
    }
}

Fix cdr timezone test issue

Fix cdr timezone test issue


public class LazyInit {
	static Object foo;

	// This should be reported
	public static Object getFoo() {
		if (foo == null)
			foo = new Object();
		return foo;
	}

	// This should not be reported
	public synchronized static Object sgetFoo() {
		if (foo == null)
			foo = new Object();
		return foo;
	}
}

public class LazyInit {
	static Object foo;
	static volatile Object bar;

	// This should be reported
	public static Object getFoo() {
		if (foo == null)
			foo = new Object();
		return foo;
	}
	// This should be reported
	public static Object getBar() {
		if (bar == null)
			bar = new Object();
		return bar;
	}

	// This should not be reported
	public synchronized static Object sgetFoo() {
		if (foo == null)
			foo = new Object();
		return foo;
	}
}

Check that volatile statics don't get flagged

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


package org.jgrades.rest;

import org.joda.time.DateTime;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class RestDocsConfig {
    @Bean
    public Docket jGradesRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .pathMapping("/")
                .directModelSubstitute(DateTime.class, Long.class)
                .enableUrlTemplating(true);
    }

}

package org.jgrades.rest;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.LocalTime;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class RestDocsConfig {
    @Bean
    public Docket jGradesRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .pathMapping("/")
                .directModelSubstitute(DateTime.class, Long.class)
                .directModelSubstitute(LocalDate.class, String.class)
                .directModelSubstitute(LocalTime.class, String.class)
                .enableUrlTemplating(true);
    }

}

Improve joda objects model in rest

Improve joda objects model in rest


package in.twizmwaz.cardinal.module.modules.filter.type.old;

import in.twizmwaz.cardinal.module.ModuleCollection;
import in.twizmwaz.cardinal.module.modules.filter.FilterModule;
import in.twizmwaz.cardinal.module.modules.filter.FilterState;
import in.twizmwaz.cardinal.module.modules.filter.parsers.ChildrenFilterParser;

import static in.twizmwaz.cardinal.module.modules.filter.FilterState.*;

public class AllowFilter extends FilterModule {

    private final ModuleCollection<FilterModule> children;

    public AllowFilter(final ChildrenFilterParser parser) {
        super(parser.getName());
        this.children = parser.getChildren();
    }

    @Override
    public FilterState evaluate(final Object... objects) {
        for (FilterModule child : children) {
            if (child.evaluate(objects).equals(DENY)) return DENY;
            if (child.evaluate(objects).equals(ALLOW)) return ALLOW;
        }
        return ABSTAIN;
    }

}

package in.twizmwaz.cardinal.module.modules.filter.type.old;

import in.twizmwaz.cardinal.module.ModuleCollection;
import in.twizmwaz.cardinal.module.modules.filter.FilterModule;
import in.twizmwaz.cardinal.module.modules.filter.FilterState;
import in.twizmwaz.cardinal.module.modules.filter.parsers.ChildrenFilterParser;

import static in.twizmwaz.cardinal.module.modules.filter.FilterState.*;

public class AllowFilter extends FilterModule {

    private final ModuleCollection<FilterModule> children;

    public AllowFilter(final ChildrenFilterParser parser) {
        super(parser.getName());
        this.children = parser.getChildren();
    }

    @Override
    public FilterState evaluate(final Object... objects) {
        boolean abstain = true;
        for (FilterModule child : children) {
            if (child.evaluate(objects).equals(DENY)) return DENY;
            if (!child.evaluate(objects).equals(ABSTAIN)) abstain = false;
        }
        if (abstain) return ABSTAIN;
        return ALLOW;
    }

}

Add abstination back to allow filters

Add abstination back to allow filters


/*
 * Copyright 2015 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

package com.skia;

import org.libsdl.app.SDLActivity;

import android.content.Intent;

public class VisualBenchActivity extends SDLActivity {
  protected String[] getArguments() {
    // intent get intent extras if triggered from the command line
    Intent intent = this.getIntent();
    String flags = intent.getStringExtra("cmdLineFlags");

    return flags.split("\\s+");
  }
}

/*
 * Copyright 2015 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

package com.skia;

import org.libsdl.app.SDLActivity;

import android.content.Intent;

public class VisualBenchActivity extends SDLActivity {
  protected String[] getArguments() {
    String flags = this.getIntent().getStringExtra("cmdLineFlags");
    if (flags != null && !flags.isEmpty()) {
	return flags.split("\\s+");
    }
    return new String[0];
  }
}

VisualBench: Make the Android SDL app start without cmdline arguments

Make the Android SDL VisualBench start even if it is started without
command-line arguments.

Also makes it start when started by pressing the icon.

BUG=skia:
GOLD_TRYBOT_URL= https://gold.skia.org/search2?unt=true&query=source_type%3Dgm&master=false&issue=1573913008

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


package fr.neamar.kiss;

import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.preference.PreferenceManager;
import android.view.Window;
import android.view.WindowManager;

/**
 * Created by neamar on 19/03/17.
 */

public class UiTweaks {
    static void updateThemePrimaryColor(Activity activity) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        String primaryColorOverride = prefs.getString("primary-color", "");

        // Circuit breaker, keep default behavior.
        if (primaryColorOverride.isEmpty()) {
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            int mainColor = Color.parseColor(primaryColorOverride);
            Window window = activity.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

            // Update status bar color
            window.setStatusBarColor(mainColor);

        }
    }
}

package fr.neamar.kiss;

import android.app.ActionBar;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.preference.PreferenceManager;
import android.view.Window;
import android.view.WindowManager;

/**
 * Created by neamar on 19/03/17.
 */

public class UiTweaks {
    static void updateThemePrimaryColor(Activity activity) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        String primaryColorOverride = prefs.getString("primary-color", "");

        // Circuit breaker, keep default behavior.
        if (primaryColorOverride.isEmpty()) {
            return;
        }

        int primaryColor = Color.parseColor(primaryColorOverride);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

            // Update status bar color
            window.setStatusBarColor(primaryColor);
        }

        ActionBar actionBar = activity.getActionBar();
        if(actionBar != null) {
            actionBar.setBackgroundDrawable(new ColorDrawable(primaryColor));
        }
    }
}

Update actionbar color in settings

Update actionbar color in settings


package fixtures.jaxb;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;

@Path("/jaxb")
public class JaxbResource {
    @GET
    public ResponseModel get() {
        return new ResponseModel();
    }

    @POST
    public javax.xml.ws.Response create(PayloadModel payload) {
        return new ResponseModel();
    }
}

package fixtures.jaxb;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

@Path("/jaxb")
public class JaxbResource {
    @GET
    public ResponseModel get() {
        return new ResponseModel();
    }

    @POST
    public Response create(PayloadModel payload) {
        return Response.ok().build();
    }
}

Fix compile error because of bad response type.


package easylog.jee;

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

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target(TYPE)
public @interface Easylog {
}

package easylog.jee;

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

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Easylog {
}

Allow interceptor annotation to be placed on methods.


package com.sequenceiq.cloudbreak.service.upgrade.ccm;

import static com.sequenceiq.cloudbreak.core.flow2.cluster.ccm.upgrade.CcmUpgradeEvent.CCM_UPGRADE_EVENT;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.sequenceiq.cloudbreak.api.endpoint.v4.dto.NameOrCrn;
import com.sequenceiq.cloudbreak.core.flow2.service.ReactorNotifier;
import com.sequenceiq.cloudbreak.domain.stack.Stack;
import com.sequenceiq.cloudbreak.logger.MDCBuilder;
import com.sequenceiq.cloudbreak.reactor.api.event.StackEvent;
import com.sequenceiq.cloudbreak.service.stack.StackService;
import com.sequenceiq.cloudbreak.structuredevent.CloudbreakRestRequestThreadLocalService;
import com.sequenceiq.flow.api.model.FlowIdentifier;

@Service
public class StackCcmUpgradeService {

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

    @Inject
    private CloudbreakRestRequestThreadLocalService restRequestThreadLocalService;

    @Inject
    private StackService stackService;

    @Inject
    private ReactorNotifier reactorNotifier;

    public FlowIdentifier upgradeCcm(NameOrCrn nameOrCrn) {
        Long workspaceId = restRequestThreadLocalService.getRequestedWorkspaceId();
        Stack stack = stackService.getByNameOrCrnInWorkspace(nameOrCrn, workspaceId);
        MDCBuilder.buildMdcContext(stack);
        LOGGER.debug("Ccm upgrade has been initiated for stack {}", nameOrCrn.getNameOrCrn());
        String selector = CCM_UPGRADE_EVENT.event();
        return reactorNotifier.notify(stack.getId(), selector, new StackEvent(selector, stack.getId()));
    }
}

package com.sequenceiq.cloudbreak.service.upgrade.ccm;

import org.springframework.stereotype.Service;

import com.sequenceiq.cloudbreak.api.endpoint.v4.dto.NameOrCrn;
import com.sequenceiq.flow.api.model.FlowIdentifier;

@Service
public class StackCcmUpgradeService {
    public FlowIdentifier upgradeCcm(NameOrCrn nameOrCrn) {
        return null;
    }
}

Revert "CB-14584 triggering ccm upgrade flow through internal call"

This reverts commit a42fe0090ce5d442a8073ef1b63a4440647aceb9.


package com.codicesoftware.plugins.hudson.util;

import hudson.Util;
import hudson.model.ParameterValue;

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

public class SelectorParametersResolver {

    public static String resolve(String text, List<ParameterValue> parameters) {
        if (parameters == null) {
            return text;
        }

        Map<String, String> parametersMap = new HashMap<>();
        for (ParameterValue parameter : parameters) {
            if ((parameter != null) && (parameter.getName() != null) && (parameter.getValue() != null)) {
                parametersMap.put(parameter.getName(), parameter.getValue().toString());
            }
        }

        return Util.replaceMacro(text, parametersMap);
    }
}

package com.codicesoftware.plugins.hudson.util;

import hudson.Util;
import hudson.model.ParameterValue;

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

public class SelectorParametersResolver {

    public static String resolve(String text, List<ParameterValue> parameters) {
        if (parameters == null) {
            return text;
        }

        Map<String, String> parametersMap = new HashMap<>();
        for (ParameterValue parameter : parameters) {
            if ((parameter != null) && (parameter.getName() != null) && (parameter.getValue() != null)) {
                parametersMap.put(parameter.getName(), parameter.getValue().toString());
            }
        }

        return Util.replaceMacro(
            resolveLegacyFormat(text, parametersMap), parametersMap);
    }

    static String resolveLegacyFormat(String text, Map<String, String> parametersMap) {
        String result = text;
        for (Map.Entry<String, String> entry : parametersMap.entrySet()) {
            result = result.replaceAll("%" + entry.getKey() + "%", entry.getValue());
        }
        return result;
    }
}

Make parameter resolution backwards compatible


package io.xchris6041x.devin.playerdata.request;

import java.util.UUID;

import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;

/**
 * @author Christopher Bishop
 */
public abstract class PlayerRequest {

	private UUID from;
	private UUID to;

	public PlayerRequest(Player from, OfflinePlayer to) {
		this.from = from.getUniqueId();
		this.to = to.getUniqueId();
	}

	public abstract String getDescription();

	/**
	 * @return the unique id of
	 */
	public UUID getFromUniqueId() {
		return from;
	}

	/**
	 * @return the uinque id of the player who was sent the request.
	 */
	public UUID getToUniqueId() {
		return to;
	}

}

package io.xchris6041x.devin.playerdata.request;

import java.util.UUID;

import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;

/**
 * @author Christopher Bishop
 */
public abstract class PlayerRequest {

	private UUID sender;
	private UUID receiver;

	public PlayerRequest(Player sender, OfflinePlayer receiver) {
		this.sender = sender.getUniqueId();
		this.receiver = receiver.getUniqueId();
	}

	public abstract String getDescription();

	/**
	 * @return the unique id of the player who sent the request.
	 */
	public UUID getSenderUniqueId() {
		return sender;
	}

	/**
	 * @return the uinque id of the player who received the request.
	 */
	public UUID getReceiverUniqueId() {
		return receiver;
	}

}

Change the name "from" and "to" to "sender" and "receiver".


package io.airlift.http.client.jetty;

import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpClientTransport;
import org.eclipse.jetty.client.HttpRequest;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.util.ssl.SslContextFactory;

import java.net.URI;

import static org.eclipse.jetty.http.HttpHeader.AUTHORIZATION;

class AuthorizationPreservingHttpClient
        extends HttpClient
{
    private static final String PRESERVE_AUTHORIZATION_KEY = "airlift_preserve_authorization";

    public AuthorizationPreservingHttpClient(HttpClientTransport transport, SslContextFactory sslContextFactory)
    {
        super(transport, sslContextFactory);
    }

    @Override
    protected Request copyRequest(HttpRequest oldRequest, URI newUri)
    {
        Request newRequest = super.copyRequest(oldRequest, newUri);

        if (isPreserveAuthorization(oldRequest)) {
            setPreserveAuthorization(newRequest, true);
            for (HttpField field : oldRequest.getHeaders()) {
                if (field.getHeader() == AUTHORIZATION) {
                    newRequest.header(field.getName(), field.getValue());
                }
            }
        }

        return newRequest;
    }

    public static void setPreserveAuthorization(Request request, boolean preserveAuthorization)
    {
        request.attribute(PRESERVE_AUTHORIZATION_KEY, preserveAuthorization);
    }

    private static boolean isPreserveAuthorization(Request request)
    {
        return (boolean) request.getAttributes().get(PRESERVE_AUTHORIZATION_KEY);
    }
}

package io.airlift.http.client.jetty;

import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpClientTransport;
import org.eclipse.jetty.client.HttpRequest;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.util.ssl.SslContextFactory;

import java.net.URI;

import static java.lang.Boolean.TRUE;
import static org.eclipse.jetty.http.HttpHeader.AUTHORIZATION;

class AuthorizationPreservingHttpClient
        extends HttpClient
{
    private static final String PRESERVE_AUTHORIZATION_KEY = "airlift_preserve_authorization";

    public AuthorizationPreservingHttpClient(HttpClientTransport transport, SslContextFactory sslContextFactory)
    {
        super(transport, sslContextFactory);
    }

    @Override
    protected Request copyRequest(HttpRequest oldRequest, URI newUri)
    {
        Request newRequest = super.copyRequest(oldRequest, newUri);

        if (isPreserveAuthorization(oldRequest)) {
            setPreserveAuthorization(newRequest, true);
            for (HttpField field : oldRequest.getHeaders()) {
                if (field.getHeader() == AUTHORIZATION) {
                    newRequest.header(field.getName(), field.getValue());
                }
            }
        }

        return newRequest;
    }

    public static void setPreserveAuthorization(Request request, boolean preserveAuthorization)
    {
        request.attribute(PRESERVE_AUTHORIZATION_KEY, preserveAuthorization);
    }

    private static boolean isPreserveAuthorization(Request request)
    {
        return TRUE.equals(request.getAttributes().get(PRESERVE_AUTHORIZATION_KEY));
    }
}

Allow HTTP client PRESERVE_AUTHORIZATION_KEY to be unset


package cpw.mods.fml.common.event;

import cpw.mods.fml.common.LoaderState.ModState;

public class FMLPostInitializationEvent extends FMLStateEvent
{
    public FMLPostInitializationEvent(Object... data)
    {
        super(data);
    }

    @Override
    public ModState getModState()
    {
        return ModState.POSTINITIALIZED;
    }

}

package cpw.mods.fml.common.event;

import com.google.common.base.Throwables;

import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.LoaderState.ModState;

public class FMLPostInitializationEvent extends FMLStateEvent
{
    public FMLPostInitializationEvent(Object... data)
    {
        super(data);
    }

    @Override
    public ModState getModState()
    {
        return ModState.POSTINITIALIZED;
    }

    public Object buildSoftDependProxy(String modId, String className)
    {
        if (Loader.isModLoaded(modId))
        {
            try
            {
                Class<?> clz = Class.forName(className,true,Loader.instance().getModClassLoader());
                return clz.newInstance();
            }
            catch (Exception e)
            {
                Throwables.propagateIfPossible(e);
                return null;
            }
        }
        return null;
    }
}

Add in a convenience method for getting a class instance based on existence of another Mod. Useful for soft dependencies.


package com.lazerycode.jmeter.configuration;

/**
 * Enum containing the log levels supported by JMeter
 */
public enum LogLevel {
	FATAL_ERROR,
	ERROR,
	WARN,
	INFO,
	DEBUG;

	@Override
	public String toString() {
		return super.toString().toUpperCase();
	}
}

package com.lazerycode.jmeter.configuration;

/**
 * Enum containing the log levels supported by JMeter
 */
public enum LogLevel {
	ERROR,
	WARN,
	INFO,
	DEBUG;

	@Override
	public String toString() {
		return super.toString().toUpperCase();
	}
}

Upgrade to JMeter 3.2 FATAL_ERROR does not exist anymore after migration of JMeter to slf4j


package cs437.som.neighborhood;

import cs437.som.NeightborhoodWidthFunction;

/**
 * Neighborhood width strategy for self-organizing maps that decays the width
 * linearly as the iterations progress.
 *
 * The exact behavior follows the formula:
 *      w_i * (1 - (-t / t_max))
 *  where
 *      w_i   is the initial width of the neighborhood
 *      e     is the base of the natural logarithm
 *      t     is the current iteration
 *      t_max is the maximum expected iteration
 */
public class LinearDecayNeighborhoodWidthFunction implements NeightborhoodWidthFunction {
    private final double initialNeighborhoodWidth;
    private double expectedIterations = 0.0;

    public LinearDecayNeighborhoodWidthFunction(double initialWidth) {
        initialNeighborhoodWidth = initialWidth;
    }

    public void setExpectedIterations(int expectedIterations) {
        this.expectedIterations = expectedIterations;
    }

    public double neighborhoodWidth(int iteration) {
        return initialNeighborhoodWidth * (1.0 - (iteration / expectedIterations));
    }

    @Override
    public String toString() {
        return "LinearDecayNeighborhoodWidthFunction";
    }
}

package cs437.som.neighborhood;

import cs437.som.NeightborhoodWidthFunction;

/**
 * Neighborhood width strategy for self-organizing maps that decays the width
 * linearly as the iterations progress.
 *
 * The exact behavior follows the formula:
 *      w_i * (1 - (-t / t_max))
 *  where
 *      w_i   is the initial width of the neighborhood
 *      t     is the current iteration
 *      t_max is the maximum expected iteration
 */
public class LinearDecayNeighborhoodWidthFunction implements NeightborhoodWidthFunction {
    private final double initialNeighborhoodWidth;
    private double expectedIterations = 0.0;

    public LinearDecayNeighborhoodWidthFunction(double initialWidth) {
        initialNeighborhoodWidth = initialWidth;
    }

    public void setExpectedIterations(int expectedIterations) {
        this.expectedIterations = expectedIterations;
    }

    public double neighborhoodWidth(int iteration) {
        return initialNeighborhoodWidth * (1.0 - (iteration / expectedIterations));
    }

    @Override
    public String toString() {
        return "LinearDecayNeighborhoodWidthFunction";
    }
}

Fix lin. decay NW comment.

Fix lin. decay NW comment.


/*++

NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury. All rights reserved.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

--*/

package com.nasmlanguage.psi;

import com.intellij.psi.PsiNameIdentifierOwner;

public interface NASMNamedElement extends PsiNameIdentifierOwner {
}

/*++

NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury

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

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

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

--*/

package com.nasmlanguage.psi;

import com.intellij.psi.PsiNameIdentifierOwner;

public interface NASMNamedElement extends PsiNameIdentifierOwner {
}

Update copyright notice with MIT license


// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)

package org.xbill.DNS;

import java.io.*;

/**
 * An exception thrown when a DNS message is invalid.
 *
 * @author Brian Wellington
 */

public class WireParseException extends IOException {

public
WireParseException() {
	super();
}

public
WireParseException(String s) {
	super(s);
}

}

// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)

package org.xbill.DNS;

import java.io.*;

/**
 * An exception thrown when a DNS message is invalid.
 *
 * @author Brian Wellington
 */

public class WireParseException extends IOException {

public
WireParseException() {
	super();
}

public
WireParseException(String s) {
	super(s);
}

public
WireParseException(String s, Throwable cause) {
	super(s, cause);
}

}

Add a constructor that takes a cause Exception.

git-svn-id: fcb33a7ee5ec38b96370833547f088a4e742b712@1638 c76caeb1-94fd-44dd-870f-0c9d92034fc1


package org.apereo.cas.web.report;

import org.springframework.cloud.bus.BusProperties;
import org.springframework.cloud.config.server.config.ConfigServerProperties;

import java.util.Map;

/**
 * This is {@link ControllerUtils}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
public final class ControllerUtils {
    private ControllerUtils() {
    }

    /**
     * Configure model map for config server cloud bus endpoints.
     *
     * @param busProperties          the bus properties
     * @param configServerProperties the config server properties
     * @param path                   the path
     * @param model                  the model
     */
    public static void configureModelMapForConfigServerCloudBusEndpoints(final BusProperties busProperties,
                                                                         final ConfigServerProperties configServerProperties,
                                                                         final String path,
                                                                         final Map model) {
        if (busProperties != null && busProperties.isEnabled()) {
            model.put("refreshEndpoint", path + configServerProperties.getPrefix() + "/cas/bus/refresh");
            model.put("refreshMethod", "GET");
        } else {
            model.put("refreshEndpoint", path + "/status/refresh");
            model.put("refreshMethod", "POST");
        }
    }
}

package org.apereo.cas.web.report;

import org.springframework.cloud.bus.BusProperties;
import org.springframework.cloud.config.server.config.ConfigServerProperties;

import java.util.Map;

/**
 * This is {@link ControllerUtils}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
final class ControllerUtils {
    private ControllerUtils() {
    }

    /**
     * Configure model map for config server cloud bus endpoints.
     *
     * @param busProperties          the bus properties
     * @param configServerProperties the config server properties
     * @param path                   the path
     * @param model                  the model
     */
    public static void configureModelMapForConfigServerCloudBusEndpoints(final BusProperties busProperties,
                                                                         final ConfigServerProperties configServerProperties,
                                                                         final String path,
                                                                         final Map model) {
        if (busProperties != null && busProperties.isEnabled()) {
            model.put("refreshEndpoint", path + configServerProperties.getPrefix() + "/cas/bus/refresh");
            model.put("refreshMethod", "GET");
        } else {
            model.put("refreshEndpoint", path + "/status/refresh");
            model.put("refreshMethod", "POST");
        }
    }
}

Clean up duplicate code in controllers

Clean up duplicate code in controllers


/*
 * oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
 *
 * Copyright (c) 2014, Gluu
 */

/**
 *
 */
package org.gluu.oxtrust.model;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

/**
 * @author "Oleksiy Tataryn"
 *
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class RegistrationConfiguration {

	private List<String> additionalAttributes;

	private boolean isCaptchaDisabled;

    public List<String> getAdditionalAttributes() {
        return additionalAttributes;
    }

    public void setAdditionalAttributes(List<String> additionalAttributes) {
        this.additionalAttributes = additionalAttributes;
    }

    public boolean isCaptchaDisabled() {
        return isCaptchaDisabled;
    }

    public void setCaptchaDisabled(boolean captchaDisabled) {
        isCaptchaDisabled = captchaDisabled;
    }

}

/*
 * oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
 *
 * Copyright (c) 2014, Gluu
 */

/**
 *
 */
package org.gluu.oxtrust.model;

import java.io.Serializable;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

/**
 * @author "Oleksiy Tataryn"
 *
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class RegistrationConfiguration implements Serializable {

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

	/**
	 *
	 */

	private List<String> additionalAttributes;

	private boolean isCaptchaDisabled;

    public List<String> getAdditionalAttributes() {
        return additionalAttributes;
    }

    public void setAdditionalAttributes(List<String> additionalAttributes) {
        this.additionalAttributes = additionalAttributes;
    }

    public boolean isCaptchaDisabled() {
        return isCaptchaDisabled;
    }

    public void setCaptchaDisabled(boolean captchaDisabled) {
        isCaptchaDisabled = captchaDisabled;
    }

}

Fix serialization issue for oxRegistration class


package alien4cloud.webconfiguration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class StaticResourcesConfiguration extends WebMvcConfigurerAdapter {
    @Value("file:///${directories.alien}/${directories.csar_repository}/")
    private String toscaRepo;
    @Value("file:///${directories.alien}/work/plugins/ui/")
    private String pluginsUi;

    public final static String PLUGIN_STATIC_ENDPOINT = "/static/plugins/";

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/tosca/**").addResourceLocations(toscaRepo);
        registry.addResourceHandler(PLUGIN_STATIC_ENDPOINT + "**").addResourceLocations(pluginsUi);
    }
}

package alien4cloud.webconfiguration;

import java.nio.file.Paths;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Slf4j
@Configuration
public class StaticResourcesConfiguration extends WebMvcConfigurerAdapter {
    @Value("${directories.alien}/${directories.csar_repository}/")
    private String toscaRepo;
    @Value("${directories.alien}/work/plugins/ui/")
    private String pluginsUi;

    public final static String PLUGIN_STATIC_ENDPOINT = "/static/plugins/";

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String prefix = "file:///";
        // resource locations must be full path and not relatives
        String absToscaRepo = prefix.concat(Paths.get(toscaRepo).toAbsolutePath().toString()).concat("/");
        String absPluginUi = prefix.concat(Paths.get(pluginsUi).toAbsolutePath().toString()).concat("/");
        log.info("Serving {} as tosca repo content.", absToscaRepo);
        log.info("Serving {} as plugin ui content.", absPluginUi);
        registry.addResourceHandler("/static/tosca/**").addResourceLocations(absToscaRepo);
        registry.addResourceHandler(PLUGIN_STATIC_ENDPOINT + "**").addResourceLocations(absPluginUi);
    }
}

Fix an issue causing alien4cloud static resources (csar and plugin) to be unavailable when main directory was expressed using relative paths.


package com.hypirion.smallex;

import java.io.Reader;
import java.util.Iterator;

import com.hypirion.smallex.Item;

public class SMLXLexer implements Iterator<Item> {
    private Reader reader;

    public SMLXLexer(Reader reader) {
        this.reader = reader;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }

    @Override
    public Item next() {
        return null;
    }

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

Add in package header to lexer.

Add in package header to lexer.


package org.jenkinsci.plugins.github.status.sources;

import hudson.model.Run;
import hudson.model.TaskListener;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.runners.MockitoJUnitRunner;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.when;

/**
 * @author pupssman (Kalinin Ivan)
 */
@RunWith(MockitoJUnitRunner.class)
public class BuildRefBackrefSourceTest {

    @Rule
    public MockitoRule mockitoRule = MockitoJUnit.rule();

    @Mock(answer = Answers.RETURNS_MOCKS)
    private Run run;

    @Mock(answer = Answers.RETURNS_MOCKS)
    private TaskListener listener;

    @Test
    public void shouldReturnRunAbsoluteUrl() throws Exception {
        when(run.getAbsoluteUrl()).thenReturn("ABSOLUTE_URL");

        String result = new BuildRefBackrefSource().get(run, listener);
        assertThat("state", result, is("ABSOLUTE_URL"));
    }

}

package org.jenkinsci.plugins.github.status.sources;

import hudson.model.FreeStyleProject;
import hudson.model.Run;
import hudson.model.TaskListener;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.runners.MockitoJUnitRunner;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.when;

/**
 * @author pupssman (Kalinin Ivan)
 */
@RunWith(MockitoJUnitRunner.class)
public class BuildRefBackrefSourceTest {

    @Rule
    public JenkinsRule jenkinsRule = new JenkinsRule();

    @Mock(answer = Answers.RETURNS_MOCKS)
    private TaskListener listener;

    @Test
    /**
     * Should've used mocked Run, but getAbsoluteUrl is final.
     *
     * @throws Exception
     */
    public void shouldReturnRunAbsoluteUrl() throws Exception {
        Run<?, ?> run = jenkinsRule.buildAndAssertSuccess(jenkinsRule.createFreeStyleProject());

        String result = new BuildRefBackrefSource().get(run, listener);
        assertThat("state", result, is(run.getAbsoluteUrl()));
    }

}

Change test to using JenkinsRule

Change test to using JenkinsRule


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

package com.google.devtools.cdbg.debuglets.java;

/**
 * Defines the version of the Java Cloud Debugger agent.
 */
public final class GcpDebugletVersion {
  /**
   * Major version of the debugger.

   * All agents of the same major version are compatible with each other. In other words an
   * application can mix different agents with the same major version within the same debuggee.
   */
  public static final int MAJOR_VERSION = 2;

  /**
   * Minor version of the agent.
   */
  public static final int MINOR_VERSION = 14;

  /**
   * Debugger agent version string in the format of MAJOR.MINOR.
   */
  public static final String VERSION = String.format("%d.%d", MAJOR_VERSION, MINOR_VERSION);

  /**
   * Main function to print the version string.
   */
  public static void main(String[] args) {
    System.out.println(VERSION);
  }
}

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

package com.google.devtools.cdbg.debuglets.java;

/**
 * Defines the version of the Java Cloud Debugger agent.
 */
public final class GcpDebugletVersion {
  /**
   * Major version of the debugger.

   * All agents of the same major version are compatible with each other. In other words an
   * application can mix different agents with the same major version within the same debuggee.
   */
  public static final int MAJOR_VERSION = 2;

  /**
   * Minor version of the agent.
   */
  public static final int MINOR_VERSION = 15;

  /**
   * Debugger agent version string in the format of MAJOR.MINOR.
   */
  public static final String VERSION = String.format("%d.%d", MAJOR_VERSION, MINOR_VERSION);

  /**
   * Main function to print the version string.
   */
  public static void main(String[] args) {
    System.out.println(VERSION);
  }
}

Increment minor version to 2.15 to prepare for a new release.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=159890586


package com.stacktoheap.go.docker.Commands.BuildCommands;

import com.stacktoheap.go.docker.Commands.DockerCommand;
import com.stacktoheap.go.docker.Config;
import com.stacktoheap.go.docker.Context;
import org.apache.commons.io.FilenameUtils;

public class DockerBuildCommand extends DockerCommand {

    public DockerBuildCommand(Context taskContext, Config taskConfig) {
        super(taskContext, taskConfig);
    }

    @Override
    public void buildCommand(Context taskContext, Config taskConfig) {
        command.add("docker");
        command.add("build");

        command.add("-t");
        command.add(getTemporaryImageTag(taskContext));

        String dockerFilePath = FilenameUtils.concat(taskContext.getWorkingDir(), taskConfig.dockerFile);
        command.add(dockerFilePath);
    }

    @Override
    protected boolean shouldRun(Context taskContext, Config taskConfig) {
        return taskConfig.isDockerBuild;
    }
}

package com.stacktoheap.go.docker.Commands.BuildCommands;

import com.stacktoheap.go.docker.Commands.DockerCommand;
import com.stacktoheap.go.docker.Config;
import com.stacktoheap.go.docker.Context;
import org.apache.commons.io.FilenameUtils;

public class DockerBuildCommand extends DockerCommand {

    public DockerBuildCommand(Context taskContext, Config taskConfig) {
        super(taskContext, taskConfig);
    }

    @Override
    public void buildCommand(Context taskContext, Config taskConfig) {
        command.add("build");

        command.add("-t");
        command.add(getTemporaryImageTag(taskContext));

        String dockerFilePath = FilenameUtils.concat(taskContext.getWorkingDir(), taskConfig.dockerFile);
        command.add(dockerFilePath);
    }

    @Override
    protected boolean shouldRun(Context taskContext, Config taskConfig) {
        return taskConfig.isDockerBuild;
    }
}

Remove redundant "docker" string in the command

The base DockerCommand class adds "docker" to the start for all command.
DockerBuildCommand also adds a superfluous "docker" creating the command "docker
docker build", which naturally fails.


/**
 *
 */
package com.trendrr.oss.concurrent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Simple threadsafe lazy init object.
 *
 * usage:
 *
 * LazyInit<MyObject> obj = new LazyInit<MyObject>() {
 * 	@Override
 * 	public MyObject init() {
 * 		return new MyObject();
 * 	}
 * }
 *
 *
 * MyObject my = obj.get();
 *
 * @author Dustin Norlander
 * @created Aug 31, 2011
 *
 */
public abstract class LazyInitObject<T> {

	protected Log log = LogFactory.getLog(LazyInitObject.class);

	T object;
	LazyInit lock = new LazyInit();

	public abstract T init();

	public T get() {
		if (lock.start()) {
			try {
				this.object = this.init();
			} finally {
				lock.end();
			}
		}
		return object;
	}

	/**
	 * will reset this object to initialize again (on the next get() method call)
	 */
	public void reset() {
		lock.reset();
	}
}

/**
 *
 */
package com.trendrr.oss.concurrent;

import java.util.concurrent.atomic.AtomicReference;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Simple threadsafe lazy init object.
 *
 * usage:
 *
 * LazyInit<MyObject> obj = new LazyInit<MyObject>() {
 * 	@Override
 * 	public MyObject init() {
 * 		return new MyObject();
 * 	}
 * }
 *
 *
 * MyObject my = obj.get();
 *
 * @author Dustin Norlander
 * @created Aug 31, 2011
 *
 */
public abstract class LazyInitObject<T> {

	protected Log log = LogFactory.getLog(LazyInitObject.class);

	AtomicReference<T> object;
	LazyInit lock = new LazyInit();

	public abstract T init();

	public T get() {
		if (lock.start()) {
			try {
				this.object.set(this.init());
			} finally {
				lock.end();
			}
		}
		return object.get();
	}

	/**
	 * will reset this object to initialize again (on the next get() method call)
	 */
	public void reset() {
		lock.reset();
	}

	/**
	 * atomically sets the reference and sets the init to not run.
	 * @param object
	 */
	public void set(T object) {
		lock.start();
		try {
			this.object.set(object);
		} finally {
			lock.end();
		}
	}
}

Add set to lazy init object, to bypass init code if needed


package com.anprosit.android.dagger.factory;

import android.content.Context;
import android.media.MediaPlayer;

/**
 * Created by Hirofumi Nakagawa on 13/09/06.
 */
public class MediaPlayerFactory {
	public MediaPlayer create(Context context, int resId) {
		return MediaPlayer.create(context, resId);
	}

	public MediaPlayer create() {
		return new MediaPlayer();
	}
}

package com.anprosit.android.dagger.factory;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;

/**
 * @author hnakagawa
 */
public class MediaPlayerFactory {
	public MediaPlayer create(Context context, int resId) {
		return MediaPlayer.create(context, resId);
	}

	public MediaPlayer create(Context context, Uri uri) {
		return MediaPlayer.create(context, uri);
	}

	public MediaPlayer create() {
		return new MediaPlayer();
	}
}

Add factory method for media player

Add factory method for media player


package reborncore.common;

import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import reborncore.RebornCore;

public abstract class BaseTileBlock extends Block implements ITileEntityProvider
{
	protected BaseTileBlock(Material materialIn)
	{
		super(materialIn);
		RebornCore.jsonDestroyer.registerObject(this);
	}

	public int getRenderType()
	{
		return 3;
	}

	@Override
	public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
	{
		super.breakBlock(worldIn, pos, state);
		worldIn.removeTileEntity(pos);
	}
}

package reborncore.common;

import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import reborncore.RebornCore;

public abstract class BaseTileBlock extends Block implements ITileEntityProvider
{
	protected BaseTileBlock(Material materialIn)
	{
		super(materialIn);
		RebornCore.jsonDestroyer.registerObject(this);
		setHardness(1F);
	}

	public int getRenderType()
	{
		return 3;
	}

	@Override
	public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
	{
		super.breakBlock(worldIn, pos, state);
		worldIn.removeTileEntity(pos);
	}
}

Add a hardness to the base block

Add a hardness to the base block


package utask.model.util;

import utask.commons.exceptions.IllegalValueException;
import utask.model.ReadOnlyUTask;
import utask.model.UTask;
import utask.model.tag.UniqueTagList;
import utask.model.task.Deadline;
import utask.model.task.EventTask;
import utask.model.task.Frequency;
import utask.model.task.Name;
import utask.model.task.Task;
import utask.model.task.Timestamp;
import utask.model.task.UniqueTaskList.DuplicateTaskException;

public class SampleDataUtil {
    public static Task[] getSamplePersons() {
        try {
            return new Task[] {
                new EventTask(new Name("My first task"), new Deadline("010117"), new Timestamp("0900 to 1000"),
                new Frequency("-"),
                new UniqueTagList("important"))
            };
        } catch (IllegalValueException e) {
            throw new AssertionError("sample data cannot be invalid", e);
        }
    }

    public static ReadOnlyUTask getSampleAddressBook() {
        try {
            UTask sampleAB = new UTask();
            for (Task sampleTask : getSamplePersons()) {
                sampleAB.addTask(sampleTask);
            }
            return sampleAB;
        } catch (DuplicateTaskException e) {
            throw new AssertionError("sample data cannot contain duplicate persons", e);
        }
    }
}

package utask.model.util;

import utask.commons.exceptions.IllegalValueException;
import utask.model.ReadOnlyUTask;
import utask.model.UTask;
import utask.model.tag.UniqueTagList;
import utask.model.task.Deadline;
import utask.model.task.EventTask;
import utask.model.task.Frequency;
import utask.model.task.IsCompleted;
import utask.model.task.Name;
import utask.model.task.Task;
import utask.model.task.Timestamp;
import utask.model.task.UniqueTaskList.DuplicateTaskException;

public class SampleDataUtil {
    public static Task[] getSamplePersons() {
        try {
            return new Task[] {
                new EventTask(new Name("My first task"), new Deadline("010117"), new Timestamp("0900 to 1000"),
                new Frequency("-"),
                new UniqueTagList("important"),
                new IsCompleted("no"))
            };
        } catch (IllegalValueException e) {
            throw new AssertionError("sample data cannot be invalid", e);
        }
    }

    public static ReadOnlyUTask getSampleAddressBook() {
        try {
            UTask sampleAB = new UTask();
            for (Task sampleTask : getSamplePersons()) {
                sampleAB.addTask(sampleTask);
            }
            return sampleAB;
        } catch (DuplicateTaskException e) {
            throw new AssertionError("sample data cannot contain duplicate persons", e);
        }
    }
}

Update SampleDateUtil to include isCompleted during Task creation


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

import io.reinert.requestor.Response;

/**
 * DoneCallback with optional access to the response.
 *
 * @param <T> Type of the response payload
 */
public abstract class DoneCallback<T> implements io.reinert.gdeferred.DoneCallback<T> {

    @Override
    public void onDone(T result) {
    }

    public void onDone(Response<T> response) {
        onDone(response.getPayload());
    }
}

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

import io.reinert.requestor.RawResponseImpl;
import io.reinert.requestor.Response;

/**
 * DoneCallback with optional access to the response.
 *
 * @param <T> Type of the response payload
 */
public abstract class DoneCallback<T> implements io.reinert.gdeferred.DoneCallback<T> {

    @Override
    public void onDone(T result) {
    }

    /**
     * If you want to access the Response attributes, then override this method.
     *
     * @param response  the HTTP Response returned from the Request.
     */
    @SuppressWarnings("unchecked")
    public void onDone(Response<T> response) {
        if (response instanceof RawResponseImpl) {
            onDone((T) response);
            return;
        }

        onDone(response.getPayload());
    }
}

Fix callback cast of SerializeResponse

Fix callback cast of SerializeResponse


package org.skyve.metadata.view;

import javax.xml.bind.annotation.XmlType;

import org.skyve.impl.util.XMLMetaData;

public interface TextOutput {
	Boolean getEscape();

	@XmlType(namespace = XMLMetaData.VIEW_NAMESPACE)
	public static enum Sanitisation {
		// Note the values are ordered from least restrictive to most restrictive so we can compare the ordinals

		// No sanitisation applied
		none,
		// CSS too
		relaxed,
		// Formatting tags, structural tags, links and images
		basic,
		// Formatting tags only
		simple,
		// Only Text - no HTML
		text
	}

	Sanitisation getSanitise();
}

package org.skyve.metadata.view;

import javax.xml.bind.annotation.XmlType;

import org.skyve.impl.util.XMLMetaData;

public interface TextOutput {
	Boolean getEscape();

	@XmlType(namespace = XMLMetaData.VIEW_NAMESPACE)
	public static enum Sanitisation {
		// Note the values are ordered from least restrictive to most restrictive so we can compare the ordinals

		// No sanitisation applied
		none,
		// Formatting tags, structural tags, links and images and CSS too
		relaxed,
		// Formatting tags, structural tags, links and images
		basic,
		// Formatting tags only
		simple,
		// Only Text - no HTML
		text
	}

	Sanitisation getSanitise();
}

Change comment on Sanitisation enum to be more clearer.


/**
 * Project RSA Algorithm.
 * Copyright Michał Szczygieł.
 * Created at Feb 24, 2014.
 */

/**
 * TODO COMMENTS MISSING!
 *
 * @author Michał Szczygieł <michal.szczygiel@wp.pl>
 *
 */
public interface Encryption {

}

import java.math.BigInteger;

/**
 * Project RSA Algorithm.
 * Copyright Michał Szczygieł.
 * Created at Feb 24, 2014.
 */

/**
 * This interface describe the basic operation with encryption algorithm.
 *
 * @author Michał Szczygieł <michal.szczygiel@wp.pl>
 *
 */
public interface Encryption {

    /**
     * This method makes operation to achieve decrypted message.
     *
     * @param valueToDecrypt
     *            The value of which will be performed the decryption process.
     * @return Decrypted value.
     */
    public BigInteger decrypt(BigInteger valueToDecrypt);

    /**
     * This method makes operation to create encrypted message.
     *
     * @param valueToEncrypt
     *            The value of which will be performed the encryption process
     * @return Encrypted value.
     */
    public BigInteger encrypt(BigInteger valueToEncrypt);

}

Define interface for encryption operations


// BSD License (http://lemurproject.org/galago-license)
package org.lemurproject.galago.core.index;

import org.lemurproject.galago.core.retrieval.iterator.BaseIterator;

import java.io.IOException;

/**
 * Each iterator from an index has an extra two methods,
 * getValueString() and nextKey(), that allows the data from
 * the index to be easily printed.  DumpIndex uses this functionality
 * to dump the contents of any Galago index.
 *
 * (2/22/2011, irmarc): Refactored into the index package to indicate this is functionality
 *                      that a disk-based iterator should have.
 *
 * @author trevor, irmarc
 */
public interface KeyIterator extends Comparable<KeyIterator> {

  // moves iterator to some particular key
  public boolean findKey(byte[] key) throws IOException;

  // moves iterator to a particular key (forward direction only)
  public boolean skipToKey(byte[] key) throws IOException;

  // moves iterator to the next key
  public boolean nextKey() throws IOException;

  // true if the iterator has moved past the last key
  public boolean isDone();

  // resets iterator to the first key
  public void reset() throws IOException;

  // Access to key data
  public byte[] getKey() throws IOException;
  public String getKeyString() throws IOException;

  // Access to the key's value. (Not all may be implemented)
  public byte[] getValueBytes() throws IOException;
  public String getValueString() throws IOException;
  public BaseIterator getValueIterator() throws IOException;
}

// BSD License (http://lemurproject.org/galago-license)
package org.lemurproject.galago.core.index;

import org.lemurproject.galago.core.retrieval.iterator.BaseIterator;
import org.lemurproject.galago.utility.ByteUtil;

import java.io.IOException;

/**
 * Each iterator from an index has an extra two methods,
 * getValueString() and nextKey(), that allows the data from
 * the index to be easily printed.  DumpIndex uses this functionality
 * to dump the contents of any Galago index.
 *
 * (2/22/2011, irmarc): Refactored into the index package to indicate this is functionality
 *                      that a disk-based iterator should have.
 *
 * @author trevor, irmarc
 */
public interface KeyIterator extends Comparable<KeyIterator> {

  // moves iterator to some particular key
  public boolean findKey(byte[] key) throws IOException;

  default boolean findKey(String key) throws IOException {
    return findKey(ByteUtil.fromString(key));
  }

  // moves iterator to a particular key (forward direction only)
  public boolean skipToKey(byte[] key) throws IOException;

  // moves iterator to the next key
  public boolean nextKey() throws IOException;

  // true if the iterator has moved past the last key
  public boolean isDone();

  // resets iterator to the first key
  public void reset() throws IOException;

  // Access to key data
  public byte[] getKey() throws IOException;
  public String getKeyString() throws IOException;

  // Access to the key's value. (Not all may be implemented)
  public byte[] getValueBytes() throws IOException;
  public String getValueString() throws IOException;
  public BaseIterator getValueIterator() throws IOException;
}

Add default method for finding strings rather than byte[]