package com.elmakers.mine.bukkit.magicworlds.listener;

import com.elmakers.mine.bukkit.magicworlds.MagicWorld;
import com.elmakers.mine.bukkit.magicworlds.MagicWorldsController;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.plugin.Plugin;

public class EntitySpawnListener implements Listener
{
    private final MagicWorldsController controller;

	public EntitySpawnListener(final MagicWorldsController controller)
	{
        this.controller = controller;
	}

    @EventHandler(priority = EventPriority.LOW)
    public void onEntitySpawn(CreatureSpawnEvent event) {
        if (event.isCancelled()) {
            return;
        }
        if (event.getSpawnReason() == SpawnReason.CUSTOM || event.getSpawnReason() == SpawnReason.DEFAULT) return;

        MagicWorld magicWorld = controller.getWorld(event.getLocation().getWorld().getName());
        if (magicWorld == null) return;

        LivingEntity entity = event.getEntity();
        Plugin plugin = controller.getPlugin();
        LivingEntity replace =  magicWorld.processEntitySpawn(plugin, entity);
        if (replace != null) {
        	entity.setHealth(0);
            event.setCancelled(true);
    	}
    }
}

package com.elmakers.mine.bukkit.magicworlds.listener;

import com.elmakers.mine.bukkit.magicworlds.MagicWorld;
import com.elmakers.mine.bukkit.magicworlds.MagicWorldsController;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.plugin.Plugin;

public class EntitySpawnListener implements Listener
{
    private final MagicWorldsController controller;

	public EntitySpawnListener(final MagicWorldsController controller)
	{
        this.controller = controller;
	}

    @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
    public void onEntitySpawn(CreatureSpawnEvent event) {
        if (event.getSpawnReason() == SpawnReason.CUSTOM || event.getSpawnReason() == SpawnReason.DEFAULT) return;

        MagicWorld magicWorld = controller.getWorld(event.getLocation().getWorld().getName());
        if (magicWorld == null) return;

        LivingEntity entity = event.getEntity();
        Plugin plugin = controller.getPlugin();
        LivingEntity replace =  magicWorld.processEntitySpawn(plugin, entity);
        if (replace != null) {
        	entity.setHealth(0);
            event.setCancelled(true);
    	}
    }
}

Change priority to ignore cancelled spawn events


/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 sample.camel;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * A bean that returns a message when you call the {@link #saySomething()} method.
 * <p/>
 * Uses <tt>@Component("myBean")</tt> to register this bean with the name <tt>myBean</tt>
 * that we use in the Camel route to lookup this bean.
 */
@Component("myBean")
public class SampleBean {

    @Value("greeting")
    private String say;

    public String saySomething() {
        return say;
    }

}

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 sample.camel;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * A bean that returns a message when you call the {@link #saySomething()} method.
 * <p/>
 * Uses <tt>@Component("myBean")</tt> to register this bean with the name <tt>myBean</tt>
 * that we use in the Camel route to lookup this bean.
 */
@Component("myBean")
public class SampleBean {

    @Value("${greeting}")
    private String say;

    public String saySomething() {
        return say;
    }

}

CAMEL-9723: Move spring-boot-starter-sample to examples so we can collapse the camel-spring-boot-starter module


package de.flux.playground.deckcompare.analyze;

import de.flux.playground.deckcompare.dto.Card;

public final class CardConflictAnalyzer {

    public static boolean conflicted(Card card, Card otherCard) {

        boolean isConflicted = false;

        if (card.equals(otherCard)) {
            int overallQunatity = card.getQty() + otherCard.getQty();
            isConflicted = overallQunatity > 3;
        }

        return isConflicted;
    }

}

package de.flux.playground.deckcompare.analyze;

import de.flux.playground.deckcompare.dto.Card;

public final class CardConflictAnalyzer {

    private CardConflictAnalyzer() {
    }

    public static boolean conflicted(Card card, Card otherCard) {

        boolean isConflicted = false;

        if (card.equals(otherCard)) {
            int overallQunatity = card.getQty() + otherCard.getQty();
            isConflicted = overallQunatity > 3;
        }

        return isConflicted;
    }

}

Add private constructor to prevent instantiation


package com.github.games647.lagmonitor.listeners;

import com.github.games647.lagmonitor.LagMonitor;
import java.io.IOException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.util.List;
import java.util.logging.Level;

import org.bukkit.Bukkit;

public class BlockingConnectionSelector extends ProxySelector {

    private final LagMonitor plugin;
    private final ProxySelector oldProxySelector;

    public BlockingConnectionSelector(LagMonitor plugin, ProxySelector oldProxySelector) {
        this.plugin = plugin;
        this.oldProxySelector = oldProxySelector;
    }

    @Override
    public List<Proxy> select(URI uri) {
        if (Bukkit.isPrimaryThread()) {
            plugin.getLogger().log(Level.WARNING
                    , "Server is performing a blocking socket connection {0} on the main thread"
                    , new Object[]{uri});
            plugin.getLogger().log(Level.WARNING, "", new Throwable());
        }

        return oldProxySelector.select(uri);
    }

    @Override
    public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
        oldProxySelector.connectFailed(uri, sa, ioe);
    }

    public ProxySelector getOldProxySelector() {
        return oldProxySelector;
    }
}

package com.github.games647.lagmonitor.listeners;

import com.github.games647.lagmonitor.LagMonitor;

import java.io.IOException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.util.List;
import java.util.logging.Level;

import org.bukkit.Bukkit;

public class BlockingConnectionSelector extends ProxySelector {

    private final LagMonitor plugin;
    private final ProxySelector oldProxySelector;

    public BlockingConnectionSelector(LagMonitor plugin, ProxySelector oldProxySelector) {
        this.plugin = plugin;
        this.oldProxySelector = oldProxySelector;
    }

    @Override
    public List<Proxy> select(URI uri) {
        if (!uri.getScheme().startsWith("http") && Bukkit.isPrimaryThread()) {
            plugin.getLogger().log(Level.WARNING
                    , "Server is performing a blocking socket connection {0} on the main thread"
                    , new Object[]{uri});
            plugin.getLogger().log(Level.WARNING, "", new Throwable());
        }

        return oldProxySelector.select(uri);
    }

    @Override
    public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
        oldProxySelector.connectFailed(uri, sa, ioe);
    }

    public ProxySelector getOldProxySelector() {
        return oldProxySelector;
    }
}

Fix showing duplicate http blocking messages, because a http connection

is also a socket connection


package org.xcolab.view.pages.contestmanagement.beans;

import org.hibernate.validator.constraints.NotBlank;

import java.io.Serializable;

public class BatchRegisterBean implements Serializable {

    @NotBlank
    private Boolean asGuests;

    @NotBlank
    private String batchText;

    public String getBatchText() {
        return batchText;
    }

    public void setBatchText(String batchText) {
        this.batchText = batchText;
    }

    public Boolean getAsGuests() {
        return asGuests;
    }

    public void setAsGuest(Boolean asGuests) {
        this.asGuests = asGuests;
    }

    @Override
    public String toString() {
        return "BatchRegisterBean [batchText='" + batchText + "', asGuests='" + asGuests.toString() + "']";
    }

}

package org.xcolab.view.pages.contestmanagement.beans;

import org.hibernate.validator.constraints.NotBlank;

import java.io.Serializable;

public class BatchRegisterBean implements Serializable {

    @NotBlank
    private boolean asGuests;

    @NotBlank
    private String batchText;

    public String getBatchText() {
        return batchText;
    }

    public void setBatchText(String batchText) {
        this.batchText = batchText;
    }

    public boolean getAsGuests() {
        return asGuests;
    }

    public void setAsGuest(boolean asGuests) {
        this.asGuests = asGuests;
    }

    @Override
    public String toString() {
        return "BatchRegisterBean [batchText='" + batchText + "', asGuests='" + String.valueOf(asGuests) + "']";
    }

}

Fix null pointer error for asGuests in batchRegister


package com.rejasupotaro.android.kvs.internal;

import org.junit.Test;

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

public class StringUtilsTest {
    @Test
    public void testCapitalize() {
        assertThat(StringUtils.capitalize("username")).isEqualTo("Username");
    }
}

package com.rejasupotaro.android.kvs.internal;

import org.junit.Test;

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

public class StringUtilsTest {
    @Test
    public void testCapitalize() {
        assertThat(StringUtils.capitalize("username")).isEqualTo("Username");
    }

    @Test
    public void testIsEmpty() {
        assertThat(StringUtils.isEmpty(null)).isTrue();
        assertThat(StringUtils.isEmpty("")).isTrue();
        assertThat(StringUtils.isEmpty("hoge")).isFalse();
    }

}

Add a test for isEmpty.

Add a test for isEmpty.


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

package com.wdullaer.materialdatetimepicker;

