/**
 * Copyright 2015 StreamSets Inc.
 *
 * Licensed under 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 com.streamsets.pipeline.stage.origin.hdfs.cluster;

import com.streamsets.pipeline.api.base.BaseEnumChooserValues;
import com.streamsets.pipeline.config.DataFormat;

public class DataFormatChooserValues extends BaseEnumChooserValues<DataFormat> {

  public DataFormatChooserValues() {
    super(DataFormat.TEXT, DataFormat.AVRO, DataFormat.DELIMITED);
  }

}

/**
 * Copyright 2015 StreamSets Inc.
 *
 * Licensed under 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 com.streamsets.pipeline.stage.origin.hdfs.cluster;

import com.streamsets.pipeline.api.base.BaseEnumChooserValues;
import com.streamsets.pipeline.config.DataFormat;

public class DataFormatChooserValues extends BaseEnumChooserValues<DataFormat> {

  public DataFormatChooserValues() {
    super(
      DataFormat.AVRO,
      DataFormat.DELIMITED,
      DataFormat.TEXT
    );
  }

}

Sort HDFS Origin file format options


/*
 * Kurento Android Media: Android Media Library based on FFmpeg.
 * Copyright (C) 2011  Tikal Technologies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.kurento.kas.media.rx;

/**
 *
 * @author mparis
 *
 */
public interface VideoRx {

	public void putVideoFrameRx(int[] rgb, int width, int height);

}

/*
 * Kurento Android Media: Android Media Library based on FFmpeg.
 * Copyright (C) 2011  Tikal Technologies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.kurento.kas.media.rx;

/**
 *
 * @author mparis
 *
 */
public interface VideoRx {

	public void putVideoFrameRx(int[] rgb, int width, int height, int nFrame);

}

Add nFrame parameter in putVideoFrameRx method.


/*
 * Kurento Android Media: Android Media Library based on FFmpeg.
 * Copyright (C) 2011  Tikal Technologies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.kurento.kas.media.rx;

public interface VideoRx {

	/**
	 * Receive a video frame.
	 *
	 * @param rgb
	 *            video frame in RGB32.
	 * @param width
	 *            frame width in pixels.
	 * @param height
	 *            frame height in pixels.
	 * @param nFrame
	 *            video frame id.
	 */
	public void putVideoFrameRx(int[] rgb, int width, int height, int nFrame);

}

/*
 * Kurento Android Media: Android Media Library based on FFmpeg.
 * Copyright (C) 2011  Tikal Technologies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.kurento.kas.media.rx;

public interface VideoRx {

	/**
	 * Receive a video frame.
	 *
	 * @param videoFrame
	 */
	public void putVideoFrameRx(VideoFrame videoFrame);

}

Use VideoFrame object as param in putVideoFrameRx method.


package com.destroystokyo.paperclip;

public class Main {

    public static void main(final String[] args) {
        System.out.println("WARNING: Java 9 currently causes significant issue for a lot of Bukkit plugins due to new ClassLoading semantics.");
        System.out.println("WARNING: For the time being, it is recommended to stick with Java 8 until plugins are updated.");

        Paperclip.run(args);
    }
}

package com.destroystokyo.paperclip;

public class Main {

    public static void main(final String[] args) {
        System.err.println("WARNING: Java 9 currently causes significant issues for a lot of Bukkit plugins due to new ClassLoading semantics.");
        System.err.println("WARNING: For the time being, it is recommended to stick with Java 8 until plugins are updated.");

        Paperclip.run(args);
    }
}

Use System.err to more highlight the warning messages


package com.edgardleal.benchmark.example;

import com.edgardleal.benchmark.Benchmark;
import org.apache.commons.beanutils.BeanUtils;

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

/**
 * Created by edgardleal on 24/07/16.
 */
public class BeanUtilsExample implements Runnable{

  public BeanUtilsExample() {

  }

  @Override
  public void run() {
    List<Cliente> list = new ArrayList<Cliente>();
    for (int i = 0; i < Benchmark.ITERATIONS; i++) {
      Cliente cliente = new Cliente("Teste", 5, 7.7, "Test street");
      Cliente second  = new Cliente();
      try {
        second = (Cliente) BeanUtils.cloneBean(cliente);
        list.add(second);
      }catch(Exception ex) {
        ex.printStackTrace();
      }
    }
  }
}

package com.edgardleal.benchmark.example;

import com.edgardleal.benchmark.Benchmark;
import org.apache.commons.beanutils.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.lang.reflect.Field;
import org.apache.commons.lang3.StringUtils;

/**
 * Created by edgardleal on 24/07/16.
 */
public class BeanUtilsExample {

  public BeanUtilsExample() {

  }

  public void timeBeanutils() {
    List<Cliente> list = new ArrayList<Cliente>();
    for (int i = 0; i < Benchmark.ITERATIONS; i++) {
      Cliente cliente = new Cliente("Teste", 5, 7.7, "Test street");
      Cliente second  = new Cliente();
      try {
        second = (Cliente) BeanUtils.cloneBean(cliente);
        list.add(second);
      }catch(Exception ex) {
        ex.printStackTrace();
      }
    }
  }

  public void timeReflection() {
      List<Cliente> list = new ArrayList<Cliente>();
      for (int i = 0; i < Benchmark.ITERATIONS; i++) {
        Cliente cliente = new Cliente("Teste", 5, 7.7, "Test street");
        Cliente second = new Cliente();
        try {
          Field fields[] = Cliente.class.getDeclaredFields();
          for (Field field : fields) {
            String capitalizedName = StringUtils.capitalize(field.getName());
            Cliente.class.getDeclaredMethod("set" + capitalizedName,
                field.getType()).invoke(second,
                Cliente.class.getDeclaredMethod("get" + capitalizedName).invoke(cliente, new Class<?>[0])
            );
            list.add(second);
          }
        } catch (Exception ex) {
          ex.printStackTrace();
        }
      }
  }
}

Improve to use with chart generator


package com.github.games647.lagmonitor;

public class RollingOverHistory {

    private final float[] samples;
    private float total;

    private int currentPosition = 1;
    private int currentSize = 1;

    public RollingOverHistory(int size, float firstValue) {
        this.samples = new float[size];
        samples[0] = firstValue;
    }

    public void add(float sample) {
        currentPosition++;
        if (currentPosition >= samples.length) {
            //we reached the end - go back to the beginning
            currentPosition = 0;
        }

        if (currentSize < samples.length) {
            //array is not full yet
            currentSize++;
        } else {
            //delete the latest sample which wil be overridden
            total -= samples[currentPosition];
        }

        total += sample;
        samples[currentPosition] = sample;
    }

    public float getAverage() {
        return total / currentSize;
    }

    public int getCurrentPosition() {
        return currentPosition;
    }

    public int getCurrentSize() {
        return currentSize;
    }

    public float getLastSample() {
        int lastPos = currentPosition - 1;
        if (lastPos < 0) {
            lastPos = samples.length - 1;
        }

        return samples[lastPos];
    }

    public float[] getSamples() {
        return samples;
    }
}

package com.github.games647.lagmonitor;

public class RollingOverHistory {

    private final float[] samples;
    private float total;

    private int currentPosition = 0;
    private int currentSize = 1;

    public RollingOverHistory(int size, float firstValue) {
        this.samples = new float[size];
        samples[0] = firstValue;
        total = firstValue;
    }

    public void add(float sample) {
        currentPosition++;
        if (currentPosition >= samples.length) {
            //we reached the end - go back to the beginning
            currentPosition = 0;
        }

        if (currentSize < samples.length) {
            //array is not full yet
            currentSize++;
        } else {
            //delete the latest sample which wil be overridden
            total -= samples[currentPosition];
        }

        total += sample;
        samples[currentPosition] = sample;
    }

    public float getAverage() {
        return total / currentSize;
    }

    public int getCurrentPosition() {
        return currentPosition;
    }

    public int getCurrentSize() {
        return currentSize;
    }

    public float getLastSample() {
        int lastPos = currentPosition;
        if (lastPos < 0) {
            lastPos = samples.length - 1;
        }

        return samples[lastPos];
    }

    public float[] getSamples() {
        return samples;
    }
}

Fix rolling over history and write unit test to prevent future bugs


package de.cinovo.cloudconductor.api.interfaces;

import de.cinovo.cloudconductor.api.IRestPath;
import de.cinovo.cloudconductor.api.MediaType;
import de.cinovo.cloudconductor.api.model.Settings;

import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

/**
 * Copyright 2017 Cinovo AG

 *

 *
 * @author psigloch
 */
@Path(IRestPath.SETTINGS)
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface ISettings {

	/**
	 * @return set of service objects
	 */
	@GET
	@RolesAllowed({"VIEW_CONFIGURATIONS","EDIT_CONFIGURATIONS"})
	Settings get();

	/**
	 * @param settings the settings to save
	 */
	@PUT
	@RolesAllowed({"EDIT_CONFIGURATIONS"})
	void save(Settings settings);
}

package de.cinovo.cloudconductor.api.interfaces;

import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import de.cinovo.cloudconductor.api.IRestPath;
import de.cinovo.cloudconductor.api.MediaType;
import de.cinovo.cloudconductor.api.model.Settings;

/**
 * Copyright 2017 Cinovo AG

 *

 *
 * @author psigloch
 */