import android.content.Context;
import android.util.AttributeSet;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Button;
import android.widget.TextView;

/**
 * Fake Button class, used so TextViews can announce themselves as Buttons, for accessibility.
 */
public class AccessibleTextView extends TextView {

    public AccessibleTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
        super.onInitializeAccessibilityEvent(event);
        event.setClassName(Button.class.getName());
    }

    @Override
    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
        super.onInitializeAccessibilityNodeInfo(info);
        info.setClassName(Button.class.getName());
    }
}

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

package com.wdullaer.materialdatetimepicker;

import android.content.Context;
import android.util.AttributeSet;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Button;

/**
 * Fake Button class, used so TextViews can announce themselves as Buttons, for accessibility.
 */
public class AccessibleTextView extends androidx.appcompat.widget.AppCompatTextView {

    public AccessibleTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
        super.onInitializeAccessibilityEvent(event);
        event.setClassName(Button.class.getName());
    }

    @Override
    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
        super.onInitializeAccessibilityNodeInfo(info);
        info.setClassName(Button.class.getName());
    }
}

Make AccessibilityTextView inherit from AppCompatTextView


package no.cantara.performance.messagesampler;

public class LatencyMessageSamplerTest {
    public static void main(String[] args) throws InterruptedException {
        final Object waitBus = new Object();
        TimeWindowSampleCallback callback = latency -> System.out.println(latency.getJson());
        LatencyMessageSampler sampler = new LatencyMessageSampler(callback, 100);
        for (int i=0; i<40; i++) {
            long sentTime = System.currentTimeMillis();
            synchronized (waitBus) {
                waitBus.wait(10, 0);
            }
            sampler.addMessage(sentTime, System.currentTimeMillis());
        }
        System.out.println(sampler.getPrintableStatistics().getJson());
    }
}

package no.cantara.performance.messagesampler;

public class LatencyMessageSamplerTest {
    public static void main(String[] args) throws InterruptedException {
        final Object waitBus = new Object();
        TimeWindowSampleCallback callback = latency -> latency.printToStandardError();
        LatencyMessageSampler sampler = new LatencyMessageSampler(callback, 100);
        for (int i=0; i<40; i++) {
            long sentTime = System.currentTimeMillis();
            synchronized (waitBus) {
                waitBus.wait(10, 0);
            }
            sampler.addMessage(sentTime, System.currentTimeMillis());
        }
        sampler.getPrintableStatistics().printToStandardOutput();
    }
}

Test stderr and stdout print methods.

Test stderr and stdout print methods.


package com.github.sergejsamsonow.codegenerator.pojo.renderer;

import com.github.sergejsamsonow.codegenerator.api.CodeFormat;
import com.github.sergejsamsonow.codegenerator.api.MethodCodeWriter;
import com.github.sergejsamsonow.codegenerator.pojo.model.PojoBean;
import com.github.sergejsamsonow.codegenerator.pojo.model.PojoProperty;

public class Setter extends AbstractPropertyRenderer<PojoProperty, PojoBean> {

    public Setter(CodeFormat format) {
        super(format);
    }

    @Override
    protected void writePropertyCode(PojoProperty property) {
        String type = property.getDeclarationType();
        String field = property.getFieldName();
        String setter = property.getSetterName();
        MethodCodeWriter writer = getMethodCodeWriter();
        writer.start("public void %s(%s %s) {", setter, type, field);
        writer.code("this.%s = %s;", field, field);
        writer.end();
    }
}

package com.github.sergejsamsonow.codegenerator.pojo.renderer;

import com.github.sergejsamsonow.codegenerator.api.CodeFormat;
import com.github.sergejsamsonow.codegenerator.api.MethodCodeWriter;
import com.github.sergejsamsonow.codegenerator.pojo.model.PojoBean;
import com.github.sergejsamsonow.codegenerator.pojo.model.PojoProperty;

public class Setter extends AbstractPropertyRenderer<PojoProperty, PojoBean> {

    public Setter(CodeFormat format) {
        super(format);
    }

    @Override
    protected void writePropertyCode(PojoProperty property) {
        String type = property.getDeclarationType();
        String field = property.getFieldName();
        String name = property.getSetterName();
        MethodCodeWriter method = getMethodCodeWriter();
        method.start("public void %s(%s %s) {", name, type, field);
        method.code("this.%s = %s;", field, field);
        method.end();
    }
}

3: Implement example producer
Small refactoring

Task-Url:
http://github.com/sergej-samsonow/code-generator/issues/issue/3


package org.openqa.selenium.server;

public class BrowserConfigurationOptions {

    private String profile = "";

    public BrowserConfigurationOptions(String browserConfiguration) {
        //"name:value;name:value"
        String[] optionsPairList = browserConfiguration.split(";");
        for (int i = 0; i < optionsPairList.length; i++) {
            String[] option = optionsPairList[i].split(":", 2);
            String optionsName = option[0].trim();
            String optionValue = option[1].trim();
            if ("profile".equalsIgnoreCase(optionsName)) {
                this.profile = optionValue;
            }
        }
    }

    public BrowserConfigurationOptions() {}

    /**
     * Sets the profile name for this configuration object.
     * @param profile_name  The name of the profile to use
     */
    public void setProfile(String profile_name) {
        this.profile = profile_name;
    }

    public String serialize() {
        //"profile:XXXXXXXXXX"
        return String.format("profile:%s", profile);
    }

    public String getProfile() {
        return profile;
    }

}

package org.openqa.selenium.server;

public class BrowserConfigurationOptions {

    private String profile = "";

    public BrowserConfigurationOptions(String browserConfiguration) {
        //"name:value;name:value"
        String[] optionsPairList = browserConfiguration.split(";");
        for (int i = 0; i < optionsPairList.length; i++) {
            String[] option = optionsPairList[i].split(":", 2);
            if (2 == option.length) {
              String optionsName = option[0].trim();
              String optionValue = option[1].trim();
              if ("profile".equalsIgnoreCase(optionsName)) {
                  this.profile = optionValue;
              }
            }
        }
    }

    public BrowserConfigurationOptions() {}

    /**
     * Sets the profile name for this configuration object.
     * @param profile_name  The name of the profile to use
     */
    public void setProfile(String profile_name) {
        this.profile = profile_name;
    }

    public String serialize() {
        //"profile:XXXXXXXXXX"
        return String.format("profile:%s", profile);
    }

    public String getProfile() {
        return profile;
    }

}

Fix index out of bounds exception by first checking to make sure the configuration option parsed correctly.

r5374