@Path(IRestPath.SETTINGS)
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface ISettings {

	/**
	 * @return set of service objects
	 */
	@GET
	Settings get();

	/**
	 * @param settings the settings to save
	 */
	@PUT
	@RolesAllowed({"EDIT_CONFIGURATIONS"})
	void save(Settings settings);
}

Enable settings to be read without login.


package edu.northwestern.bioinformatics.studycalendar.web;

import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import org.springframework.mock.web.MockServletContext;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

/**
 * @author Rhett Sutphin
 */
public class WebTestCase extends StudyCalendarTestCase {
    protected MockHttpServletRequest request;
    protected MockHttpServletResponse response;
    protected MockServletContext servletContext;
    protected MockHttpSession session;

    protected void setUp() throws Exception {
        super.setUp();
        servletContext = new MockServletContext();
        session = new MockHttpSession(servletContext);
        request = new MockHttpServletRequest(servletContext);
        request.setMethod("POST");
        request.setSession(session);
        response = new MockHttpServletResponse();
    }
}

package edu.northwestern.bioinformatics.studycalendar.web;

import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import org.springframework.mock.web.MockServletContext;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

/**
 * @author Rhett Sutphin
 */
public abstract class WebTestCase extends StudyCalendarTestCase {
    protected MockHttpServletRequest request;
    protected MockHttpServletResponse response;
    protected MockServletContext servletContext;
    protected MockHttpSession session;

    protected void setUp() throws Exception {
        super.setUp();
        servletContext = new MockServletContext();
        session = new MockHttpSession(servletContext);
        request = new MockHttpServletRequest(servletContext);
        request.setMethod("POST");
        request.setSession(session);
        response = new MockHttpServletResponse();
    }
}

Mark abstract since it isn't separately runnable


package net.safedata.springboot.training.d02.s05.config;

import net.safedata.springboot.training.d02.s05.model.Product;
import net.safedata.springboot.training.d02.s05.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.PostConstruct;

/**
 * A simple {@link javax.sql.DataSource} configuration, which:
 *

 *
configures the JPA repositories, using the {@link EnableJpaRepositories} annotation

 *
inserts a simple {@link Product} in the database, using the auto-configured {@link javax.sql.DataSource}

 *

 */
@Configuration
@EnableJpaRepositories(basePackages = "net.safedata.springboot.training.d02.s05.repository")
@EnableTransactionManagement
public class DataSourceConfig {

    private final ProductService productService;

    @Autowired
    public DataSourceConfig(final ProductService productService) {
        this.productService = productService;
    }

    @PostConstruct
    public void init() {
        final Product product = new Product();
        product.setName("A default product");
        productService.create(product);
    }
}

package net.safedata.springboot.training.d02.s05.config;

import net.safedata.springboot.training.d02.s05.model.Product;
import net.safedata.springboot.training.d02.s05.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.PostConstruct;
import java.util.Random;
import java.util.stream.IntStream;

/**
 * A simple {@link javax.sql.DataSource} configuration, which:
 *

 *
configures the JPA repositories, using the {@link EnableJpaRepositories} annotation

 *
inserts a simple {@link Product} in the database, using the auto-configured {@link javax.sql.DataSource}

 *

 */
@Configuration
@EnableJpaRepositories(basePackages = "net.safedata.springboot.training.d02.s05.repository")
@EnableTransactionManagement
public class DataSourceConfig {

    private static final Random RANDOM = new Random(200);

    private final ProductService productService;

    @Autowired
    public DataSourceConfig(final ProductService productService) {
        this.productService = productService;
    }

    @PostConstruct
    public void init() {
        IntStream.range(0, 20)
                 .forEach(value -> {
                     final Product product = new Product();
                     product.setName("A default product with the ID " + RANDOM.nextInt());
                     productService.create(product);
                 });
    }
}

Insert several products in the database


package com.digirati.elucidate.infrastructure.security.impl;

import com.digirati.elucidate.infrastructure.security.UserSecurityDetails;
import com.digirati.elucidate.infrastructure.security.UserSecurityDetailsLoader;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;

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

public final class JwtUserAuthenticationConverter extends DefaultUserAuthenticationConverter {

    private List<String> uidProperties;
    private UserSecurityDetailsLoader securityDetailsLoader;

    public JwtUserAuthenticationConverter(List<String> uidProperties, UserSecurityDetailsLoader securityDetailsLoader) {
        this.uidProperties = uidProperties;
        this.securityDetailsLoader = securityDetailsLoader;
    }

    @Override
    public Authentication extractAuthentication(Map<String, ?> details) {
        return uidProperties.stream()
            .filter(details::containsKey)
            .map(prop -> (String) details.get(prop))
            .findFirst()
            .map(uid -> {
                UserSecurityDetails securityDetails = securityDetailsLoader.findOrCreateUserDetails(uid);
                Authentication auth = new UsernamePasswordAuthenticationToken(
                    securityDetails,
                    "N/A",
                    Collections.emptySet()
                );

                return auth;
            })
            .orElse(null);
    }
}

package com.digirati.elucidate.infrastructure.security.impl;

import com.digirati.elucidate.infrastructure.security.UserSecurityDetails;
import com.digirati.elucidate.infrastructure.security.UserSecurityDetailsLoader;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;

public final class JwtUserAuthenticationConverter extends DefaultUserAuthenticationConverter {

    private List<String> uidProperties;
    private UserSecurityDetailsLoader securityDetailsLoader;

    public JwtUserAuthenticationConverter(List<String> uidProperties, UserSecurityDetailsLoader securityDetailsLoader) {
        this.uidProperties = uidProperties;
        this.securityDetailsLoader = securityDetailsLoader;
    }

    @Override
    public Authentication extractAuthentication(Map<String, ?> details) {
        return uidProperties.stream()
            .filter(details::containsKey)
            .map(prop -> (String) details.get(prop))
            .findFirst()
            .map(uid -> {
                UserSecurityDetails securityDetails = securityDetailsLoader.findOrCreateUserDetails(uid);
                Collection<String> roles = (Collection<String>) details.get(AUTHORITIES);

                if (roles == null) {
                    roles = Collections.emptyList();
                }

                List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(roles.toArray(new String[0]));
                Authentication auth = new UsernamePasswordAuthenticationToken(
                    securityDetails,
                    "N/A",
                    authorities
                );

                return auth;
            })
            .orElse(null);
    }
}

Fix decoding of admin authorities from access tokens


package fr.synchrotron.soleil.ica.ci.service.multirepoproxy;

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

/**
 * @author Gregory Boissinot
 */
public class RepositoryScanner {

    private List<RepositoryObject> repos = new ArrayList<RepositoryObject>();

    public RepositoryScanner(List<RepositoryObject> repoList) {
        if (repoList == null) {
            throw new NullPointerException("A list of repo is required.");
        }
        this.repos = repoList;
    }

    public boolean isLastRepo(int index) {
        return index == repos.size() - 1;
    }

    public RepositoryObject getRepoFromIndex(int index) {
        return repos.get(index);
    }

    public int getNextIndex(int index) {
        return ++index;
    }

}

package fr.synchrotron.soleil.ica.ci.service.multirepoproxy;

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

/**
 * @author Gregory Boissinot
 */
public class RepositoryScanner {

    private List<RepositoryObject> repos = new ArrayList<RepositoryObject>();

    public RepositoryScanner(List<RepositoryObject> repoList) {
        if (repoList == null) {
            throw new NullPointerException("A list of repo is required.");
        }
        this.repos = repoList;
    }

    public boolean isLastRepo(int index) {
        return index == -1;
    }

    public RepositoryObject getRepoFromIndex(int index) {
        return repos.get(index);
    }

    public int getNextIndex(int index) {
        int nextIndex = ++index;
        if (nextIndex > repos.size() - 1) {
            return -1;
        }
        return nextIndex;
    }

}

Fix last repo. Use a limit


package org.helioviewer.jhv.plugins.swek.sources.comesep;

public class ComesepEventStream {

}

package org.helioviewer.jhv.plugins.swek.sources.comesep;

import java.util.LinkedList;
import java.util.Queue;

import org.helioviewer.jhv.data.datatype.event.JHVEvent;
import org.helioviewer.jhv.plugins.swek.sources.SWEKEventStream;

public class ComesepEventStream implements SWEKEventStream {

    /** Queue with events */
    Queue<JHVEvent> eventQueue = new LinkedList<JHVEvent>();

    public ComesepEventStream() {
        eventQueue = new LinkedList<JHVEvent>();
    }

    @Override
    public boolean hasEvents() {
        return !eventQueue.isEmpty();
    }

    @Override
    public JHVEvent next() {
        return eventQueue.poll();
    }

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

    public void addJHVEvent(ComesepEvent currentEvent) {
        eventQueue.add(currentEvent);
    }

}

Implement the comesep event stream


class Str2 {
	public static void main (String args[]) {
		String a = "1";
		a += "2";
		System.out.println(a);
	}
}

/* Expected Output:
12
*/

class Str2 {
	public static void main (String args[]) {
		String a = "1";
		a += "2";
		System.out.println(a);
		System.out.println("abc".indexOf("", -32));
		System.out.println("abc".indexOf("", 100));
		System.out.println("abc".lastIndexOf("", -32));
		System.out.println("abc".lastIndexOf("", 100));
	}
}

/* Expected Output:
12
0
-1
-1
3
*/

Add checks for indexOf() and lastIndexOf() with empty string arguments


package com.screaminggreen.sculptor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.screaminggreen.beans.ProfessorBean;
import com.screaminggreen.beans.SessionBean;
import com.screaminggreen.datastore.CourseTab;
import com.screaminggreen.datastore.DatastoreAPI;
import com.screaminggreen.datastore.Professor;

@SuppressWarnings("serial")
public class SearchServlet extends HttpServlet {

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

		PrintWriter out = resp.getWriter();

        Iterable<Entity> entities = Professor.getAllProfessors("Professor");

        String json = DatastoreAPI.writeJSON(entities);

        System.out.println(json);

        resp.setStatus(200);
        out.println(json);

        out.close();

	}

}

package com.screaminggreen.sculptor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.screaminggreen.beans.ProfessorBean;
import com.screaminggreen.beans.SessionBean;
import com.screaminggreen.datastore.CourseTab;
import com.screaminggreen.datastore.DatastoreAPI;
import com.screaminggreen.datastore.Professor;

@SuppressWarnings("serial")
public class SearchServlet extends HttpServlet {

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

		PrintWriter out = resp.getWriter();

        Iterable<Entity> entities = Professor.getAllProfessors("Professor");

        String json = DatastoreAPI.writeJSON(entities);

        resp.setStatus(200);

        out.println(json);

        out.close();

	}

}

Clean up for autocomplete servlet


package ru.stqua.pft.addressbook.tests;

import org.testng.Assert;
import org.testng.annotations.Test;
import ru.stqua.pft.addressbook.model.GroupData;

import java.util.HashSet;
import java.util.List;

public class GroupCreationTests extends TestBase{

  @Test
  public void testGroupCreation() {
    app.getNavigationHelper().gotoGroupPage();
    List<GroupData> before = app.getGroupHelper().getGroupList();
    GroupData group = new GroupData("test1", null, null);
    app.getGroupHelper().createGroup(group);
    List<GroupData> after = app.getGroupHelper().getGroupList();

    Assert.assertEquals(after.size(), before.size() + 1);

    int max = 0;
    for (GroupData g : after){
      if (g.getId() > max){
        max = g.getId();
      }
    }
    group.setId(max);
    before.add(group);
    Assert.assertEquals(new HashSet<Object>(before), new HashSet<Object>(after));
  }

}

package ru.stqua.pft.addressbook.tests;

import org.testng.Assert;
import org.testng.annotations.Test;
import ru.stqua.pft.addressbook.model.GroupData;

import java.util.HashSet;
import java.util.List;

public class GroupCreationTests extends TestBase{

  @Test
  public void testGroupCreation() {
    app.getNavigationHelper().gotoGroupPage();
    List<GroupData> before = app.getGroupHelper().getGroupList();
    GroupData group = new GroupData("test2", null, null);
    app.getGroupHelper().createGroup(group);
    List<GroupData> after = app.getGroupHelper().getGroupList();

    Assert.assertEquals(after.size(), before.size() + 1);

    group.setId(after.stream().max((o1, o2) -> Integer.compare(o1.getId(), o2.getId())).get().getId());
    before.add(group);
    Assert.assertEquals(new HashSet<Object>(before), new HashSet<Object>(after));
  }

}

Add Example 9 Lesson 4


package org.collectionspace.services.jaxrs;

import org.collectionspace.services.CollectionObjectResource;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;

public class CollectionSpaceJaxRsApplication extends Application {

    private Set<Object> singletons = new HashSet<Object>();
    private Set<Class<?>> empty = new HashSet<Class<?>>();

    public CollectionSpaceJaxRsApplication() {
        singletons.add(new CollectionObjectResource());
//        singletons.add(new DomainIdentifierResource());
//        singletons.add(new PingResource());
    }

    @Override
    public Set<Class<?>> getClasses() {
        return empty;
    }

    @Override
    public Set<Object> getSingletons() {
        return singletons;
    }
}

package org.collectionspace.services.jaxrs;

import org.collectionspace.services.CollectionObjectResource;
import org.collectionspace.services.IntakeResource;

import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;

public class CollectionSpaceJaxRsApplication extends Application {

    private Set<Object> singletons = new HashSet<Object>();
    private Set<Class<?>> empty = new HashSet<Class<?>>();

    public CollectionSpaceJaxRsApplication() {
        singletons.add(new CollectionObjectResource());
        singletons.add(new IntakeResource());
//        singletons.add(new DomainIdentifierResource());
//        singletons.add(new PingResource());
    }

    @Override
    public Set<Class<?>> getClasses() {
        return empty;
    }

    @Override
    public Set<Object> getSingletons() {
        return singletons;
    }
}

Add new singleton for Intake resource


package devopsdistilled.operp.client.party.panes.controllers.impl;

import javax.inject.Inject;

import devopsdistilled.operp.client.exceptions.EntityValidationException;
import devopsdistilled.operp.client.party.panes.CreateVendorPane;
import devopsdistilled.operp.client.party.panes.controllers.CreateVendorPaneController;
import devopsdistilled.operp.client.party.panes.models.CreateVendorPaneModel;
import devopsdistilled.operp.server.data.entity.party.Vendor;

public class CreateVendorPaneControllerImpl implements
		CreateVendorPaneController {

	@Inject
	private CreateVendorPane view;

	@Inject
	private CreateVendorPaneModel model;

	@Override
	public void validate(Vendor entity) throws EntityValidationException {
		// TODO Auto-generated method stub

	}

	@Override
	public Vendor save(Vendor entity) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void init() {
		view.init();
		model.registerObserver(view);
	}

}

package devopsdistilled.operp.client.party.panes.controllers.impl;

import javax.inject.Inject;
import javax.swing.JPanel;

import devopsdistilled.operp.client.commons.panes.controllers.CreateContactInfoPaneController;
import devopsdistilled.operp.client.exceptions.EntityValidationException;
import devopsdistilled.operp.client.party.panes.CreateVendorPane;
import devopsdistilled.operp.client.party.panes.controllers.CreateVendorPaneController;
import devopsdistilled.operp.client.party.panes.models.CreateVendorPaneModel;
import devopsdistilled.operp.server.data.entity.party.Vendor;

public class CreateVendorPaneControllerImpl implements
		CreateVendorPaneController {

	@Inject
	private CreateVendorPane view;

	@Inject
	private CreateVendorPaneModel model;

	@Inject
	private CreateContactInfoPaneController createContactInfoPaneController;

	@Override
	public void validate(Vendor entity) throws EntityValidationException {
		// TODO Auto-generated method stub

	}

	@Override
	public Vendor save(Vendor entity) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void init() {
		createContactInfoPaneController.getView().setController(
				createContactInfoPaneController);
		view.setContactInfopanel((JPanel) createContactInfoPaneController
				.getView().getPane());
		view.init();
		model.registerObserver(view);
	}

}

Add ContactInfo pane to create vendor pane


package org.python.pydev.debug.ui;

import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IAdaptable;
import org.python.pydev.editor.codecompletion.revisited.PythonPathHelper;
import org.python.pydev.navigator.elements.IWrappedResource;

public class PythonTypePropertyTester extends PropertyTester {

    public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
        IFile iFile = getIFile(receiver);
        if (iFile != null) {
            if (PythonPathHelper.markAsPyDevFileIfDetected(iFile)) {
                return true;
            }
        }
        return false;
    }

    private IFile getIFile(Object receiver) {
        if (receiver instanceof IWrappedResource) {
            IWrappedResource wrappedResource = (IWrappedResource) receiver;
            Object actualObject = wrappedResource.getActualObject();
            if (actualObject instanceof IFile) {
                return (IFile) actualObject;
            }
        }
        if (receiver instanceof IAdaptable) {
            IAdaptable iAdaptable = (IAdaptable) receiver;
            return (IFile) iAdaptable.getAdapter(IFile.class);
        }
        return null;
    }

}

package org.python.pydev.debug.ui;

import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IAdaptable;
import org.python.pydev.editor.codecompletion.revisited.PythonPathHelper;
import org.python.pydev.navigator.elements.IWrappedResource;

public class PythonTypePropertyTester extends PropertyTester {

    public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {

        IFile iFile = null;

        if (receiver instanceof IWrappedResource) {
            IWrappedResource wrappedResource = (IWrappedResource) receiver;
            Object actualObject = wrappedResource.getActualObject();
            if (actualObject instanceof IProject) {
                return true;
            } else if (actualObject instanceof IFile) {
                iFile = (IFile) actualObject;
            }
        }
        if (receiver instanceof IAdaptable) {
            IAdaptable iAdaptable = (IAdaptable) receiver;
            iFile = (IFile) iAdaptable.getAdapter(IFile.class);
        }

        if (iFile != null) {
            if (PythonPathHelper.markAsPyDevFileIfDetected(iFile)) {
                return true;
            }
        }
        return false;
    }

}

Allow Pydev launch shortcuts from context of Pydev project selection.


package com.github.arteam.dropwizard.http2.client;

import io.dropwizard.setup.Environment;
import org.eclipse.jetty.client.HttpClient;