/*
 * Copyright 2013 Google LLC
 *
 * 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.auto.factory.processor;

import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableSet;
import javax.lang.model.type.TypeMirror;

@AutoValue
abstract class ImplementationMethodDescriptor {
  abstract String name();
  abstract TypeMirror returnType();
  abstract boolean publicMethod();
  abstract ImmutableSet<Parameter> passedParameters();
  abstract boolean isVarArgs();

  static Builder builder() {
    return new AutoValue_ImplementationMethodDescriptor.Builder()
        .publicMethod(true)
        .isVarArgs(false);
  }

  @AutoValue.Builder
  static abstract class Builder {
    abstract Builder name(String name);
    abstract Builder returnType(TypeMirror returnTypeElement);
    abstract Builder publicMethod(boolean publicMethod);
    abstract Builder passedParameters(Iterable<Parameter> passedParameters);
    abstract Builder isVarArgs(boolean isVarargs);
    abstract ImplementationMethodDescriptor build();

    Builder publicMethod() {
      return publicMethod(true);
    }
  }
}

/*
 * Copyright 2013 Google LLC
 *
 * 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.auto.factory.processor;

import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableSet;
import javax.lang.model.type.TypeMirror;

@AutoValue
abstract class ImplementationMethodDescriptor {
  abstract String name();
  abstract TypeMirror returnType();
  abstract boolean publicMethod();
  abstract ImmutableSet<Parameter> passedParameters();
  abstract boolean isVarArgs();

  static Builder builder() {
    return new AutoValue_ImplementationMethodDescriptor.Builder()
        .publicMethod(true)
        .isVarArgs(false);
  }

  @AutoValue.Builder
  static abstract class Builder {
    abstract Builder name(String name);

    abstract Builder returnType(TypeMirror returnTypeElement);

    abstract Builder publicMethod(boolean publicMethod);

    final Builder publicMethod() {
      return publicMethod(true);
    }

    abstract Builder passedParameters(Iterable<Parameter> passedParameters);

    abstract Builder isVarArgs(boolean isVarargs);

    abstract ImplementationMethodDescriptor build();
  }
}

Fix 1 ErrorProneStyle finding:
* Constructors and methods with the same name should appear sequentially with no other code in between. Please re-order or re-name methods.

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


package org.wildfly.swarm.examples.jaxrs.health;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.wildfly.swarm.monitor.Health;

@Path("/app")
public class HealthCheckResource {

    @GET
    @Path("/health")
    @Produces(MediaType.TEXT_PLAIN)
    @Health
    public String firstHealthCheckMethod() {
        return "Healthy: On HealthCheckResource#firstHealthCheckMethod()";
    }

    @GET
    @Path("/second-health")
    @Produces(MediaType.TEXT_PLAIN)
    @Health(secure = false)
    public String secondHealthCheckMethod() {
        return "Healthy: On HealthCheckResource#secondHealthCheckMethod()";
    }

}

package org.wildfly.swarm.examples.jaxrs.health;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.wildfly.swarm.monitor.Health;

@Path("/app")
public class HealthCheckResource {

    @GET
    @Path("/health")
    @Produces(MediaType.TEXT_PLAIN)
    @Health
    public String firstHealthCheckMethod() {
        return "Healthy: On HealthCheckResource#firstHealthCheckMethod()";
    }

    @GET
    @Path("/second-health")
    @Produces(MediaType.TEXT_PLAIN)
    @Health(inheritSecurity = false)
    public String secondHealthCheckMethod() {
        return "Healthy: On HealthCheckResource#secondHealthCheckMethod()";
    }

}

Rename @Health parameter to 'inheritSecurity'


package com.csci4448.MediaManagementSystem.model.media;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class MediaDAO {

    private SessionFactory sessionFactory;

    public MediaDAO() {
        sessionFactory = new Configuration().configure().buildSessionFactory();
    }

}

package com.csci4448.MediaManagementSystem.model.media;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class MediaDAO {

    private SessionFactory sessionFactory;

    public MediaDAO() {
        sessionFactory = new Configuration().configure().buildSessionFactory();
    }

    //ToDo: System inventory stuff, basic add/edit/delete of media, and waitlist of rentable media

}

Add ToDo stuff for media DAO

Add ToDo stuff for media DAO


package models;

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

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

import com.fasterxml.jackson.annotation.JsonIgnore;

import play.db.ebean.Model;
import play.db.ebean.Model.Finder;

//tar magnus feil?
@Entity
public class Guest extends Model {

	@Id
	public Long id;

	@OneToMany(cascade = CascadeType.ALL, mappedBy = "guest")
	@JsonIgnore
	public List<Booking> booking =new ArrayList<Booking>();

	/** TODO REMOVE TEST **/
	public Guest(long id) {
		this.id = id;
	}
	/** END TEST **/
	public static Finder<Long, Guest> find = new Finder<Long, Guest>(Long.class, Guest.class);
}

package models;

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

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

import com.fasterxml.jackson.annotation.JsonIgnore;

import play.db.ebean.Model;
import play.db.ebean.Model.Finder;

@Entity
public class Guest extends Model {

	@Id
	public Long id;

	@OneToMany(cascade = CascadeType.ALL, mappedBy = "guest")
	@JsonIgnore
	public List<Booking> booking =new ArrayList<Booking>();

	/** TODO REMOVE TEST **/
	public Guest(long id) {
		this.id = id;
	}
	/** END TEST **/
	public static Finder<Long, Guest> find = new Finder<Long, Guest>(Long.class, Guest.class);
}

Test commit, magnus tok ikke feil

Test commit, magnus tok ikke feil


// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.sdk.internal.wip.protocol.input;

import java.util.List;

import org.chromium.sdk.internal.protocolparser.JsonOptionalField;
import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException;
import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting;
import org.chromium.sdk.internal.protocolparser.JsonType;

@JsonType(subtypesChosenManually=true)
public interface WipTabList {
  @JsonSubtypeCasting List<TabDescription> asTabList() throws JsonProtocolParseException;

  @JsonType interface TabDescription {
    String faviconUrl();
    String title();
    String url();

    String thumbnailUrl();

    @JsonOptionalField
    String devtoolsFrontendUrl();

    @JsonOptionalField
    String webSocketDebuggerUrl();
  }
}

// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.sdk.internal.wip.protocol.input;

import java.util.List;

import org.chromium.sdk.internal.protocolparser.JsonOptionalField;
import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException;
import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting;
import org.chromium.sdk.internal.protocolparser.JsonType;

@JsonType(subtypesChosenManually=true)
public interface WipTabList {
  @JsonSubtypeCasting List<TabDescription> asTabList() throws JsonProtocolParseException;

  @JsonType interface TabDescription {
    String faviconUrl();
    String title();
    String url();

    String thumbnailUrl();

    // TODO: consider adding enum here
    String type();

    @JsonOptionalField
    String devtoolsFrontendUrl();

    @JsonOptionalField
    String webSocketDebuggerUrl();
  }
}

Add 'type' field to tab enumeration JSON protocol

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


import com.lisb.msgpack.bind.MsgpackBind;

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

@MsgpackBind
public class SimpleSource {
    public String first;
    public int second;
    public List<String> third;
    public List<List<Boolean>> fourth;
    public Map<Long, String> fifth;
    public MimeTypes sixth;
    public byte[] seventh;

    public enum MimeTypes {
        IMAGE, VIDEO, SOUND
    }
}

import com.lisb.msgpack.bind.MsgpackBind;

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

@MsgpackBind
public class SimpleSource {
    public String first;
    public int second;
    public List<String> third;
    public List<List<Boolean>> fourth;
    public Map<Long, String> fifth;
    public MimeTypes sixth;
    public byte[] seventh;
    // private field is ignored.
    private long eighth;
    // static field is ignored.
    static Long nineth;
    // final field is ignored.
    final Short tenth = 1;

    public enum MimeTypes {
        IMAGE, VIDEO, SOUND
    }
}

Add ignored field to simple test case

Add ignored field to simple test case


package com.bungleton.yarrgs;

import com.bungleton.yarrgs.parser.Command;

public class Yarrgs
{
    public static <T> T parseInMain (Class<T> argsType, String[] args)
    {
        try {
            return parse(argsType, args);
        } catch (YarrgParseException e) {
            System.err.println(e.getUsage() + "\n" + e.getMessage());
            System.exit(1);
            return null;
        }
    }

    public static <T> T parse (Class<T> argsType, String[] args)
        throws YarrgParseException
    {
        T t;
        try {
            t = argsType.newInstance();
        } catch (Exception e) {
            throw new YarrgConfigurationException("'" + argsType
                + "' must have a public no-arg constructor", e);
        }
        new Command(t).parse(args);
        return t;
    }
}

package com.bungleton.yarrgs;

import com.bungleton.yarrgs.parser.Command;

public class Yarrgs
{
    public static <T> T parseInMain (Class<T> argsType, String[] args)
    {
        try {
            return parse(argsType, args);
        } catch (YarrgParseException e) {
            System.err.println(e.getUsage() + "\n" + e.getMessage());
            System.exit(1);
            throw new IllegalStateException("Java continued past a System.exit call");
        }
    }

    public static <T> T parse (Class<T> argsType, String[] args)
        throws YarrgParseException
    {
        T t;
        try {
            t = argsType.newInstance();
        } catch (Exception e) {
            throw new YarrgConfigurationException("'" + argsType
                + "' must have a public no-arg constructor", e);
        }
        new Command(t).parse(args);
        return t;
    }
}

Throw an exception when we hit an impossible condition rather than returning null


package io.digdag.standards.operator.gcp;

import com.google.api.services.bigquery.model.Job;
import com.google.api.services.bigquery.model.JobConfiguration;
import io.digdag.client.config.Config;
import io.digdag.client.config.ConfigFactory;
import io.digdag.client.config.ConfigKey;
import io.digdag.spi.OperatorContext;
import io.digdag.spi.TaskResult;

import java.nio.file.Path;

abstract class BaseBqJobOperator
        extends BaseBqOperator
{
    BaseBqJobOperator(OperatorContext context, BqClient.Factory clientFactory, GcpCredentialProvider credentialProvider)
    {
        super(context, clientFactory, credentialProvider);
    }

    @Override
    protected TaskResult run(BqClient bq, String projectId)
    {
        BqJobRunner jobRunner = new BqJobRunner(request, bq, projectId);
        Job completed = jobRunner.runJob(jobConfiguration(projectId));
        return result(completed);
    }

    private TaskResult result(Job job)
    {
        ConfigFactory cf = request.getConfig().getFactory();
        Config result = cf.create();
        Config bq = result.getNestedOrSetEmpty("bq");
        bq.set("last_job_id", job.getId());
        return TaskResult.defaultBuilder(request)
                .storeParams(result)
                .addResetStoreParams(ConfigKey.of("bq", "last_job_id"))
                .build();
    }

    protected abstract JobConfiguration jobConfiguration(String projectId);
}

package io.digdag.standards.operator.gcp;