/**
 * Date: 11/26/15
 * Time: 10:22 AM
 * <p>
 * A builder for {@link HttpClient}. It builds an instance from an external
 * configuration and ties it to Dropwizard environment.
 *
 * @author Artem Prigoda
 */
public class JettyHttpClientBuilder {

    private Environment environment;
    private Http2ClientConfiguration configuration;

    public JettyHttpClientBuilder(Environment environment) {
        this.environment = environment;
    }

    public JettyHttpClientBuilder using(Http2ClientConfiguration configuration) {
        this.configuration = configuration;
        return this;
    }

    public HttpClient build(String name) {
        ClientTransportFactory connectionFactoryBuilder = configuration.getConnectionFactoryBuilder();
        HttpClient httpClient = new HttpClient(
                connectionFactoryBuilder.httpClientTransport(environment.metrics(), name),
                connectionFactoryBuilder.sslContextFactory());
        environment.lifecycle().manage(httpClient);
        return httpClient;
    }

    public HttpClient build() {
        return build("");
    }
}

package com.github.arteam.dropwizard.http2.client;

import io.dropwizard.setup.Environment;
import org.eclipse.jetty.client.HttpClient;

/**
 * Date: 11/26/15
 * Time: 10:22 AM
 * <p>
 * A builder for {@link HttpClient}. It builds an instance from an external
 * configuration and ties it to Dropwizard environment.
 *
 * @author Artem Prigoda
 */
public class JettyHttpClientBuilder {

    private Environment environment;
    private Http2ClientConfiguration configuration = new Http2ClientConfiguration();

    public JettyHttpClientBuilder(Environment environment) {
        this.environment = environment;
    }

    public JettyHttpClientBuilder using(Http2ClientConfiguration configuration) {
        this.configuration = configuration;
        return this;
    }

    public HttpClient build(String name) {
        ClientTransportFactory connectionFactoryBuilder = configuration.getConnectionFactoryBuilder();
        HttpClient httpClient = new HttpClient(
                connectionFactoryBuilder.httpClientTransport(environment.metrics(), name),
                connectionFactoryBuilder.sslContextFactory());
        environment.lifecycle().manage(httpClient);
        return httpClient;
    }

    public HttpClient build() {
        return build("");
    }
}

Set H2 over TLS as the default configuration


import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;

public class Board extends JPanel  {
	 private JButton[][] buttons = new JButton[5][5];

  public Board() {
	  super(new GridLayout(5,5));

       for(int row=0; row<buttons.length; row++){
           for(int col=0; col<buttons.length; col++){

             JButton b = new JButton ("("+row+","+col+")");
             this.buttons[row][col] = b;
             this.add(b);

           }
       }

   }

   public JButton getSpot(int x, int y) {
       return buttons[x][y];
   }

}

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class Board extends JPanel  {
	Tile[][] buttons;

	public Board(int rows, int cols) {
		super(new GridLayout(rows, cols));
		buttons = new Tile[rows][cols];
		BufferedImage puzzle = null;
		try {
			puzzle = ImageIO.read(new File("Images/pic1.jpg"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		int width = puzzle.getWidth();
		int height = puzzle.getHeight();

		for(int row = 0; row < rows; row++){
			for(int col = 0; col < cols; col++){
				Tile tile = new Tile(row, col);
				buttons[row][col] = tile;
				if (!(row == 0 && col == 0)) {
					BufferedImage cropped = puzzle.getSubimage(
							col * width / cols, row * height / rows, width / cols, height / rows);
					tile.setIcon(new ImageIcon(cropped));
				}
				tile.setBackground(Color.GRAY);
				//tile.addActionListener(new TileListener());
				this.add(tile);
			}
		}
	}

	public void checkIfComplete() {
		for (Tile[] tiles : buttons) {
			for (Tile tile : tiles) {
				if (!tile.hasRightImage()) {
					return;
				}
			}
		}
//		Window.endGame();
	}

}

Implement split image board with a variable number of tiles.


/**
 * Copyright (C) 2011 rwoo@gmx.de
 *
 * 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.googlecode.catchexception;

@SuppressWarnings("javadoc")
public interface Something {

    public void doNothing();

    public void doThrow();

    public void doThrowAssertionError();

}

/**
 * Copyright (C) 2011 rwoo@gmx.de
 *
 * 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.googlecode.catchexception;

@SuppressWarnings("javadoc")
public interface Something {

    void doNothing();

    void doThrow();

    void doThrowAssertionError();

}

Remove duplicate public in interface


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

import com.yahoo.config.model.ConfigModelContext;
import com.yahoo.config.model.builder.xml.ConfigModelId;
import com.yahoo.vespa.model.clients.Clients;
import org.w3c.dom.Element;

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

/**
 * Builds the Clients plugin
 *
 * @author hmusum
 */
public class DomClientsBuilder extends LegacyConfigModelBuilder<Clients> {

    public DomClientsBuilder() {
        super(Clients.class);
    }

    @Override
    public List<ConfigModelId> handlesElements() {
        return Arrays.asList(ConfigModelId.fromNameAndVersion("clients", "2.0"));
    }

    @Override
    public void doBuild(Clients clients, Element clientsE, ConfigModelContext modelContext) {
        String version = clientsE.getAttribute("version");
        if (version.startsWith("2.")) {
            DomV20ClientsBuilder parser = new DomV20ClientsBuilder(clients, version);
            parser.build(modelContext.getDeployState(), clientsE);
        } else {
            throw new IllegalArgumentException("Version '" + version + "' of 'clients' not supported.");
        }
    }

}

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

import com.yahoo.config.model.ConfigModelContext;
import com.yahoo.config.model.builder.xml.ConfigModelId;
import com.yahoo.vespa.model.clients.Clients;
import org.w3c.dom.Element;

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

/**
 * Builds the Clients plugin
 *
 * @author hmusum
 */
public class DomClientsBuilder extends LegacyConfigModelBuilder<Clients> {

    public DomClientsBuilder() {
        super(Clients.class);
    }

    @Override
    public List<ConfigModelId> handlesElements() {
        return Arrays.asList(ConfigModelId.fromNameAndVersion("clients", "2.0"));
    }

    @Override
    public void doBuild(Clients clients, Element clientsE, ConfigModelContext modelContext) {
        String version = clientsE.getAttribute("version");
        if (version.startsWith("2.")) {
            DomV20ClientsBuilder parser = new DomV20ClientsBuilder(clients, version);
            parser.build(clientsE);
        } else {
            throw new IllegalArgumentException("Version '" + version + "' of 'clients' not supported.");
        }
    }

}

Remove deployState parameter, forgotten during rebase to master.


package com.hubspot.singularity.resources;

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

import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.hubspot.singularity.config.SingularityConfiguration;
import com.hubspot.singularity.views.IndexView;

import static com.hubspot.singularity.SingularityMainModule.SINGULARITY_URI_BASE;

@Singleton
@Path("/{uiPath:.*}")
public class StaticCatchallResource {
  private final SingularityConfiguration configuration;
  private final String singularityUriBase;

  @Inject
  public StaticCatchallResource(@Named(SINGULARITY_URI_BASE) String singularityUriBase, SingularityConfiguration configuration) {
    this.configuration = configuration;
    this.singularityUriBase = singularityUriBase;
  }

  @GET
  @Produces(MediaType.TEXT_HTML)
  public IndexView getIndex() {
    return new IndexView(singularityUriBase, "/", configuration);
  }
}

package com.hubspot.singularity.resources;

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

import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.hubspot.singularity.config.SingularityConfiguration;
import com.hubspot.singularity.views.IndexView;

import static com.hubspot.singularity.SingularityMainModule.SINGULARITY_URI_BASE;

@Singleton
@Path("/{uiPath:.*}")
public class StaticCatchallResource {
  private final SingularityConfiguration configuration;
  private final String singularityUriBase;

  @Inject
  public StaticCatchallResource(@Named(SINGULARITY_URI_BASE) String singularityUriBase, SingularityConfiguration configuration) {
    this.configuration = configuration;
    this.singularityUriBase = singularityUriBase;
  }

  @GET
  @Produces(MediaType.TEXT_HTML)
  public IndexView getIndex() {
    return new IndexView(singularityUriBase, "", configuration);
  }
}

Fix appRoot for catchall resource.


package edu.duke.cabig.c3pr.dao;

import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import edu.duke.cabig.c3pr.domain.PlannedNotification;
import edu.duke.cabig.c3pr.domain.RecipientScheduledNotification;

/**
 * Hibernate implementation of ArmDao
 *
 * @see edu.duke.cabig.c3pr.dao.RecipientScheduledNotificationDao
 * @author Priyatam
 */
public class RecipientScheduledNotificationDao extends GridIdentifiableDao<RecipientScheduledNotification> {

    @Override
    public Class<RecipientScheduledNotification> domainClass() {
        return RecipientScheduledNotification.class;
    }

    /*
     * Returns all Arm objects (non-Javadoc)
     *
     * @see edu.duke.cabig.c3pr.dao.Arm#getAll()
     */
    @Transactional(readOnly=true)
    public List<RecipientScheduledNotification> getAll() {
        return getHibernateTemplate().find("from RecipientScheduledNotification");
    }

    @Transactional(readOnly=true)
    public RecipientScheduledNotification getInitializedRecipientScheduledNotificationById(int id){
    	RecipientScheduledNotification recipientScheduledNotification = getById(id);
    	return recipientScheduledNotification;
    }

    @Transactional(readOnly=false)
    public void saveOrUpdate(RecipientScheduledNotification recipientScheduledNotification){
    	//do not remove the flush...imperative for the notifications flow.
    	getHibernateTemplate().saveOrUpdate(recipientScheduledNotification);
    	getHibernateTemplate().flush();
    }
}

package edu.duke.cabig.c3pr.dao;

import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import edu.duke.cabig.c3pr.domain.PlannedNotification;
import edu.duke.cabig.c3pr.domain.RecipientScheduledNotification;

/**
 * Hibernate implementation of ArmDao
 *
 * @see edu.duke.cabig.c3pr.dao.RecipientScheduledNotificationDao
 * @author Priyatam
 */
public class RecipientScheduledNotificationDao extends GridIdentifiableDao<RecipientScheduledNotification> {

    @Override
    public Class<RecipientScheduledNotification> domainClass() {
        return RecipientScheduledNotification.class;
    }

    /*
     * Returns all Arm objects (non-Javadoc)
     *
     * @see edu.duke.cabig.c3pr.dao.Arm#getAll()
     */
    @Transactional(readOnly=true)
    public List<RecipientScheduledNotification> getAll() {
        return getHibernateTemplate().find("from RecipientScheduledNotification");
    }

    //readOnly was chnaged from true to false to get notifications to work on ORacle
    @Transactional(readOnly=false)
    public RecipientScheduledNotification getInitializedRecipientScheduledNotificationById(int id){
    	RecipientScheduledNotification recipientScheduledNotification = getById(id);
    	return recipientScheduledNotification;
    }

    @Transactional(readOnly=false)
    public void saveOrUpdate(RecipientScheduledNotification recipientScheduledNotification){
    	//do not remove the flush...imperative for the notifications flow.
    	getHibernateTemplate().saveOrUpdate(recipientScheduledNotification);
    	getHibernateTemplate().flush();
    }
}

Fix for the failing notfns on Oracle


package com.github.kristofa.brave.resteasyexample;

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

import com.github.kristofa.brave.Brave;
import com.github.kristofa.brave.SpanCollector;

/**
 * {@link SpanCollector} spring dependency injection configuration.
 *
 * @author kristof
 */
@Configuration
public class SpanCollectorConfiguration {

    @Bean
    @Scope(value = "singleton")
    public SpanCollector spanCollector() {

        // For development purposes we use the logging span collector.
        return Brave.getLoggingSpanCollector();
    }
}

package com.github.kristofa.brave.resteasyexample;

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

import com.github.kristofa.brave.LoggingSpanCollectorImpl;
import com.github.kristofa.brave.SpanCollector;

/**
 * {@link SpanCollector} spring dependency injection configuration.
 *
 * @author kristof
 */
@Configuration
public class SpanCollectorConfiguration {

    @Bean
    @Scope(value = "singleton")
    public SpanCollector spanCollector() {

        // For development purposes we use the logging span collector.
        return new LoggingSpanCollectorImpl();
    }
}

Fix to make compatible with brave-impl changes. LoggingSpanCollectorImpl is public class and not to be instantiated through com.github.kristofa.brave.Brave anymore.


/********************************************************************************
 * Copyright (c) 2019 Stephane Bastian
 *
 * This program and the accompanying materials are made available under the 2
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * SPDX-License-Identifier: EPL-2.0 3
 *
 * Contributors: 4
 *   Stephane Bastian - initial API and implementation
 ********************************************************************************/
package io.vertx.ext.auth.authorization;

import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.MultiMap;
import io.vertx.ext.auth.User;

/**
 * The AuthorizationContext contains properties that can be used to match
 * authorizations.
 *
 * @author Stephane Bastian
 *
 */
@VertxGen
public interface AuthorizationContext {

  /**
   * Get the authenticated user
   *
   * @return the user
   */
  User user();

  /**
   * @return a Multimap containing variable names and values that can be resolved
   *         at runtime by {@link Authorization}Authorizations
   */
  MultiMap variables();

}

/********************************************************************************
 * Copyright (c) 2019 Stephane Bastian
 *
 * This program and the accompanying materials are made available under the 2
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * SPDX-License-Identifier: EPL-2.0 3
 *
 * Contributors: 4
 *   Stephane Bastian - initial API and implementation
 ********************************************************************************/
package io.vertx.ext.auth.authorization;

import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.MultiMap;
import io.vertx.ext.auth.User;
import io.vertx.ext.auth.authorization.impl.AuthorizationContextImpl;

/**
 * The AuthorizationContext contains properties that can be used to match
 * authorizations.
 *
 * @author Stephane Bastian
 *
 */
@VertxGen
public interface AuthorizationContext {

  /**
   * Factory for Authorization Context
   * @param user a user
   * @return a AuthorizationContext instance
   */
  static AuthorizationContext create(User user) {
    return new AuthorizationContextImpl(user);
  }

  /**
   * Get the authenticated user
   *
   * @return the user
   */
  User user();

  /**
   * @return a Multimap containing variable names and values that can be resolved
   *         at runtime by {@link Authorization}Authorizations
   */
  MultiMap variables();

}

Add factory to avoid referring to impl classes from other modules


/*******************************************************************************
 * Copyright (c) 2016 Red Hat Inc and others.
 * 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:
 *     Red Hat Inc - initial API and implementation
 *******************************************************************************/
package org.eclipse.kura.camel.runner;

import org.apache.camel.CamelContext;

public interface RoutesProvider {

    /**
     * Apply the desired state of camel routes to the context
     *

     * Note:  This method may need to stop and remove
     * routes which are no longer used
     *

     *
     * @param camelContext
     *            the context the routes should by applied to
     * @throws Exception
     *             if anything goes wrong
     */
    public void applyRoutes(CamelContext camelContext) throws Exception;
}

/*******************************************************************************
 * Copyright (c) 2016, 2017 Red Hat Inc and others.
 * 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:
 *     Red Hat Inc - initial API and implementation
 *******************************************************************************/
package org.eclipse.kura.camel.runner;

import org.apache.camel.CamelContext;

@FunctionalInterface
public interface RoutesProvider {

    /**
     * Apply the desired state of camel routes to the context
     *

     * Note:  This method may need to stop and remove
     * routes which are no longer used
     *

     *
     * @param camelContext
     *            the context the routes should by applied to
     * @throws Exception
     *             if anything goes wrong
     */
    public void applyRoutes(CamelContext camelContext) throws Exception;
}

Make it a functional interface


package mib.microservice.commons.kafka;

import java.util.Map;
import java.util.Properties;

/**
 * Default/fallback config properties for a kafka producer
 *
 * @author knittl
 *
 */
public class KafkaProducerDefaultProperties extends Properties {
	private static final long serialVersionUID = 1L;

	public KafkaProducerDefaultProperties() {
		this.put("serializer.class", "mib.microservices.util.JsonEncoder");
		this.put("key.serializer.class", "kafka.serializer.StringEncoder");
		this.put("partitioner.class", "kafka.producer.DefaultPartitioner");
		this.put("request.required.acks", "1");
	}

	public KafkaProducerDefaultProperties(Map<String, String> props) {
		this();

		this.putAll(props);
	}
}

package mib.microservice.commons.kafka;

import java.util.Map;
import java.util.Properties;

/**
 * Default/fallback config properties for a kafka producer
 *
 * @author knittl
 *
 */
public class KafkaProducerDefaultProperties extends Properties {
	private static final long serialVersionUID = 1L;

	public KafkaProducerDefaultProperties() {
		this.put("serializer.class", JsonEncoder.class.getName());
		this.put("key.serializer.class", kafka.serializer.StringEncoder.class.getName());
		this.put("partitioner.class", kafka.producer.DefaultPartitioner.class.getName());
		this.put("request.required.acks", "1");
	}

	public KafkaProducerDefaultProperties(Map<String, String> props) {
		this();

		this.putAll(props);
	}
}

Use .class.getName() instead of hardcoded strings in default properties


package com.thinkaurelius.titan.diskstorage.cassandra;

import static com.thinkaurelius.titan.diskstorage.cassandra.AbstractCassandraStoreManager.CASSANDRA_READ_CONSISTENCY;
import static com.thinkaurelius.titan.diskstorage.cassandra.AbstractCassandraStoreManager.CASSANDRA_WRITE_CONSISTENCY;

import com.google.common.base.Preconditions;
import com.thinkaurelius.titan.diskstorage.TransactionHandleConfig;
import com.thinkaurelius.titan.diskstorage.common.AbstractStoreTransaction;
import com.thinkaurelius.titan.diskstorage.keycolumnvalue.StoreTransaction;

public class CassandraTransaction extends AbstractStoreTransaction {

    public CassandraTransaction(TransactionHandleConfig c) {
        super(c);
    }

    public CLevel getReadConsistencyLevel() {
        return CLevel.parse(getConfiguration().getCustomOption(CASSANDRA_READ_CONSISTENCY));
    }

    public CLevel getWriteConsistencyLevel() {
        return CLevel.parse(getConfiguration().getCustomOption(CASSANDRA_WRITE_CONSISTENCY));
    }

    public static CassandraTransaction getTx(StoreTransaction txh) {
        Preconditions.checkArgument(txh != null);
        Preconditions.checkArgument(txh instanceof CassandraTransaction, "Unexpected transaction type %s", txh.getClass().getName());
        return (CassandraTransaction) txh;
    }
}

package com.thinkaurelius.titan.diskstorage.cassandra;

import static com.thinkaurelius.titan.diskstorage.cassandra.AbstractCassandraStoreManager.CASSANDRA_READ_CONSISTENCY;
import static com.thinkaurelius.titan.diskstorage.cassandra.AbstractCassandraStoreManager.CASSANDRA_WRITE_CONSISTENCY;

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

import com.google.common.base.Preconditions;
import com.thinkaurelius.titan.diskstorage.TransactionHandleConfig;
import com.thinkaurelius.titan.diskstorage.common.AbstractStoreTransaction;
import com.thinkaurelius.titan.diskstorage.keycolumnvalue.StoreTransaction;

public class CassandraTransaction extends AbstractStoreTransaction {

    private static final Logger log = LoggerFactory.getLogger(CassandraTransaction.class);

    public CassandraTransaction(TransactionHandleConfig c) {
        super(c);
    }

    public CLevel getReadConsistencyLevel() {
        CLevel lev = CLevel.parse(getConfiguration().getCustomOption(CASSANDRA_READ_CONSISTENCY));
        log.debug("Read consistency level for tx {} is {}", this, lev);
        return lev;
    }

    public CLevel getWriteConsistencyLevel() {
        CLevel lev = CLevel.parse(getConfiguration().getCustomOption(CASSANDRA_WRITE_CONSISTENCY));
        log.debug("Write consistency level for tx {} is {}", this, lev);
        return lev;
    }

    public static CassandraTransaction getTx(StoreTransaction txh) {
        Preconditions.checkArgument(txh != null);
        Preconditions.checkArgument(txh instanceof CassandraTransaction, "Unexpected transaction type %s", txh.getClass().getName());
        return (CassandraTransaction) txh;
    }
}

Add DEBUG logging of Cassandra consistency levels


package nl.esciencecenter.e3dchem.knime.silicosit;

import java.io.File;
import java.io.IOException;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
import org.knime.core.node.CanceledExecutionException;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.workflow.UnsupportedWorkflowVersionException;
import org.knime.core.util.LockFailedException;
import org.knime.testing.core.TestrunConfiguration;

import nl.esciencecenter.e3dchem.knime.testing.TestFlowRunner;

public class PharmacophoreReaderWorkflowTest {
    @Rule
    public ErrorCollector collector = new ErrorCollector();
    private TestFlowRunner runner;

    @Before
    public void setUp() {
        TestrunConfiguration runConfiguration = new TestrunConfiguration();
        runConfiguration.setTestDialogs(true);
        runConfiguration.setReportDeprecatedNodes(true);
        runConfiguration.setCheckMemoryLeaks(true);
        runConfiguration.setLoadSaveLoad(false);
        runner = new TestFlowRunner(collector, runConfiguration);
    }

    @Test
    public void test_simple() throws IOException, InvalidSettingsException, CanceledExecutionException,
            UnsupportedWorkflowVersionException, LockFailedException, InterruptedException {
        File workflowDir = new File("src/knime/silicos-it-phar-reader-test");
        runner.runTestWorkflow(workflowDir);
    }
}

package nl.esciencecenter.e3dchem.knime.silicosit;

import java.io.File;
import java.io.IOException;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
import org.knime.core.node.CanceledExecutionException;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.workflow.UnsupportedWorkflowVersionException;
import org.knime.core.util.LockFailedException;
import org.knime.testing.core.TestrunConfiguration;

import nl.esciencecenter.e3dchem.knime.testing.TestFlowRunner;

public class PharmacophoreReaderWorkflowTest {
    @Rule
    public ErrorCollector collector = new ErrorCollector();
    private TestFlowRunner runner;

    @Before
    public void setUp() {
        TestrunConfiguration runConfiguration = new TestrunConfiguration();
        runConfiguration.setTestDialogs(true);
        runConfiguration.setReportDeprecatedNodes(true);
        runConfiguration.setCheckMemoryLeaks(false);
        runConfiguration.setLoadSaveLoad(false);
        runner = new TestFlowRunner(collector, runConfiguration);
    }

    @Test
    public void test_simple() throws IOException, InvalidSettingsException, CanceledExecutionException,
            UnsupportedWorkflowVersionException, LockFailedException, InterruptedException {
        File workflowDir = new File("src/knime/silicos-it-phar-reader-test");
        runner.runTestWorkflow(workflowDir);
    }
}

Disable mem leak check, it is to sensitive


package com.codahale.metrics;

import static java.lang.Math.min;

/**
 * A {@link Reservoir} implementation backed by a sliding window that stores the last {@code N}
 * measurements.
 */
public class SlidingWindowReservoir implements Reservoir {
    private final long[] measurements;
    private boolean fullWindow;
    private long count;

    /**
     * Creates a new {@link SlidingWindowReservoir} which stores the last {@code size} measurements.
     *
     * @param size the number of measurements to store
     */
    public SlidingWindowReservoir(int size) {
        this.measurements = new long[size];
        this.count = 0;
    }

    @Override
    public synchronized int size() {
    	if(fullWindow){
    		return measurements.length;
    	}else{
    		return (int) min(count, measurements.length);
    	}
    }

    @Override
    public synchronized void update(long value) {
        measurements[(int) count++] = value;
    	if(count >= measurements.length){
    		count = 0;
    		fullWindow = true;
    	}
    }

    @Override
    public Snapshot getSnapshot() {
        final long[] values = new long[size()];
        for (int i = 0; i < values.length; i++) {
            synchronized (this) {
                values[i] = measurements[i];
            }
        }
        return new Snapshot(values);
    }
}

package com.codahale.metrics;

import static java.lang.Math.min;

/**
 * A {@link Reservoir} implementation backed by a sliding window that stores the last {@code N}
 * measurements.
 */
public class SlidingWindowReservoir implements Reservoir {
    private final long[] measurements;
    private long count;

    /**
     * Creates a new {@link SlidingWindowReservoir} which stores the last {@code size} measurements.
     *
     * @param size the number of measurements to store
     */
    public SlidingWindowReservoir(int size) {
        this.measurements = new long[size];
        this.count = 0;
    }

    @Override
    public synchronized int size() {
        return (int) min(count, measurements.length);
    }

    @Override
    public synchronized void update(long value) {
        measurements[(int) (count++ % measurements.length)] = value;
    }

    @Override
    public Snapshot getSnapshot() {
        final long[] values = new long[size()];
        for (int i = 0; i < values.length; i++) {
            synchronized (this) {
                values[i] = measurements[i];
            }
        }
        return new Snapshot(values);
    }
}

Update fix per ceetav's comments.


/*
 * Created by Michael Carrara <michael.carrara@breadwallet.com> on 5/31/18.
 * Copyright (c) 2018 Breadwinner AG.  All right reserved.
 *
 * See the LICENSE file at the project root for license information.
 * See the CONTRIBUTORS file at the project root for a list of contributors.
 */
package com.breadwallet.crypto.events.walletmanager;

import android.support.annotation.Nullable;

import com.google.common.base.Optional;

import java.util.Date;

public final class WalletManagerSyncProgressEvent implements WalletManagerEvent {

    private final double percentComplete;

    @Nullable
    private final Date timestamp;

    public WalletManagerSyncProgressEvent(double percentComplete, @Nullable Date timestamp) {
        this.percentComplete = percentComplete;
        this.timestamp = timestamp;
    }

    public double getPercentComplete() {
        return percentComplete;
    }

    public Optional<Date> getTimestamp() {
        return Optional.fromNullable(timestamp);
    }

    @Override
    public <T> T accept(WalletManagerEventVisitor<T> visitor) {
        return visitor.visit(this);
    }
}

/*
 * Created by Michael Carrara <michael.carrara@breadwallet.com> on 5/31/18.
 * Copyright (c) 2018 Breadwinner AG.  All right reserved.
 *
 * See the LICENSE file at the project root for license information.
 * See the CONTRIBUTORS file at the project root for a list of contributors.
 */
package com.breadwallet.crypto.events.walletmanager;

import android.support.annotation.Nullable;

import com.google.common.base.Optional;

import java.util.Date;

public final class WalletManagerSyncProgressEvent implements WalletManagerEvent {

    private final float percentComplete;

    @Nullable
    private final Date timestamp;

    public WalletManagerSyncProgressEvent(float percentComplete, @Nullable Date timestamp) {
        this.percentComplete = percentComplete;
        this.timestamp = timestamp;
    }

    public float getPercentComplete() {
        return percentComplete;
    }

    public Optional<Date> getTimestamp() {
        return Optional.fromNullable(timestamp);
    }

    @Override
    public <T> T accept(WalletManagerEventVisitor<T> visitor) {
        return visitor.visit(this);
    }
}

Update Java progress events to use floats


package com.vaenow.appupdate.android;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

/**
 * Created by LuoWen on 2015/10/27.
 */
public class CheckAppUpdate extends CordovaPlugin {
    public static final String TAG = "CheckAppUpdate";

    private UpdateManager updateManager = null;

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
            throws JSONException {

        if (action.equals("checkAppUpdate")) {
            getUpdateManager(args, callbackContext).checkUpdate();
            return true;
        }
        callbackContext.error(Utils.makeJSON(Constants.NO_SUCH_METHOD, "no such method: " + action));
        return false;
    }

    public UpdateManager getUpdateManager(JSONArray args, CallbackContext callbackContext)
            throws JSONException {

        if (this.updateManager == null) {
            this.updateManager = new UpdateManager(this.cordova.getActivity(), this.cordova);
        }

        return this.updateManager.options(args, callbackContext);
    }
}

package com.vaenow.appupdate.android;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.Manifest;
import android.support.v4.app.ActivityCompat;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

/**
 * Created by LuoWen on 2015/10/27.
 */
public class CheckAppUpdate extends CordovaPlugin {
    public static final String TAG = "CheckAppUpdate";

    private UpdateManager updateManager = null;

    // Storage Permissions
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE };

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
            throws JSONException {

        if (action.equals("checkAppUpdate")) {
            verifyStoragePermissions(this.cordova.getActivity());
            getUpdateManager(args, callbackContext).checkUpdate();
            return true;
        }
        callbackContext.error(Utils.makeJSON(Constants.NO_SUCH_METHOD, "no such method: " + action));
        return false;
    }

    public UpdateManager getUpdateManager(JSONArray args, CallbackContext callbackContext)
            throws JSONException {

        if (this.updateManager == null) {
            this.updateManager = new UpdateManager(this.cordova.getActivity(), this.cordova);
        }

        return this.updateManager.options(args, callbackContext);
    }

    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
        Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
            REQUEST_EXTERNAL_STORAGE);
        }
    }
}