import com.google.api.services.bigquery.model.Job;
import com.google.api.services.bigquery.model.JobConfiguration;
import io.digdag.client.config.Config;
import io.digdag.client.config.ConfigFactory;
import io.digdag.client.config.ConfigKey;
import io.digdag.spi.OperatorContext;
import io.digdag.spi.TaskResult;

import java.nio.file.Path;

abstract class BaseBqJobOperator
        extends BaseBqOperator
{
    BaseBqJobOperator(OperatorContext context, BqClient.Factory clientFactory, GcpCredentialProvider credentialProvider)
    {
        super(context, clientFactory, credentialProvider);
    }

    @Override
    protected TaskResult run(BqClient bq, String projectId)
    {
        BqJobRunner jobRunner = new BqJobRunner(request, bq, projectId);
        Job completed = jobRunner.runJob(jobConfiguration(projectId));
        return result(completed);
    }

    private TaskResult result(Job job)
    {
        ConfigFactory cf = request.getConfig().getFactory();
        Config result = cf.create();
        Config bq = result.getNestedOrSetEmpty("bq");
        bq.set("last_job_id", job.getId());
        bq.set("last_jobid", job.getId());
        return TaskResult.defaultBuilder(request)
                .storeParams(result)
                .addResetStoreParams(ConfigKey.of("bq", "last_job_id"))
                .addResetStoreParams(ConfigKey.of("bq", "last_jobid"))
                .build();
    }

    protected abstract JobConfiguration jobConfiguration(String projectId);
}

Make last_jobid available for compatibility.


package seedu.task.model.task;

import java.util.Calendar;

import seedu.task.commons.exceptions.IllegalValueException;
import seedu.task.model.util.DateParser;

public class DueDate {
/**
 * Represents a Task's due date in the task list.
 * Guarantees: immutable; is valid as declared in {@link #isValidDueDate(String)}
 */
    public final Calendar dueDate;

    /**
     * Validates given description.
     *
     * @throws IllegalValueException if given description string is invalid.
     */
    public DueDate(String inputDueDate) throws IllegalValueException {
        this.dueDate = DateParser.parse(inputDueDate);
    }

    @Override
    public String toString() {
        return DateParser.toString(dueDate);
    }

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

}

package seedu.task.model.task;

import java.util.Calendar;

import seedu.task.commons.exceptions.IllegalValueException;
import seedu.task.model.util.DateParser;

public class DueDate {
/**
 * Represents a Task's due date in the task list.
 * Guarantees: immutable; is valid as declared in {@link #isValidDueDate(String)}
 */
    public final Calendar dueDate;

    /**
     * Validates given description.
     *
     * @throws IllegalValueException if given description string is invalid.
     */
    public DueDate(String inputDueDate) throws IllegalValueException {
        this.dueDate = DateParser.parse(inputDueDate);
    }

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

    @Override
    public String toString() {
        return DateParser.toString(dueDate);
    }

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

}

Add equals method to duedate model

Add equals method to duedate model

Adding an equals method so that calling `.equals` in tests equates
objects with equal due dates.


package org.knowm.xchange.huobi.service;

import org.knowm.xchange.Exchange;
import org.knowm.xchange.huobi.BitVc;
import org.knowm.xchange.huobi.BitVcFutures;
import si.mazi.rescu.RestProxyFactory;

public class BitVcFuturesServiceRaw {

    protected final BitVcFutures bitvc;
    protected final String accessKey;
    protected HuobiDigest digest;

    public BitVcFuturesServiceRaw(Exchange exchange) {
        this.bitvc = RestProxyFactory.createProxy(BitVcFutures.class, "https://api.bitvc.com/futures");
        this.accessKey = exchange.getExchangeSpecification().getApiKey();

        /** BitVc Futures expect a different secret key digest name from BitVc spot and Huobi */
        this.digest = new HuobiDigest(exchange.getExchangeSpecification().getSecretKey(), "secretKey");
    }

    protected long requestTimestamp() {
        return System.currentTimeMillis() / 1000;
    }
}

package org.knowm.xchange.huobi.service;

import org.knowm.xchange.Exchange;
import org.knowm.xchange.huobi.BitVc;
import org.knowm.xchange.huobi.BitVcFutures;
import org.knowm.xchange.huobi.dto.trade.BitVcFuturesPosition;
import org.knowm.xchange.huobi.dto.trade.BitVcFuturesPositionByContract;
import si.mazi.rescu.RestProxyFactory;

public class BitVcFuturesServiceRaw {

    protected final BitVcFutures bitvc;
    protected final String accessKey;
    protected HuobiDigest digest;

    public BitVcFuturesServiceRaw(Exchange exchange) {
        this.bitvc = RestProxyFactory.createProxy(BitVcFutures.class, "https://api.bitvc.com/futures");
        this.accessKey = exchange.getExchangeSpecification().getApiKey();

        /** BitVc Futures expect a different secret key digest name from BitVc spot and Huobi */
        this.digest = new HuobiDigest(exchange.getExchangeSpecification().getSecretKey(), "secretKey");
    }

    public BitVcFuturesPositionByContract getFuturesPositions() {
        final BitVcFuturesPositionByContract positions = bitvc.positions(accessKey, 1, requestTimestamp(), digest);

        return positions;
    }

    protected long requestTimestamp() {
        return System.currentTimeMillis() / 1000;
    }
}

Add getter for futures positions for BitVc


/*
 * ******************************************************************************
 *    Copyright 2016-2017 Spectra Logic Corporation. 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. A copy of the License is located at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *    or in the "license" file accompanying this file.
 *    This file 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.spectralogic.dsbrowser.gui.services;

import org.junit.Test;

import java.time.LocalDateTime;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

public class BuildInfoService_Test {

    @Test
    public void parseDateString() {
        final String buildDate = "Wed Mar 15 11:10:25 MDT 2017";
        final LocalDateTime ldt = LocalDateTime.parse(buildDate, BuildInfoServiceImpl.dtf);
        final String formattedDate = ldt.format(BuildInfoServiceImpl.dtf);
        //final String formattedDate = ldt.format(BuildInfoServiceImpl.dtf);
        assertThat(formattedDate, is(buildDate));
    }
}

/*
 * ******************************************************************************
 *    Copyright 2016-2017 Spectra Logic Corporation. 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. A copy of the License is located at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *    or in the "license" file accompanying this file.
 *    This file 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.spectralogic.dsbrowser.gui.services;

import org.junit.Test;

import java.time.LocalDateTime;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

public class BuildInfoService_Test {

    @Test
    public void parseDateString() {
        final String buildDate = "Wed Mar 15 11:10:25 MDT 2017";
        final LocalDateTime ldt = LocalDateTime.parse(buildDate, BuildInfoServiceImpl.dtf);
        assertThat(ldt.toString(), is("2017-03-15T11:10:25"));
    }
}

Convert LocalDateTime expected output to ISO-8601, since there's no timezone in LocalDateTime


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

package io.spine.server.model;

import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * An error message formatting helper.
 */
final class MessageFormatter {

    private MessageFormatter() {
    }

    static Collector<CharSequence, ?, String> toStringEnumeration() {
        return Collectors.joining(", ");
    }
}

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

package io.spine.server.model;

import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * An error message formatting helper.
 */
final class MessageFormatter {

    private MessageFormatter() {
    }

    /**
     * Collects items into a string separating them with commas.
     *
     * @apiNote Migrate off this method once the API resulted from
     * this issue in {@code base}
     * is available.
     */
    static Collector<CharSequence, ?, String> toStringEnumeration() {
        return Collectors.joining(", ");
    }
}

Add Javadoc and migration path

Add Javadoc and migration path


package com.digirati.elucidate.model;

public class ServiceResponse<T> {

    public enum Status {
        OK, NOT_FOUND, CACHE_KEY_MISS, ILLEGAL_MODIFICATION, NON_CONFORMANT, DELETED, ALREADY_EXISTS
    }

    private final Status status;
    private final T obj;

    public ServiceResponse(Status status, T obj) {
        this.status = status;
        this.obj = obj;
    }

    public Status getStatus() {
        return status;
    }

    public T getObj() {
        return obj;
    }
}

package com.digirati.elucidate.model;

public class ServiceResponse<T> {

    public enum Status {
        OK, NOT_FOUND, CACHE_KEY_MISS, ILLEGAL_MODIFICATION, NON_CONFORMANT, DELETED, ALREADY_EXISTS,
        UNAUTHORIZED
    }

    private final Status status;
    private final T obj;

    public ServiceResponse(Status status, T obj) {
        this.status = status;
        this.obj = obj;
    }

    public Status getStatus() {
        return status;
    }

    public T getObj() {
        return obj;
    }
}

Add new 'unauthorized' service response status