Handle android EXTERNAL_STORAGE permissions in M


package ca.corefacility.bioinformatics.irida.web.controller.thymeleaf;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * The Thymeleaf portion of the web project is powered by an AngularJS single-page application. This controller is
 * responsible for only responding with a Thymeleaf index page, then the AngularJS application takes over and queries
 * the server for resources using the REST api.
 */
@Controller
@RequestMapping("/**")
public class RootController {
    @RequestMapping
    public String getRoot() {
        return "index";
    }
}

package ca.corefacility.bioinformatics.irida.web.controller.thymeleaf;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * The Thymeleaf portion of the web project is powered by an AngularJS single-page application. This controller is
 * responsible for only responding with a Thymeleaf index page, then the AngularJS application takes over and queries
 * the server for resources using the REST api.
 */
@Controller
public class RootController {
    private static final Logger logger = LoggerFactory.getLogger(RootController.class);

    /**
     * Get the index for any request that does not contain the string "css", "js",
     * or "font" for thymeleaf to render.
     * @return the name of the index page
     */
    @RequestMapping(value = {"{path:(?!css|js|font).*$}", "{path:(?!css|js|font).*$}/**", "/"})
    public String getRoot() {
        logger.debug("Loading index.");
        return "index";
    }
}

Load the index page for *all* requests (except those that should be handled as resources by spring).


package myproject1;

public class HelloWorld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.print("Hello World!");
	}

}

package myproject1;

public class HelloWorld {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.print("Hello World! 日本語追加");
	}

}

Change print text with Japanese.


package io.quarkus.dynamodb.runtime;

import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;

@ConfigRoot(phase = ConfigPhase.RUN_TIME)
public class DynamodbConfig {

    /**
     * Enable DynamoDB service endpoint discovery.
     */
    @ConfigItem
    public boolean enableEndpointDiscovery;

    /**
     * AWS service configurations
     */
    @ConfigItem
    public AwsConfig aws;

    /**
     * SDK client configurations
     */
    @ConfigItem(name = ConfigItem.PARENT)
    public SdkConfig sdk;

    /**
     * Apache HTTP client transport configuration
     */
    @ConfigItem
    public ApacheHttpClientConfig syncClient;

    /**
     * Netty HTTP client transport configuration
     */
    @ConfigItem
    public NettyHttpClientConfig asyncClient;
}

package io.quarkus.dynamodb.runtime;

import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;

@ConfigRoot(phase = ConfigPhase.RUN_TIME)
public class DynamodbConfig {

    /**
     * Enable DynamoDB service endpoint discovery.
     */
    @ConfigItem
    public boolean enableEndpointDiscovery;

    /**
     * SDK client configurations
     */
    @ConfigItem(name = ConfigItem.PARENT)
    public SdkConfig sdk;

    /**
     * AWS service configurations
     */
    @ConfigItem
    public AwsConfig aws;

    /**
     * Apache HTTP client transport configuration
     */
    @ConfigItem
    public ApacheHttpClientConfig syncClient;

    /**
     * Netty HTTP client transport configuration
     */
    @ConfigItem
    public NettyHttpClientConfig asyncClient;
}

Reorder config groups for better documentation


/*
 * Copyright 2016 higherfrequencytrading.com
 *
 * 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 net.openhft.chronicle.bytes.util;

import net.openhft.chronicle.bytes.Bytes;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/*
 * Created by Peter Lawrey on 17/09/15.
 */
public class StringInternerBytesTest {

    @Test
    public void testIntern() {
        @NotNull StringInternerBytes si = new StringInternerBytes(128);
        for (int i = 0; i < 100; i++) {
            Bytes b = Bytes.from("key" + i);
            si.intern(b, (int) b.readRemaining());
        }
        assertEquals(82, si.valueCount());
    }
}

/*
 * Copyright 2016 higherfrequencytrading.com
 *
 * 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 net.openhft.chronicle.bytes.util;

import net.openhft.chronicle.bytes.Bytes;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/*
 * Created by Peter Lawrey on 17/09/15.
 */
public class StringInternerBytesTest {

    @Test
    public void testIntern() {
        @NotNull StringInternerBytes si = new StringInternerBytes(128);
        for (int i = 0; i < 100; i++) {
            Bytes b = Bytes.from("key" + i);
            si.intern(b, (int) b.readRemaining());
        }
        assertEquals(86, si.valueCount());
    }
}

Improve test coverage and deprecate some methods.


package com.skogsrud.halvard.springmvc.spike.controller;

import com.skogsrud.halvard.springmvc.spike.tomcat.Server;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.net.ServerSocket;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

public class HelloWorldControllerIT {
    private static Server server;
    private static int port;
    private static OkHttpClient client;

    @BeforeClass
    public static void beforeClass() throws Exception {
        port = findRandomOpenPort();
        server = new Server(port);
        server.start();
        client = new OkHttpClient();
    }

    @AfterClass
    public static void afterClass() throws Exception {
        server.stop();
    }

    @Test
    public void testHelloWorld() throws Exception {
        Request request = new Request.Builder()
                .url("http://localhost:" + port + "/app/hello")
                .build();
        Response response = client.newCall(request).execute();
        assertThat(response.body().string(), equalTo("Hello world"));
    }

    private static int findRandomOpenPort() throws IOException {
        try (ServerSocket socket = new ServerSocket(0)) {
            return socket.getLocalPort();
        }
    }
}

package com.skogsrud.halvard.springmvc.spike.controller;

import com.skogsrud.halvard.springmvc.spike.tomcat.Server;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.net.ServerSocket;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

public class HelloWorldControllerIT {
    private static Server server;
    private static int port;
    private static OkHttpClient client;

    @BeforeClass
    public static void beforeClass() throws Exception {
        port = findRandomOpenPort();
        server = new Server(port);
        server.start();
        client = new OkHttpClient();
    }

    @AfterClass
    public static void afterClass() throws Exception {
        server.stop();
    }

    @Test
    public void testHelloWorld() throws Exception {
        Request request = new Request.Builder()
                .url("http://localhost:" + port + "/app/hello")
                .build();
        Response response = client.newCall(request).execute();
        assertThat(response.code(), equalTo(200));
        assertThat(response.body().string(), equalTo("Hello world"));
    }

    private static int findRandomOpenPort() throws IOException {
        try (ServerSocket socket = new ServerSocket(0)) {
            return socket.getLocalPort();
        }
    }
}

Add assert for response status code


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

import java.io.IOException;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

public class ExceptionTest {

    @ExtendWith(IgnoreIOExceptionExtension.class)
    @Test
    public void firstTest() throws IOException {
        throw new IOException("IO Exception");
    }

    @Disabled
    @Test
    public void secondTest() throws IOException {
        throw new IOException("My IO Exception");
    }

}

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

import java.io.IOException;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

public class ExceptionTest {

    @RegisterExtension
    static IgnoreIOExceptionExtension ignoreIOExceptionExtension = new IgnoreIOExceptionExtension();

    @Test
    public void firstTest() throws IOException {
        throw new IOException("IO Exception");
    }

    @Test
    public void secondTest() throws IOException {
        throw new IOException("My IO Exception");
    }

}

Use @RegisterExtension in junit5-extension-model 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 io.trino.testing;

import com.google.common.collect.ImmutableMap;

import java.util.Map;

public final class FaultTolerantExecutionConnectorTestHelper
{
    private FaultTolerantExecutionConnectorTestHelper() {}

    public static Map<String, String> getExtraProperties()
    {
        return ImmutableMap.<String, String>builder()
                .put("retry-policy", "TASK")
                .put("fault-tolerant-execution-partition-count", "5")
                .put("fault-tolerant-execution-target-task-input-size", "10MB")
                .put("fault-tolerant-execution-target-task-split-count", "4")
                // to trigger spilling
                .put("exchange.deduplication-buffer-size", "1kB")
                .put("fault-tolerant-execution-task-memory", "1GB")
                .buildOrThrow();
    }
}

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