package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnection {
	Connection dbConnection;

	public DatabaseConnection() {
		dbConnection = DatabaseConnection.connector();
	}

	public static Connection connector() {
		// SQLite connection string
        Connection conn = null;
        try {
        	Class.forName("org.sqlite.JDBC");
        	//for Linux distribution
//            String url = "jdbc:sqlite:/home/"+System.getProperty("user.name")+"/Money-ManagerDB/Money_Manager.db";

        	//for Mac distribution
//        	String url = "jdbc:sqlite:/Users/"+System.getProperty("user.name")+"/Money-ManagerDB/Money_Manager.db";

          //for Windows distribution
            String url = "jdbc:sqlite:Money_Manager.db";

            conn = DriverManager.getConnection(url);
//            System.out.println("Connection to SQLite has been established.");
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println(e.getMessage());
        }
        return conn;
	}

	public boolean isDBConnected() {
		try {
			return !dbConnection.isClosed();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

//	public static void main(String[] args) {
//		DatabaseConnection access = new DatabaseConnection();
//		System.out.println(access.isDBConnected());
//	}
}

package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnection {
	Connection dbConnection;

	public DatabaseConnection() {
		dbConnection = DatabaseConnection.connector();
	}

	public static Connection connector() {
		// SQLite connection string
        Connection conn = null;
        try {
        	Class.forName("org.sqlite.JDBC");
        	//for Linux distribution
            String url = "jdbc:sqlite:/home/"+System.getProperty("user.name")+"/Money-ManagerDB/Money_Manager.db";

        	//for Mac distribution
//        	String url = "jdbc:sqlite:/Users/"+System.getProperty("user.name")+"/Money-ManagerDB/Money_Manager.db";

          //for Windows distribution
//            String url = "jdbc:sqlite:Money_Manager.db";

            conn = DriverManager.getConnection(url);
//            System.out.println("Connection to SQLite has been established.");
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println(e.getMessage());
        }
        return conn;
	}

	public boolean isDBConnected() {
		try {
			return !dbConnection.isClosed();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

//	public static void main(String[] args) {
//		DatabaseConnection access = new DatabaseConnection();
//		System.out.println(access.isDBConnected());
//	}
}

Make changes in Sign Out button

Make changes in Sign Out button


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

import com.google.common.base.Throwables;

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

public class DefaultTemplateLibraryVersionProvider implements TemplateLibraryVersionProvider {

    private final Properties libraryVersions = new Properties();

    public DefaultTemplateLibraryVersionProvider() {
        try {
            this.libraryVersions.load(getClass().getResourceAsStream("/org/gradle/buildinit/tasks/templates/library-versions.properties"));
        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }

    public String getVersion(String module) {
        return libraryVersions.getProperty(module);
    }
}

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

import com.google.common.base.Throwables;
import org.gradle.api.JavaVersion;

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

public class DefaultTemplateLibraryVersionProvider implements TemplateLibraryVersionProvider {

    private final Properties libraryVersions = new Properties();

    public DefaultTemplateLibraryVersionProvider() {
        try {
            this.libraryVersions.load(getClass().getResourceAsStream("/org/gradle/buildinit/tasks/templates/library-versions.properties"));
        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }

    public String getVersion(String module) {
        if (module.equals("testng") && !JavaVersion.current().isJava8Compatible()) {
            // Use the highest version that runs on Java 7
            return "6.9.12";
        }
        return libraryVersions.getProperty(module);
    }
}

Revert "Remove temporary patch for broken TestNG 6.9.13"

This reverts commit 3aaab7db09e801d66e66029a7c0719fe24084d39.

CI still has the dynamic versions lookup result in cache.
Will resubmit later.


package com.jakewharton.telecine;

import android.app.Activity;
import android.content.Intent;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import butterknife.ButterKnife;
import butterknife.OnClick;
import timber.log.Timber;

public final class TelecineActivity extends Activity {
  private static final int CREATE_SCREEN_CAPTURE = 4242;

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

  @OnClick(R.id.launch) void onLaunchClicked() {
    Timber.d("Attempting to acquire permission to screen capture.");

    MediaProjectionManager manager =
        (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
    Intent intent = manager.createScreenCaptureIntent();
    startActivityForResult(intent, CREATE_SCREEN_CAPTURE);
  }

  @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
      case CREATE_SCREEN_CAPTURE:
        Timber.d("Acquired permission to screen capture. Starting service.");
        startService(TelecineService.newIntent(this, resultCode, data));
        break;

      default:
        super.onActivityResult(requestCode, resultCode, data);
    }
  }
}

package com.jakewharton.telecine;

import android.app.Activity;
import android.content.Intent;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import butterknife.ButterKnife;
import butterknife.OnClick;
import timber.log.Timber;

public final class TelecineActivity extends Activity {
  private static final int CREATE_SCREEN_CAPTURE = 4242;

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

  @OnClick(R.id.launch) void onLaunchClicked() {
    Timber.d("Attempting to acquire permission to screen capture.");

    MediaProjectionManager manager =
        (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
    Intent intent = manager.createScreenCaptureIntent();
    startActivityForResult(intent, CREATE_SCREEN_CAPTURE);
  }

  @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
      case CREATE_SCREEN_CAPTURE:
        if (resultCode == 0) {
          Timber.d("Failed to acquire permission to screen capture.");
        } else {
          Timber.d("Acquired permission to screen capture. Starting service.");
          startService(TelecineService.newIntent(this, resultCode, data));
        }
        break;

      default:
        super.onActivityResult(requestCode, resultCode, data);
    }
  }
}

Handle when the user presses cancel on the permission prompt.


/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

package com.skelril.skree.service;

import com.skelril.nitro.Clause;

import java.util.Collection;

public interface ModifierService {
    void setExpiry(String modifierName, long time);
    long expiryOf(String modifierName);
    default long statusOf(String modifierName) {
        return Math.max(expiryOf(modifierName) - System.currentTimeMillis(), 0);
    }
    default boolean isActive(String modifierName) {
        return statusOf(modifierName) != 0;
    }

    Collection<Clause<String, Long>> getActiveModifiers();
}

/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

package com.skelril.skree.service;

import com.skelril.nitro.Clause;

import java.util.Collection;

public interface ModifierService {
    void setExpiry(String modifier, long time);
    long expiryOf(String modifier);
    default long statusOf(String modifier) {
        return Math.max(expiryOf(modifier) - System.currentTimeMillis(), 0);
    }
    default boolean isActive(String modifier) {
        return statusOf(modifier) != 0;
    }

    Collection<Clause<String, Long>> getActiveModifiers();
}

Change the variable name modifierName to modifier


package ws.biotea.ld2rdf.rdf.model;

import ws.biotea.ld2rdf.util.OntologyPrefix;
import java.io.Serializable;

/**
 * OpenAnnotation: This class represents a general annotation on a Document.
 * @author leylajael
 */
public class BaseAnnotation implements Serializable {
	private static final long serialVersionUID = 1L;
	/* OWL Descriptors */
	public final static String ANNOTATION_DP_LABEL = OntologyPrefix.RDFS.getURL() + "label";
	public final static String RDFS_COMMENT = OntologyPrefix.RDFS.getURL() + "comment";
	public final static String BIOTEA_OCURRENCES = OntologyPrefix.BIOTEA.getURL() + "tf";
	public final static String BIOTEA_IDF = OntologyPrefix.BIOTEA.getURL() + "idf";
	public final static String RDFS_SEE_ALSO = OntologyPrefix.RDFS.getURL() + "seeAlso";
	public final static String OWL_SAME_AS = OntologyPrefix.OWL.getURL() + "sameAs";
    public final static String DC_IS_REFERENCED_BY = OntologyPrefix.DCTERMS.getURL() + "isReferencedBy";
    public final static String SIO_IN_DATASET = OntologyPrefix.SIO.getURL() + "001278";
    public final static String DP_SCORE = OntologyPrefix.BIOTEA.getURL() + "score";
}

package ws.biotea.ld2rdf.rdf.model;

import ws.biotea.ld2rdf.util.OntologyPrefix;
import java.io.Serializable;

/**
 * OpenAnnotation: This class represents a general annotation on a Document.
 * @author leylajael
 */
public class BaseAnnotation implements Serializable {
	private static final long serialVersionUID = 1L;
	/* OWL Descriptors */
	public final static String ANNOTATION_DP_LABEL = OntologyPrefix.RDFS.getURL() + "label";
	public final static String RDFS_COMMENT = OntologyPrefix.RDFS.getURL() + "comment";
	public final static String BIOTEA_OCURRENCES = OntologyPrefix.BIOTEA.getURL() + "tf";
	public final static String BIOTEA_IDF = OntologyPrefix.BIOTEA.getURL() + "idf";
	public final static String RDFS_SEE_ALSO = OntologyPrefix.RDFS.getURL() + "seeAlso";
	public final static String OWL_SAME_AS = OntologyPrefix.OWL.getURL() + "sameAs";
    public final static String DC_IS_REFERENCED_BY = OntologyPrefix.DCTERMS.getURL() + "isReferencedBy";
    public final static String SIO_IN_DATASET = OntologyPrefix.SIO.getURL() + "SIO_001278";
    public final static String DP_SCORE = OntologyPrefix.BIOTEA.getURL() + "score";
}

Update SIO "in dataset" property.

Update SIO "in dataset" property.


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

package org.culturegraph.mf.flux;

import java.io.PrintStream;

import org.apache.commons.io.output.NullOutputStream;
import org.culturegraph.mf.flux.parser.FluxProgramm;
import org.junit.Test;

/**
 * Tests {@link FluxProgramm}
 *
 * @author markus geipel
 *
 */

public final class FluxProgrammTest {
	@Test
	public void testCommandRegistration() {
		// all commands must properly load to print the help
		FluxProgramm.printHelp(new PrintStream(new NullOutputStream()));

	}
}

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

package org.culturegraph.mf.flux;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import org.culturegraph.mf.flux.parser.FluxProgramm;
import org.junit.Test;

/**
 * Tests {@link FluxProgramm}
 *
 * @author markus geipel
 *
 */

public final class FluxProgrammTest {

	@Test
	public void testCommandRegistration() {
		// all commands must properly load to print the help
		FluxProgramm.printHelp(discardOutput());

	}

	private PrintStream discardOutput() {
		return new PrintStream(new OutputStream() {
			@Override
			public void write(int b) throws IOException {
				// Do not write any output.
			}
		});
	}

}

Replace NullOutputStream with inline implementation

Using `NullOutputStream` in `FluxProgrammTest` introduced a depdency on
Apache Commons IO which can easily be avoided.


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

import com.google.inject.Inject;
import com.yahoo.container.jaxrs.annotation.Component;
import com.yahoo.log.LogLevel;

import javax.ws.rs.Consumes;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.logging.Logger;

/**
 * @author bjorncs
 */
@Path("/instance")
public class InstanceConfirmationResource {

    private static final Logger log = Logger.getLogger(InstanceConfirmationResource.class.getName());

    private final InstanceValidator instanceValidator;

    @Inject
    public InstanceConfirmationResource(@Component InstanceValidator instanceValidator) {
        this.instanceValidator = instanceValidator;
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public InstanceConfirmation confirmInstance(InstanceConfirmation instanceConfirmation) {
        if (!instanceValidator.isValidInstance(instanceConfirmation)) {
            log.log(LogLevel.ERROR, "Invalid instance: " + instanceConfirmation);
            throw new ForbiddenException("Instance is invalid");
        }
        return instanceConfirmation;
    }
}

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

import com.google.inject.Inject;
import com.yahoo.container.jaxrs.annotation.Component;
import com.yahoo.log.LogLevel;

import javax.ws.rs.Consumes;
import javax.ws.rs.ForbiddenException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.logging.Logger;

/**
 * @author bjorncs
 */
@Path("/{path: instance|refresh}")
public class InstanceConfirmationResource {

    private static final Logger log = Logger.getLogger(InstanceConfirmationResource.class.getName());

    private final InstanceValidator instanceValidator;

    @Inject
    public InstanceConfirmationResource(@Component InstanceValidator instanceValidator) {
        this.instanceValidator = instanceValidator;
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public InstanceConfirmation confirmInstance(InstanceConfirmation instanceConfirmation) {
        if (!instanceValidator.isValidInstance(instanceConfirmation)) {
            log.log(LogLevel.ERROR, "Invalid instance: " + instanceConfirmation);
            throw new ForbiddenException("Instance is invalid");
        }
        return instanceConfirmation;
    }
}

Implement /refresh endpoint for indetity provider


package org.innovateuk.ifs.finance.resource.cost;

public enum OverheadRateType{
    NONE(null, null, "None"),
    DEFAULT_PERCENTAGE(20, "DEFAULT_PERCENTAGE", "Default %"),
    TOTAL(null, "total", "Custom Amount"),
    CUSTOM_RATE(null, "customRate", "Custom Rate"); // NOTE: Now that competiton 1 is gone, there is no need to keep custom rate. TODO: Check with Rogier and remove if safe : INFUND-7322

    private final Integer rate;
    private final String name;
    private final String label;

    OverheadRateType(Integer rate, String name, String label) {
        this.rate = rate;
        this.name = name;
        this.label = label;
    }

    public Integer getRate() {
        return rate;
    }
    public String getName() {
        return name;
    }

    public String getLabel() {
        return label;
    }
}

package org.innovateuk.ifs.finance.resource.cost;

public enum OverheadRateType{
    NONE(null, null, "None"),
    DEFAULT_PERCENTAGE(20, "defaultPercentage", "Default %"),
    TOTAL(null, "total", "Custom Amount"),
    CUSTOM_RATE(null, "customRate", "Custom Rate"); // NOTE: Now that competiton 1 is gone, there is no need to keep custom rate. TODO: Check with Rogier and remove if safe : INFUND-7322

    private final Integer rate;
    private final String name;
    private final String label;

    OverheadRateType(Integer rate, String name, String label) {
        this.rate = rate;
        this.name = name;
        this.label = label;
    }

    public Integer getRate() {
        return rate;
    }
    public String getName() {
        return name;
    }

    public String getLabel() {
        return label;
    }
}

Address PR comment.  Made name consistent with others using camel case

Former-commit-id: dd6877565ece23b153a6b4d26edc6a5d71ca1649


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

package com.google.template.soy.data;

/**
 * Exception thrown when a future fails.  Similar to ExecutionException.
 *
 */
public final class SoyFutureException extends RuntimeException {
  public SoyFutureException(Throwable cause) {
    super("Error dereferencing future", cause,
        true,  // allow suppressions
        // No stack trace.  If we had a stack trace it would just point at renderer code which is
        // irrelevant to programmers.
        false);
  }
}

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

package com.google.template.soy.data;

/**
 * Exception thrown when a future fails.  Similar to ExecutionException.
 *
 */
public final class SoyFutureException extends RuntimeException {
  public SoyFutureException(Throwable cause) {
    super("Error dereferencing future", cause);
  }
}

Change apps/framework/template to use AbstractSoyTemplate in the response handlers instead of TofuTemplate (or just Template).  This will allow the --experimental_use_soy_sauce flag to influence the standard framework response handlers.

Also, fix the TemplateExceptionHandler to better support exceptions thrown by
SoySauce.
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=98009319


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.qpid.proton4j.transport;

import org.apache.qpid.proton4j.amqp.Binary;
import org.apache.qpid.proton4j.amqp.transport.Performative;

/**
 * Frame object that carries an AMQP Performative
 */
public class ProtocolFrame extends Frame<Performative> {

    public static final byte AMQP_FRAME_TYPE = (byte) 1;

    public ProtocolFrame(Performative performative, short channel, Binary payload) {
        super(performative, channel, AMQP_FRAME_TYPE, payload);
    }
}

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.qpid.proton4j.transport;

import org.apache.qpid.proton4j.amqp.Binary;
import org.apache.qpid.proton4j.amqp.transport.Performative;

/**
 * Frame object that carries an AMQP Performative
 */
public class ProtocolFrame extends Frame<Performative> {

    public static final byte AMQP_FRAME_TYPE = (byte) 0;

    public ProtocolFrame(Performative performative, short channel, Binary payload) {
        super(performative, channel, AMQP_FRAME_TYPE, payload);
    }
}

Fix frame type, should be 0 for protocol frames


import traildb.*;

import java.io.FileNotFoundException;

public class Wikipedia {
	public static long SESSION_LIMIT = 3600;
	public static void sessions(TrailDB tdb) {
		TrailDBCursor cursor = tdb.cursorNew();
		long n = tdb.numTrails();
		long totalSessions = 0;
		long totalEvents = 0;

		for (long i = 0; i < n; i++) {
			TrailDBEvent event;
			cursor.getTrail(i);
			event = cursor.next();
			long prevTime = event.timestamp;
			long numSessions = 1;
			long numEvents = 1;
			while ((event = cursor.next()) != null) {
				if (event.timestamp - prevTime > SESSION_LIMIT)
					numSessions++;
				prevTime = event.timestamp;
				numEvents++;
			}
			totalSessions += numSessions;
			totalEvents += numEvents;
		}
		System.out.println("Trails: " + n + "Sessions: " + totalSessions + " Events: " + totalEvents);
	}

	public static void main(String[] args) throws FileNotFoundException {
		TrailDB tdb = new TrailDB("wikipedia-history.tdb");
		sessions(tdb);
	}
}

import traildb.*;

import java.io.FileNotFoundException;

public class Wikipedia {
	public static long SESSION_LIMIT = 30 * 60;
	public static void sessions(TrailDB tdb) {
		TrailDBCursor cursor = tdb.cursorNew();
		long n = tdb.numTrails();
		long totalSessions = 0;
		long totalEvents = 0;

		for (long i = 0; i < n; i++) {
			TrailDBEvent event;
			cursor.getTrail(i);
			event = cursor.next();
			long prevTime = event.timestamp;
			long numSessions = 1;
			long numEvents = 1;
			while ((event = cursor.next()) != null) {
				if (event.timestamp - prevTime > SESSION_LIMIT)
					numSessions++;
				prevTime = event.timestamp;
				numEvents++;
			}
			totalSessions += numSessions;
			totalEvents += numEvents;
		}
		System.out.println("Trails: " + n + "Sessions: " + totalSessions + " Events: " + totalEvents);
	}

	public static void main(String[] args) throws FileNotFoundException {
		TrailDB tdb = new TrailDB("wikipedia-history-small.tdb");
		sessions(tdb);
	}
}

Use small tdb in wikipedia example

Use small tdb in wikipedia example


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

import java.util.StringTokenizer;

import org.fedoraproject.maven.resolver.DefaultResolver;
import org.fedoraproject.maven.resolver.Resolver;
import org.fedoraproject.maven.resolver.SystemResolver;

public class ResolverCli
{
    public static void main( String[] args )
    {
        Resolver resolver = new DefaultResolver();

        for ( String arg : args )
        {
            StringTokenizer tok = new StringTokenizer( arg, ":" );
            String groupId = tok.nextToken();
            String artifactId = tok.nextToken();
            String version = tok.hasMoreTokens() ? tok.nextToken() : "SYSTEM";
            String extension = tok.hasMoreTokens() ? tok.nextToken() : "pom";

            resolver.resolve( groupId, artifactId, version, extension );
        }

        SystemResolver.printInvolvedPackages();
    }
}

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

import java.io.File;
import java.util.StringTokenizer;

import org.fedoraproject.maven.resolver.DefaultResolver;
import org.fedoraproject.maven.resolver.Resolver;
import org.fedoraproject.maven.resolver.SystemResolver;

public class ResolverCli
{
    public static void main( String[] args )
    {
        Resolver resolver = new DefaultResolver();

        for ( String arg : args )
        {
            StringTokenizer tok = new StringTokenizer( arg, ":" );
            String groupId = tok.nextToken();
            String artifactId = tok.nextToken();
            String version = tok.hasMoreTokens() ? tok.nextToken() : "SYSTEM";
            String extension = tok.hasMoreTokens() ? tok.nextToken() : "pom";

            File file = resolver.resolve( groupId, artifactId, version, extension );
            System.out.println( file );
        }

        SystemResolver.printInvolvedPackages();
    }
}

Make xmvn-resolve print resolved artifact files


package io.quarkus.micrometer.runtime.binder;

import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder;

public class JVMInfoBinder implements MeterBinder {

    @Override
    public void bindTo(MeterRegistry registry) {
        Gauge.builder("jvm_info", () -> 1L)
                .description("JVM version info")
                .tags("version", System.getProperty("java.runtime.version", "unknown"),
                        "vendor", System.getProperty("java.vm.vendor", "unknown"),
                        "runtime", System.getProperty("java.runtime.name", "unknown"))
                .strongReference(true)
                .register(registry);
    }
}

package io.quarkus.micrometer.runtime.binder;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder;

public class JVMInfoBinder implements MeterBinder {

    @Override
    public void bindTo(MeterRegistry registry) {
        Counter.builder("jvm_info")
                .description("JVM version info")
                .tags("version", System.getProperty("java.runtime.version", "unknown"),
                        "vendor", System.getProperty("java.vm.vendor", "unknown"),
                        "runtime", System.getProperty("java.runtime.name", "unknown"))
                .register(registry)
                .increment();
    }
}

Use counter for JVM Info

Use counter for JVM Info


package com.qualcomm.ftcrobotcontroller.opmodes.custom.util;

import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.hardware.GyroSensor;

/**
 * Created by Peter on 2/29/16.
 */
public class GyroTest5421 extends OpMode {

    GyroSensor gyro;
    //DcMotor mL;
    //DcMotor mR;
    //Gamepad g1;

    @Override
    public void init() {
        gyro = hardwareMap.gyroSensor.get("gyro");
        gyro.calibrate();
        //mL = hardwareMap.dcMotor.get("mL");
        //mR = hardwareMap.dcMotor.get("mR");
        //mR.setDirection(DcMotor.Direction.REVERSE);
        //g1 = gamepad1;
    }

    @Override
    public void loop() {
        //double leftPower = g1.left_stick_y;
        //double rightPower = g1.right_stick_y;
        //mL.setPower(leftPower);
        //mR.setPower(rightPower);

        telemetry.addData("X-Y-Z-H", gyro.rawX() + "-" + gyro.rawY() + "-" + gyro.rawZ() + "-" + gyro.getHeading());
    }
}

package com.qualcomm.ftcrobotcontroller.opmodes.custom.util;

import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.hardware.GyroSensor;

/**
 * Created by Peter on 2/29/16.
 */
public class GyroTest5421 extends OpMode {

    GyroSensor gyro;
    //DcMotor mL;
    //DcMotor mR;
    //Gamepad g1;

    @Override
    public void init() {
        gyro = hardwareMap.gyroSensor.get("gyro");
        gyro.calibrate();
        //mL = hardwareMap.dcMotor.get("mL");
        //mL.setDirection(DcMotor.Direction.REVERSE);
        //mR = hardwareMap.dcMotor.get("mR");
        //g1 = gamepad1;
    }

    public void init_loop() {
        telemetry.addData("GYRO CALIBRATING:", gyro.isCalibrating());
    }

    @Override
    public void loop() {
        //double leftPower = g1.left_stick_y;
        //double rightPower = g1.right_stick_y;
        //mL.setPower(leftPower*0.5);
        //mR.setPower(rightPower*0.5);

        //telemetry.addData("X-Y-Z-H", gyro.rawX() + "-" + gyro.rawY() + "-" + gyro.rawZ() + "-" + gyro.getHeading());

        telemetry.addData("1. x", String.format("%03d", gyro.rawX()));
        telemetry.addData("2. y", String.format("%03d", gyro.rawY()));
        telemetry.addData("3. z", String.format("%03d", gyro.rawZ()));
        telemetry.addData("4. h", String.format("%03d", gyro.getHeading()));
        telemetry.addData("5. t", String.format("%05d", getRuntime()));
    }
}

Add more functionality to gyro test

Add more functionality to gyro test


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

import org.csstudio.display.builder.runtime.pv.RuntimePV;
import org.csstudio.display.builder.runtime.pv.RuntimePVFactory;
import org.csstudio.vtype.pv.PV;
import org.csstudio.vtype.pv.PVPool;

/** {@link RuntimePVFactory} for {@link PV}
 *
 *  @author Kay Kasemir
 */
public class VTypePVFactory implements RuntimePVFactory
{
    @Override
    public RuntimePV getPV(final String name) throws Exception
    {
        return new VTypePV(PVPool.getPV(name));
    }

    @Override
    public void releasePV(final RuntimePV pv)
    {
        PVPool.releasePV(((VTypePV)pv).getPV());
    }
}

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

import org.csstudio.display.builder.runtime.pv.RuntimePV;
import org.csstudio.display.builder.runtime.pv.RuntimePVFactory;
import org.csstudio.vtype.pv.PV;
import org.csstudio.vtype.pv.PVPool;

/** {@link RuntimePVFactory} for {@link PV}
 *
 *  @author Kay Kasemir
 */
public class VTypePVFactory implements RuntimePVFactory
{
    /** @param name PV Name that might contain legacy information
     *  @return Patched PV name
     */
    private String patch(String name)
    {
        // Remove PVManager's longString modifier.
        // Not using regular expression because text
        // had to be exactly like this at end of PV name.
        if (name.endsWith(" {\"longString\":true}"))
            name = name.substring(0,  name.length()-20);
        return name;
    }

    @Override
    public RuntimePV getPV(final String name) throws Exception
    {
        return new VTypePV(PVPool.getPV(patch(name)));
    }

    @Override
    public void releasePV(final RuntimePV pv)
    {
        PVPool.releasePV(((VTypePV)pv).getPV());
    }
}

PV: Patch 'longString' modifier for legacy PVM names


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

package org.springframework.boot.logging.java;

import java.util.logging.Formatter;
import java.util.logging.LogRecord;

/**
 * Simple test {@link Formatter}.
 *
 * @author Dave Syer
 */
public class TestFormatter extends Formatter {

	@Override
	public String format(LogRecord record) {
		return String.format("foo: %s -- %s%n", record.getLoggerName(), record.getMessage());
	}

}

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

package org.springframework.boot.logging.java;

import java.util.logging.Formatter;
import java.util.logging.LogRecord;

/**
 * Simple test {@link Formatter}.
 *
 * @author Dave Syer
 */
public class TestFormatter extends Formatter {

	@Override
	public String format(LogRecord record) {
		return String.format("foo: %s -- %s%n", record.getLoggerName(), record.getMessage());
	}

}

Update copyright of changed file

Update copyright of changed file

See gh-23571


package com.musitorika;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

Add H2DB service with initial SQL injection. Add test RESTfull API and index page.


package tars.commons.core;

/**
 * Container for user visible messages.
 */
public class Messages {

    public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command";
    public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s";
    public static final String MESSAGE_INVALID_DATE = "Invalid date";
    public static final String MESSAGE_INVALID_TASK_DISPLAYED_INDEX = "The task index provided is invalid";
    public static final String MESSAGE_PERSONS_LISTED_OVERVIEW = "%1$d tasks listed!";

}

package tars.commons.core;

/**
 * Container for user visible messages.
 */
public class Messages {

    public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command";
    public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s";
    public static final String MESSAGE_INVALID_DATE = "Invalid date";
    public static final String MESSAGE_INVALID_TASK_DISPLAYED_INDEX = "The task index provided is invalid";
    public static final String MESSAGE_PERSONS_LISTED_OVERVIEW = "%1$d tasks listed!";
    public static final String MESSAGE_TASK_CANNOT_BE_FOUND = "Task cannot be found!";
}

Add new message for task cannot be found


package net.simpvp.Misc;

import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

/**
 * Don't announce name changes for ops.
 */
public class AdminNameChange implements Listener {
	@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled=true)
	public void onPlayerJoin(PlayerJoinEvent event) {
		if (!event.getPlayer().isOp()) {
			return;
		}

		if (!event.getJoinMessage().matches("^.* \\(formerly known as .*$")) {
			return;
		}

		Misc.instance.getLogger().info("Removing name change info from: " + event.getJoinMessage());
		event.setJoinMessage(event.getJoinMessage().replaceFirst(" \\(formerly known as \\S+\\) ", " "));
	}
}

package net.simpvp.Misc;

import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

/**
 * Don't announce name changes for ops.
 */
public class AdminNameChange implements Listener {
	@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled=true)
	public void onPlayerJoin(PlayerJoinEvent event) {
		if (!event.getPlayer().isOp()) {
			return;
		}

		String jm = event.getJoinMessage();
		if (jm == null) {
			return;
		}

		if (!jm.matches("^.* \\(formerly known as .*$")) {
			return;
		}

		Misc.instance.getLogger().info("Removing name change info from: " + jm);
		event.setJoinMessage(jm.replaceFirst(" \\(formerly known as \\S+\\) ", " "));
	}
}

Fix exception on empty join messages

Fix exception on empty join messages


/*
Copyright 2020 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package com.google.gpay.virtualqueue.backendservice.repository;

import java.util.Map;
import java.util.UUID;

import com.google.gpay.virtualqueue.backendservice.model.Shop;
import com.google.gpay.virtualqueue.backendservice.proto.CreateShopRequest;

public interface VirtualQueueRepository {

    public UUID createShop(CreateShopRequest createShopRequest);

    public Map<UUID, Shop> getAllShops();
}

/*
Copyright 2020 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package com.google.gpay.virtualqueue.backendservice.repository;

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

import com.google.gpay.virtualqueue.backendservice.model.Shop;
import com.google.gpay.virtualqueue.backendservice.model.Token;
import com.google.gpay.virtualqueue.backendservice.proto.CreateShopRequest;

public interface VirtualQueueRepository {

    public UUID createShop(CreateShopRequest createShopRequest);

    public Map<UUID, Shop> getAllShops();

    public List<Token> getTokensByShopId(UUID shopId);
}

Add modified get tokens of a shop function


/*
 */
package org.datadryad.journalstatistics.statistics;

import java.util.ArrayList;
import java.util.List;
import org.datadryad.journalstatistics.extractor.DataPackageCount;
import org.dspace.core.Context;

/**
 *
 * @author Dan Leehr <dan.leehr@nescent.org>
 */
public class DefaultStatisticsPackage implements StatisticsPackage {
    private List<Statistic> statistics = new ArrayList<Statistic>();
    public DefaultStatisticsPackage(Context context) {
        statistics.add(new Statistic<Integer>("Data packages by journal", new DataPackageCount(context)));
    }
    @Override
    public void run(String journalName) {
        for(Statistic s : statistics) {
            s.extractAndStore(journalName);
            System.out.println(s);
        }
    }
}

/*
 */
package org.datadryad.journalstatistics.statistics;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.datadryad.journalstatistics.extractor.DataFileCount;
import org.datadryad.journalstatistics.extractor.DataFileTotalSize;
import org.datadryad.journalstatistics.extractor.DataPackageCount;
import org.datadryad.journalstatistics.extractor.DataPackageUnpublishedCount;
import org.datadryad.journalstatistics.extractor.EmbargoedDataFileCount;
import org.dspace.core.Context;

/**
 *
 * @author Dan Leehr <dan.leehr@nescent.org>
 */
public class DefaultStatisticsPackage implements StatisticsPackage {
    private List<Statistic> statistics = new ArrayList<Statistic>();
    public DefaultStatisticsPackage(Context context) {
        statistics.add(new Statistic<Integer>("Data packages count", new DataPackageCount(context)));
        statistics.add(new Statistic<Integer>("Data files count", new DataFileCount(context)));
        statistics.add(new Statistic<Long>("Data files total size", new DataFileTotalSize(context)));
        statistics.add(new Statistic<Map<String, Integer>>("Unpublished data packages", new DataPackageUnpublishedCount(context)));
        statistics.add(new Statistic<Integer>("Embargoed data files", new EmbargoedDataFileCount(context)));
    }
    @Override
    public void run(String journalName) {
        for(Statistic s : statistics) {
            s.extractAndStore(journalName);
            System.out.println(s);
        }
    }
}

Add extractors to default statistics package


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

/**
 * No operation class to remove checkstyle's fall-through try/catch block.
 * @author JunHo Yoon
 * @since 3.0
 */
public final class NoOp {
	/**
	 * Private Constructor not to make the instance.
	 */
	private NoOp() {
	}
	/**
	 * No operation.
	 */
	public static void noOp() {
	}
}

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

/**
 * No operation class to remove checkstyle's fall-through try/catch block.
 *
 * @author JunHo Yoon
 * @since 3.0
 */
public abstract class NoOp {

	/**
	 * No operation.
	 */
	public static void noOp() {
	}
}

[NGRINDER-588] Make noOp class abstract for consistency.


/*******************************************************************************
  * Copyright (c) 2012 Megha Nidhi Dahal.
  * All rights reserved. This program and the accompanying materials
  * are made available under the terms of the Eclipse Public License v1.0
  * which accompanies this distribution, and is available at
  * http://www.eclipse.org/legal/epl-v10.html
  *
  * Contributors:
  *    Megha Nidhi Dahal - initial API and implementation and/or initial documentation
  *******************************************************************************/
package org.eclipse.birt.report.data.oda.excel.ui.util;

public interface IHelpConstants
{

	public static final String PREFIX = "org.eclipse.datatools.oda.cshelp" + "."; //$NON-NLS-1$ //$NON-NLS-2$

	public static final String CONEXT_ID_DATASOURCE_EXCEL = PREFIX
			+ "Wizard_ExcelDatasource_ID";//$NON-NLS-1$

	public static final String CONEXT_ID_DATASET_EXCEL = PREFIX
			+ "Dialog_SelectTableColumn_ID";//$NON-NLS-1$

}

/*******************************************************************************
  * Copyright (c) 2012 Megha Nidhi Dahal.
  * All rights reserved. This program and the accompanying materials
  * are made available under the terms of the Eclipse Public License v1.0
  * which accompanies this distribution, and is available at
  * http://www.eclipse.org/legal/epl-v10.html
  *
  * Contributors:
  *    Megha Nidhi Dahal - initial API and implementation and/or initial documentation
  *******************************************************************************/
package org.eclipse.birt.report.data.oda.excel.ui.util;

public interface IHelpConstants
{

	public static final String PREFIX = "org.eclipse.datatools.oda.cshelp" + "."; //$NON-NLS-1$ //$NON-NLS-2$

	public static final String CONEXT_ID_DATASOURCE_EXCEL = PREFIX
			+ "Wizard_ExcelDatasource_ID";//$NON-NLS-1$

	public static final String CONEXT_ID_DATASET_EXCEL = PREFIX
			+ "Dialog_SelectExcelColumn_ID";//$NON-NLS-1$

}

Fix an issue - Edit excel data set page is using flat file's help document[60395].