import com.google.common.collect.ImmutableMap;

import java.util.Map;

public final class FaultTolerantExecutionConnectorTestHelper
{
    private FaultTolerantExecutionConnectorTestHelper() {}

    public static Map<String, String> getExtraProperties()
    {
        return ImmutableMap.<String, String>builder()
                .put("retry-policy", "TASK")
                .put("retry-initial-delay", "50ms")
                .put("retry-max-delay", "100ms")
                .put("fault-tolerant-execution-partition-count", "5")
                .put("fault-tolerant-execution-target-task-input-size", "10MB")
                .put("fault-tolerant-execution-target-task-split-count", "4")
                // to trigger spilling
                .put("exchange.deduplication-buffer-size", "1kB")
                .put("fault-tolerant-execution-task-memory", "1GB")
                .buildOrThrow();
    }
}

Decrease retry delay in fault tolerant execution tests


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

import ai.vespa.metricsproxy.core.VespaMetrics;
import com.google.common.collect.ImmutableList;

import static com.yahoo.vespa.model.admin.monitoring.NetworkMetrics.networkMetricSet;
import static com.yahoo.vespa.model.admin.monitoring.SystemMetrics.systemMetricSet;
import static com.yahoo.vespa.model.admin.monitoring.VespaMetricSet.vespaMetricSet;
import static java.util.Collections.emptyList;

/**
 * This class sets up the 'Vespa' metrics consumer.
 *
 * @author trygve
 * @author gjoranv
 */
public class VespaMetricsConsumer {

    public static final String VESPA_CONSUMER_ID = VespaMetrics.VESPA_CONSUMER_ID.id;

    private static final MetricSet defaultConsumerMetrics = new MetricSet("vespa-consumer-metrics",
                                                                          emptyList(),
                                                                          ImmutableList.of(vespaMetricSet,
                                                                                systemMetricSet,
                                                                                networkMetricSet));

    public static MetricsConsumer getVespaMetricsConsumer() {
        return new MetricsConsumer(VESPA_CONSUMER_ID, defaultConsumerMetrics);
    }

}

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

import ai.vespa.metricsproxy.core.VespaMetrics;
import com.google.common.collect.ImmutableList;

import static com.yahoo.vespa.model.admin.monitoring.NetworkMetrics.networkMetricSet;
import static com.yahoo.vespa.model.admin.monitoring.SystemMetrics.systemMetricSet;
import static com.yahoo.vespa.model.admin.monitoring.VespaMetricSet.vespaMetricSet;
import static java.util.Collections.emptyList;

/**
 * This class sets up the 'Vespa' metrics consumer, which is mainly used for Yamas in hosted Vespa.
 *
 * @author trygve
 * @author gjoranv
 */
public class VespaMetricsConsumer {

    public static final String VESPA_CONSUMER_ID = VespaMetrics.VESPA_CONSUMER_ID.id;

    private static final MetricSet vespaConsumerMetrics = new MetricSet("vespa-consumer-metrics",
                                                                        emptyList(),
                                                                        ImmutableList.of(vespaMetricSet,
                                                                                systemMetricSet,
                                                                                networkMetricSet));

    public static MetricsConsumer getVespaMetricsConsumer() {
        return new MetricsConsumer(VESPA_CONSUMER_ID, vespaConsumerMetrics);
    }

}

Rename default -> vespa and add clarifying comment.


/*
 * Copyright (C) 2011-2012 The University of Manchester
 *
 * See the file "LICENSE" for license terms.
 */
package org.taverna.server.port_description;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

import org.taverna.server.port_description.utils.IntAdapter;

@XmlType(name = "Port")
public class AbstractPort {
	@XmlAttribute(required = true)
	public String name;

	@XmlAttribute
	@XmlSchemaType(name = "int")
	@XmlJavaTypeAdapter(IntAdapter.class)
	public Integer depth;
}

/*
 * Copyright (C) 2011-2012 The University of Manchester
 *
 * See the file "LICENSE" for license terms.
 */
package org.taverna.server.port_description;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

import org.taverna.server.port_description.utils.IntAdapter;

@XmlType(name = "Port")
public class AbstractPort {
	@XmlID
	@XmlAttribute(required = true)
	public String name;

	@XmlAttribute
	@XmlSchemaType(name = "int")
	@XmlJavaTypeAdapter(IntAdapter.class)
	public Integer depth;
}

Make ports in descriptors be XML IDs


/*
 * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
 *
 * 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.orientechnologies.orient.core.serialization.serializer.stream;

import java.io.IOException;

import com.orientechnologies.orient.core.serialization.OBinaryProtocol;

public class OStreamSerializerLong implements OStreamSerializer {
	public static final String								NAME			= "l";

	public static final OStreamSerializerLong	INSTANCE	= new OStreamSerializerLong();

	public String getName() {
		return NAME;
	}

	public Object fromStream(final byte[] iStream) throws IOException {
		return OBinaryProtocol.bytes2long(iStream);
	}

	public byte[] toStream(final Object iObject) throws IOException {
		return OBinaryProtocol.long2bytes((Long) iObject);
	}
}

/*
 * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
 *
 * 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.orientechnologies.orient.core.serialization.serializer.stream;

import java.io.IOException;

import com.orientechnologies.orient.core.serialization.OBinaryProtocol;

public class OStreamSerializerLong implements OStreamSerializer {
	public static final String								NAME			= "lo";

	public static final OStreamSerializerLong	INSTANCE	= new OStreamSerializerLong();

	public String getName() {
		return NAME;
	}

	public Object fromStream(final byte[] iStream) throws IOException {
		return OBinaryProtocol.bytes2long(iStream);
	}

	public byte[] toStream(final Object iObject) throws IOException {
		return OBinaryProtocol.long2bytes((Long) iObject);
	}
}

Fix by Sylvain on duplicated name for serializers Record and Long


package at.ac.tuwien.inso.controller.lecturer.forms;

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

import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.entity.Tag;

public class AddCourseForm {

    private Course course;

    private List<AddCourseTag> activeAndInactiveTags = new ArrayList<>();

    protected AddCourseForm() {
    }

    public AddCourseForm(Course course) {
        this.course = course;

    }

    public AddCourseForm setInitialTags(List<Tag> tags) {
        tags.forEach(tag -> activeAndInactiveTags.add(new AddCourseTag(tag, false)));
        return this;
    }

    public Course getCourse() {
        return course;
    }

    public void setCourse(Course course) {
        this.course = course;
    }

    public List<AddCourseTag> getActiveAndInactiveTags() {
        return activeAndInactiveTags;
    }

    public void setActiveAndInactiveTags(List<AddCourseTag> activeAndInactiveTags) {
        this.activeAndInactiveTags = activeAndInactiveTags;
    }
}

package at.ac.tuwien.inso.controller.lecturer.forms;

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

import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.entity.Tag;

public class AddCourseForm {

    private Course course;

    private List<AddCourseTag> activeAndInactiveTags = new ArrayList<>();

    protected AddCourseForm() {
    }

    public AddCourseForm(Course course) {
        this.course = course;

    }

    public AddCourseForm setInitialTags(List<Tag> tags) {
        tags.forEach(tag -> activeAndInactiveTags.add(new AddCourseTag(tag, false)));
        return this;
    }

    public Course getCourse() {
        return course;
    }

    public void setCourse(Course course) {
        this.course = course;
    }

    public List<AddCourseTag> getActiveAndInactiveTags() {
        return activeAndInactiveTags;
    }

    public void setActiveAndInactiveTags(List<AddCourseTag> activeAndInactiveTags) {
        this.activeAndInactiveTags = activeAndInactiveTags;
    }

    public void setInitialActiveTags(List<Tag> initialActiveTags) {
        activeAndInactiveTags.stream()
                .filter(tag -> initialActiveTags.contains(tag.getTag()))
                .forEach(tag -> tag.setActive(true));
    }
}

Add method to extract active tags from courses when editing


// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.metricsproxy.metric.model;

import java.util.Objects;

/**
 * @author gjoranv
 */
public class MetricId {

    public static final MetricId empty = toMetricId("");
    public final String id;
    private MetricId(String id) { this.id = id; }

    public static MetricId toMetricId(String id) { return new MetricId(id); }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MetricId metricId = (MetricId) o;
        return Objects.equals(id, metricId.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

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

}

// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.metricsproxy.metric.model;

import com.yahoo.yolean.concurrent.CopyOnWriteHashMap;

import java.util.Map;
import java.util.Objects;

/**
 * @author gjoranv
 */
public class MetricId {

    private static final Map<String, MetricId> dictionary = new CopyOnWriteHashMap<>();
    public static final MetricId empty = toMetricId("");
    public final String id;
    private MetricId(String id) { this.id = id; }

    public static MetricId toMetricId(String id) {
        return dictionary.computeIfAbsent(id, key -> new MetricId(key));
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MetricId metricId = (MetricId) o;
        return Objects.equals(id, metricId.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

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

}

Use a dictionary for metrid ids. There are few unique ones (less than 1k), but many instances.