package pro.beam.api.resource.chat.events.data;

import java.util.List;

import pro.beam.api.resource.BeamUser;
import pro.beam.api.resource.chat.AbstractChatEvent;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterators;
import com.google.gson.annotations.SerializedName;

public class IncomingMessageData extends AbstractChatEvent.EventData {
    public int channel;
    public String id;
    public String user_name;
    public String user_id;
    public List<BeamUser.Role> user_roles;
    public List<MessagePart> message;

    public String getMessage() {
        return Joiner.on(' ').join(Iterators.transform(this.message.iterator(), new Function<MessagePart, String>() {
            @Override public String apply(MessagePart part) {
                switch(part.type) {
                    case ME:
                        return part.text;
                    case EMOTICON:
                        return part.path;
                    case LINK:
                        return part.url;
                    case TEXT:
                    default:
                        return part.data;
                }
            }
        }));
    }

    public static class MessagePart {
        public Type type;
        public String url;
        public String data;
        public String path;
        public String text;

        public static enum Type {
            @SerializedName("me") ME,
            @SerializedName("text") TEXT,
            @SerializedName("emoticon") EMOTICON,
            @SerializedName("link") LINK,
        }
    }
}

package pro.beam.api.resource.chat.events.data;

import java.util.List;

import pro.beam.api.resource.BeamUser;
import pro.beam.api.resource.chat.AbstractChatEvent;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterators;
import com.google.gson.annotations.SerializedName;

public class IncomingMessageData extends AbstractChatEvent.EventData {
    public int channel;
    public String id;
    public String user_name;
    public String user_id;
    public List<BeamUser.Role> user_roles;
    public List<MessagePart> message;

    public String getMessage() {
        return Joiner.on(' ').join(Iterators.transform(this.message.iterator(), new Function<MessagePart, String>() {
            @Override public String apply(MessagePart part) {
                switch(part.type) {
                    case ME:
                    case EMOTICON:
                        return part.text;
                    case LINK:
                        return part.url;
                    case TEXT:
                    default:
                        return part.data;
                }
            }
        }));
    }

    public static class MessagePart {
        public Type type;
        public String url;
        public String data;
        public String path;
        public String text;

        // Emoticon-related
        public String source;
        public String pack;
        public Coords coords;

        public static class Coords {
            public int x;
            public int y;
        }

        public static enum Type {
            @SerializedName("me") ME,
            @SerializedName("text") TEXT,
            @SerializedName("emoticon") EMOTICON,
            @SerializedName("link") LINK,
        }
    }
}

Fix emoticon-related parsing issues for chat messages


package com.ggj.game;

import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.utils.Array;
import com.ggj.model.Player;
import com.ggj.model.Rock;

public class ObjectController {
  public static synchronized int register(Actor actor) {
    objects.add(actor);

    return ++objectId;
  }

  public static <T> T getObject(Class<T> callee)
  {
    for(Actor actor : objects)
    {
      if(callee.equals(actor.getClass()))
      {
        return (T)actor;
      }
    }

    return null;
  }

  private static int objectId = 0;
  private static Array<Actor> objects = new Array<Actor>();
}

package com.ggj.game;

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

import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.utils.Array;
import com.ggj.model.Player;
import com.ggj.model.Rock;

public class ObjectController {
  public static synchronized int register(Actor actor) {
    objects.add(actor);

    return ++objectId;
  }

  public static <T> T getObject(Class<T> callee)
  {
    for(Actor actor : objects)
    {
      if(callee.equals(actor.getClass()))
      {
        return (T)actor;
      }
    }

    return null;
  }

  public static <T> List<T> getList(Class<T> callee)
  {
    List<T> result = new ArrayList<T>();
    for(Actor actor : objects)
    {
      if(callee.equals(actor.getClass()))
      {
        result.add((T)actor);
      }
    }

    return result;
  }

  private static int objectId = 0;
  private static Array<Actor> objects = new Array<Actor>();
}

Add generic way to get a list of objects by class


package uk.ac.ebi.biosamples.utils;

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

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;

public class MailSender {
    private static final String BODY_PART_FAIL = " failed execution on ";
    private static final String MAILX = "mailx";
    private static final String SUBJECT = "-s Email from pipeline ";
    private static final String RECIPIENT = "biosamples-tech@ebi.ac.uk";
    private static final String BODY_PART_SUCCESS = " pipeline execution successful for ";
    public static final String FAILED_FILES_ARE = " Failed files are: ";
    private static Logger log = LoggerFactory.getLogger("MailSender");

    public static void sendEmail(final String pipelineName, final String failures, final boolean isPassed) {
        try {
            final String[] cmd = {MAILX, SUBJECT + pipelineName, RECIPIENT};
            final Process p = Runtime.getRuntime().exec(cmd);
            final OutputStreamWriter osw = new OutputStreamWriter(p.getOutputStream());

            if (isPassed) {
                if (failures != null && !failures.isEmpty())
                    osw.write(pipelineName + BODY_PART_SUCCESS + new Date() + FAILED_FILES_ARE + failures);
                else
                    osw.write(pipelineName + BODY_PART_SUCCESS + new Date());
            } else osw.write(pipelineName + BODY_PART_FAIL + new Date());

            osw.close();
        } catch (final IOException ioe) {
            log.error("Email send failed");
        }
    }
}

package uk.ac.ebi.biosamples.utils;

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

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;

public class MailSender {
    private static final String BODY_PART_FAIL = " failed execution on ";
    private static final String MAILX = "mailx";
    private static final String SUBJECT = "-s Email from pipeline ";
    private static final String RECIPIENT = "biosamples-dev@ebi.ac.uk";
    private static final String BODY_PART_SUCCESS = " pipeline execution successful for ";
    public static final String FAILED_FILES_ARE = " Failed files are: ";
    private static Logger log = LoggerFactory.getLogger("MailSender");

    public static void sendEmail(final String pipelineName, final String failures, final boolean isPassed) {
        try {
            final String[] cmd = {MAILX, SUBJECT + pipelineName, RECIPIENT};
            final Process p = Runtime.getRuntime().exec(cmd);
            final OutputStreamWriter osw = new OutputStreamWriter(p.getOutputStream());

            if (isPassed) {
                if (failures != null && !failures.isEmpty())
                    osw.write(pipelineName + BODY_PART_SUCCESS + new Date() + FAILED_FILES_ARE + failures);
                else
                    osw.write(pipelineName + BODY_PART_SUCCESS + new Date());
            } else osw.write(pipelineName + BODY_PART_FAIL + new Date());

            osw.close();
        } catch (final IOException ioe) {
            log.error("Email send failed");
        }
    }
}

Send emails to biosamples-dev@ebi.ac.uk until we find what is wrong in sending to tech


package pl.brightinventions.slf4android;

import java.text.SimpleDateFormat;

class DateValueSupplier implements LoggerPatternValueSupplier {
    private static ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy.MM.dd HH:mm:ss.SSS");
        }
    };

    @Override
    public void append(LogRecord record, StringBuilder builder) {
        String formatted = dateFormat.get().format(record.getDate());
        builder.append(formatted);
    }
}

package pl.brightinventions.slf4android;

import java.text.SimpleDateFormat;
import java.util.Locale;

class DateValueSupplier implements LoggerPatternValueSupplier {
    private static ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy.MM.dd HH:mm:ss.SSS", Locale.US);
        }
    };

    @Override
    public void append(LogRecord record, StringBuilder builder) {
        String formatted = dateFormat.get().format(record.getDate());
        builder.append(formatted);
    }
}

Fix lint warning about locale


/**
 * Project RSA Algorithm.
 * Copyright Michał Szczygieł.
 * Created at Mar 14, 2014.
 */

package com.m4gik;

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

import org.junit.Test;

/**
 * This class contains JUnit tests for class {@link SHA1}.
 *
 * @author Michał Szczygieł <michal.szczygiel@wp.pl>
 *
 */
public class SHA1Test {

    private static final String EXAMPLE_TEXT = "The quick brown fox jumps over the lazy dog";
    private static final String HASHED_EXAMPLE_TEXT = "2fd4e1c6 7a2d28fc ed849ee1 bb76e739 1b93eb12";

    /**
     * This test method checks SHA1 algorithm for given string, which should be
     * correct with another algorithm based on SHA1.
     *
     * @throws Exception
     */
    @Test
    public void checkCorrectnessOfSHA1() throws Exception {
        // given
        SHA1 sha1 = new SHA1();
        // when
        String result = sha1.hash(EXAMPLE_TEXT);
        // then
        assertThat(result, is(equalTo(HASHED_EXAMPLE_TEXT)));
    }
}

/**
 * Project RSA Algorithm.
 * Copyright Michał Szczygieł.
 * Created at Mar 14, 2014.
 */

package com.m4gik;

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

import java.security.spec.InvalidParameterSpecException;

import org.junit.Test;

/**
 * This class contains JUnit tests for class {@link SHA1}.
 *
 * @author Michał Szczygieł <michal.szczygiel@wp.pl>
 *
 */
public class SHA1Test {

    private static final String EXAMPLE_TEXT = "The quick brown fox jumps over the lazy dog";
    private static final String HASHED_EXAMPLE_TEXT = "2fd4e1c6 7a2d28fc ed849ee1 bb76e739 1b93eb12";

    /**
     * This test method checks SHA1 algorithm for given string, which should be
     * correct with another algorithm based on SHA1.
     *
     * @throws Exception
     */
    @Test
    public void checkCorrectnessOfSHA1() throws Exception {
        // when
        String result = SHA1.hash(EXAMPLE_TEXT);
        // then
        assertThat(result, is(equalTo(HASHED_EXAMPLE_TEXT)));
    }

    /**
     * This test method checks SHA1 algorithm for given string, and this method
     * shouldn't return exeption
     *
     * @throws Exception
     */
    @Test(
            expected = InvalidParameterSpecException.class)
    public void dataShouldBeMultipleOf64() throws Exception {
        // when
        SHA1.checkData(EXAMPLE_TEXT.getBytes());
        // then ... throw new Exception
    }
}

Add test for checkData() method


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

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.rest.RestStatus;

import java.io.IOException;

/**
 * Generic ResourceNotFoundException corresponding to the {@link RestStatus#NOT_FOUND} status code
 */
public class ResourceNotFoundException extends ElasticsearchException {

    public ResourceNotFoundException(String msg, Object... args) {
        super(msg, args);
    }

    protected ResourceNotFoundException(String msg, Throwable cause, Object... args) {
        super(msg, cause, args);
    }

    public ResourceNotFoundException(StreamInput in) throws IOException {
        super(in);
    }

    @Override
    public final RestStatus status() {
        return RestStatus.NOT_FOUND;
    }
}

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

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.rest.RestStatus;

import java.io.IOException;

/**
 * Generic ResourceNotFoundException corresponding to the {@link RestStatus#NOT_FOUND} status code
 */
public class ResourceNotFoundException extends ElasticsearchException {

    public ResourceNotFoundException(String msg, Object... args) {
        super(msg, args);
    }

    public ResourceNotFoundException(String msg, Throwable cause, Object... args) {
        super(msg, cause, args);
    }

    public ResourceNotFoundException(StreamInput in) throws IOException {
        super(in);
    }

    @Override
    public final RestStatus status() {
        return RestStatus.NOT_FOUND;
    }
}

Fix exception on task not found


package stroom.data.store.impl.fs;

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

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

class StreamTypeExtensions {
    private static final Logger LOGGER = LoggerFactory.getLogger(StreamTypeExtensions.class);
    private static final Map<String, String> EXTENSION_MAP = new HashMap<>();

    static {
        EXTENSION_MAP.put("Manifest", "mf");
        EXTENSION_MAP.put("Raw Events", "revt");
        EXTENSION_MAP.put("Raw Reference", "rref");
        EXTENSION_MAP.put("Events", "evt");
        EXTENSION_MAP.put("Reference", "ref");
        EXTENSION_MAP.put("Test Events", "tevt");
        EXTENSION_MAP.put("Test Reference", "tref");
        EXTENSION_MAP.put("Segment Index", "seg");
        EXTENSION_MAP.put("Boundary Index", "bdy");
        EXTENSION_MAP.put("Meta Data", "meta");
        EXTENSION_MAP.put("Error", "err");
        EXTENSION_MAP.put("Context", "ctx");
    }

    static String getExtension(final String streamType) {
        String extension = EXTENSION_MAP.get(streamType);
        if (extension == null) {
            LOGGER.warn("Unknown stream type '" + streamType + "' using extension 'dat'");
            extension = "dat";
        }
        return extension;
    }
}

package stroom.data.store.impl.fs;

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

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

class StreamTypeExtensions {
    private static final Logger LOGGER = LoggerFactory.getLogger(StreamTypeExtensions.class);
    private static final Map<String, String> EXTENSION_MAP = new HashMap<>();

    static {
        EXTENSION_MAP.put("Manifest", "mf");
        EXTENSION_MAP.put("Raw Events", "revt");
        EXTENSION_MAP.put("Raw Reference", "rref");
        EXTENSION_MAP.put("Events", "evt");
        EXTENSION_MAP.put("Reference", "ref");
        EXTENSION_MAP.put("Test Events", "tevt");
        EXTENSION_MAP.put("Test Reference", "tref");
        EXTENSION_MAP.put("Segment Index", "seg");
        EXTENSION_MAP.put("Boundary Index", "bdy");
        EXTENSION_MAP.put("Meta Data", "meta");
        EXTENSION_MAP.put("Error", "err");
        EXTENSION_MAP.put("Context", "ctx");
        EXTENSION_MAP.put("Detections", "dtxn");
    }

    static String getExtension(final String streamType) {
        String extension = EXTENSION_MAP.get(streamType);
        if (extension == null) {
            LOGGER.warn("Unknown stream type '" + streamType + "' using extension 'dat'");
            extension = "dat";
        }
        return extension;
    }
}

Introduce new Detections stream type


package org.springframework.cloud.cloudfoundry;

import java.util.Map;

import org.springframework.cloud.service.common.MongoServiceInfo;

/**
 *
 * @author Ramnivas Laddad
 *
 */
public class MongoServiceInfoCreator extends CloudFoundryServiceInfoCreator<MongoServiceInfo> {

	public MongoServiceInfoCreator() {
		super("mongodb");

	}

	public MongoServiceInfo createServiceInfo(Map<String,Object> serviceData) {
		@SuppressWarnings("unchecked")
		Map<String,Object> credentials = (Map<String, Object>) serviceData.get("credentials");

		String id = (String) serviceData.get("name");

		String uri = (String) credentials.get("uri");

		return new MongoServiceInfo(id, uri);
	}

}

package org.springframework.cloud.cloudfoundry;

import java.util.Map;

import org.springframework.cloud.service.common.MongoServiceInfo;

/**
 *
 * @author Ramnivas Laddad
 *
 */
public class MongoServiceInfoCreator extends CloudFoundryServiceInfoCreator<MongoServiceInfo> {

	public MongoServiceInfoCreator() {
		super("mongodb");

	}

	public MongoServiceInfo createServiceInfo(Map<String,Object> serviceData) {
		@SuppressWarnings("unchecked")
		Map<String,Object> credentials = (Map<String, Object>) serviceData.get("credentials");

		String id = (String) serviceData.get("name");

		String uri = (String) ((credentials.get("uri") == null) ? credentials.get("url") : credentials.get("uri"));

		return new MongoServiceInfo(id, uri);
	}

}

Add fix for MongoDb if url is used instead of uri


package com.vladmihalcea.book.hpjp.hibernate.transaction.spring.routing;

import com.vladmihalcea.book.hpjp.hibernate.transaction.forum.Post;
import com.vladmihalcea.book.hpjp.hibernate.transaction.forum.Tag;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Arrays;
import java.util.List;

/**
 * @author Vlad Mihalcea
 */
@Service
public class ForumServiceImpl implements ForumService {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional
    public Post newPost(String title, String... tags) {
        Post post = new Post();
        post.setTitle(title);

        post.getTags().addAll(
            entityManager.createQuery("""
                select t
                from Tag t
                where t.name in :tags
                """, Tag.class)
            .setParameter("tags", Arrays.asList(tags))
            .getResultList()
        );

        entityManager.persist(post);

        return post;
    }

    @Override
    @Transactional(readOnly = true)
    public List<Post> findAllPostsByTitle(String title) {
        return entityManager.createQuery("""
            select p
            from Post p
            where p.title = :title
            """, Post.class)
        .setParameter("title", title)
        .getResultList();
    }
}

package com.vladmihalcea.book.hpjp.hibernate.transaction.spring.routing;

import com.vladmihalcea.book.hpjp.hibernate.transaction.forum.Post;
import com.vladmihalcea.book.hpjp.hibernate.transaction.forum.Tag;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Arrays;
import java.util.List;

/**
 * @author Vlad Mihalcea
 */
@Service
@Transactional(readOnly = true)
public class ForumServiceImpl implements ForumService {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional
    public Post newPost(String title, String... tags) {
        Post post = new Post();
        post.setTitle(title);

        post.getTags().addAll(
            entityManager.createQuery("""
                select t
                from Tag t
                where t.name in :tags
                """, Tag.class)
            .setParameter("tags", Arrays.asList(tags))
            .getResultList()
        );

        entityManager.persist(post);

        return post;
    }

    @Override
    public List<Post> findAllPostsByTitle(String title) {
        return entityManager.createQuery("""
            select p
            from Post p
            where p.title = :title
            """, Post.class)
        .setParameter("title", title)
        .getResultList();
    }
}

Move the @Transactional(readOnly = true) annotation to class level


package org.cyanogenmod.launcher.home.api.sdkexample.receiver;

import android.util.Log;

import org.cyanogenmod.launcher.home.api.cards.DataCard;
import org.cyanogenmod.launcher.home.api.receiver.CmHomeCardChangeReceiver;

/**
 * An extension of CmHomeCardChangeReceiver, that implements the callback for
 * when a card is deleted.
 */
public class CardDeletedBroadcastReceiver extends CmHomeCardChangeReceiver{
    public static final String TAG = "CardDeletedBroadcastReceiver";

    @Override
    protected void onCardDeleted(DataCard.CardDeletedInfo cardDeletedInfo) {
        Log.i(TAG, "CM Home API card was deleted: id: " + cardDeletedInfo.getId()
                   + ", internalID: " + cardDeletedInfo.getInternalId()
                   + ", authority: " + cardDeletedInfo.getAuthority()
                   + ", globalID: " + cardDeletedInfo.getGlobalId());
    }
}

package org.cyanogenmod.launcher.home.api.sdkexample.receiver;

import android.content.Context;
import android.util.Log;

import org.cyanogenmod.launcher.home.api.cards.DataCard;
import org.cyanogenmod.launcher.home.api.receiver.CmHomeCardChangeReceiver;

/**
 * An extension of CmHomeCardChangeReceiver, that implements the callback for
 * when a card is deleted.
 */
public class CardDeletedBroadcastReceiver extends CmHomeCardChangeReceiver{
    public static final String TAG = "CardDeletedBroadcastReceiver";

    @Override
    protected void onCardDeleted(Context context, DataCard.CardDeletedInfo cardDeletedInfo) {
        Log.i(TAG, "CM Home API card was deleted: id: " + cardDeletedInfo.getId()
                   + ", internalID: " + cardDeletedInfo.getInternalId()
                   + ", authority: " + cardDeletedInfo.getAuthority()
                   + ", globalID: " + cardDeletedInfo.getGlobalId());    }
}

Add Context parameter to onCardDelete to match SDK


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

import org.junit.Test;

public class ShellTest extends AbstractParserTest {

    @Test
    public void test() throws Exception {
        Context context = new Context();
        context.execute("a = \"foo\"");
        assertEquals("foo", context.get("a"));
        context.execute("a = $(echo bar)");
        assertEquals("bar", context.get("a"));
    }

}

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

import java.util.Arrays;

import org.junit.Test;

public class ShellTest extends AbstractParserTest {

    @Test
    public void testAssignmentWithEcho() throws Exception {
        Context context = new Context();
        context.execute("a = \"foo\"");
        assertEquals("foo", context.get("a"));
        context.execute("a = $(echo bar)");
        assertEquals("bar", context.get("a"));
    }

    @Test
    public void testJobIds() throws Exception {
        Context context = new Context();
        // TODO: not than in zsh, the same thing is achieved using
        // TODO:     ${${${(@f)"$(jobs)"}%]*}#*\[}
        Object result = context.execute("sleep 1 & sleep 1 & ${${${(f)$(jobs)}%']*'}#'*\\['}");
        assertEquals(Arrays.asList("1", "2"), result);
    }

}

Add a test for jobids


package entity;

import java.sql.Timestamp;
import java.util.Calendar;
import java.io.Serializable;

/**
 * Created by corentin on 10/03/15.
 */
public abstract class AbstractEntity  implements Serializable {
    /**
     * Unique id of entity
     */
    protected long id;

    /**
     * Type of entity
     */
    protected String type;

    /**
     * Timestamp
     */
    protected Timestamp lastUpdate;

    /**
     * Basic contruct, assign an id
     */
    public AbstractEntity()
    {
        id = -1;
    }

    /**
     * Update the lastUpdate timestamp to current timestamp
     */
    public void updateDate() {
        this.lastUpdate = new Timestamp(Calendar.getInstance().getTime().getTime());
    }

    public long getId() {
        return id;
    }

    public void setId(long id)
    {
        this.id=id;
    }

    public String getType() {
        return type;
    }
}

package entity;

import java.sql.Timestamp;
import java.util.Calendar;
import java.io.Serializable;

/**
 * Created by corentin on 10/03/15.
 */
public abstract class AbstractEntity  implements Serializable {
    /**
     * Unique id of entity
     */
    protected long id;

    /**
     * Type of entity
     */
    protected String type;

    /**
     * Timestamp
     */
    protected Timestamp lastUpdate;

    /**
     * Basic contruct, assign an id
     */
    public AbstractEntity()
    {
        id = -1;
    }

    /**
     * Update the lastUpdate timestamp to current timestamp
     */
    public void updateDate() {
        this.lastUpdate = new Timestamp(Calendar.getInstance().getTime().getTime());
    }

    public long getId() {
        return id;
    }

    public void setId(long id)
    {
        this.id=id;
    }

    public String getType() {
        return type;
    }

    public Timestamp getLastUpdate() {
        return lastUpdate;
    }
}

Modify : ajout de get Timestamp


public class Main {

	public static void main(String[] args) {

		System.out.println("Teste");

	}

}

public class Main {

	public static void main(String[] args) {

		System.out.print("Arquivo de Leitura: ");
		System.out.println(args[0]);
		System.out.print("Palavra de Entrada: ");
		System.out.println(args[1]);
		System.out.print("Arquivo de Sada: ");
		System.out.println(args[2]);

	}

}

Print dos aquivos de entrada, saída e da palavra


package ee.shy.core.merge;

import ee.shy.TemporaryDirectory;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import java.io.IOException;

import static org.junit.Assume.*;

public abstract class MergerTest<T> {
    @Rule
    public TemporaryDirectory temporaryDirectory = new TemporaryDirectory();

    protected T patchable;
    protected T original;
    protected T revised;
    protected T patched;

    protected abstract T getState(String name) throws IOException;

    @Before
    public void setUp() throws Exception {
        patchable = getState("patchable");
        original = getState("original");
        revised = getState("revised");
        patched = getState("patched");
        assumeNotNull(patchable, original, revised, patchable);
    }

    @Test
    public void testForwardMainMerge() throws Exception {
        testMerge(patchable, original, revised, patched);
    }

    @Test
    public void testForwardSideMerge() throws Exception {
        testMerge(revised, original, patchable, patched);
    }

    @Test
    public void testBackwardMainMerge() throws Exception {
        testMerge(patched, revised, original, patchable);
    }

    @Test
    public void testBackwardSideMerge() throws Exception {
        testMerge(original, revised, patched, patchable);
    }

    protected abstract void testMerge(T patchable, T original, T revised, T patched) throws IOException;
}

package ee.shy.core.merge;

import ee.shy.TemporaryDirectory;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import java.io.IOException;

import static org.junit.Assume.*;

public abstract class MergerTest<T> {
    @Rule
    public TemporaryDirectory temporaryDirectory = new TemporaryDirectory();

    protected T patchable;
    protected T original;
    protected T revised;
    protected T patched;

    protected abstract T getState(String name) throws IOException;

    @Before
    public void setUp() throws Exception {
        patchable = getState("patchable");
        original = getState("original");
        revised = getState("revised");
        patched = getState("patched");
        assumeNotNull(patchable, original, revised, patchable);
    }

    @Test
    public void testForwardMainMerge() throws Exception {
        testMerge(patchable, original, revised, patched);
    }

    @Test
    public void testForwardSideMerge() throws Exception {
        testMerge(revised, original, patchable, patched);
    }

    @Test
    public void testBackwardMainMerge() throws Exception {
        testMerge(patchable, patched, revised, original);
    }

    @Test
    public void testBackwardSideMerge() throws Exception {
        testMerge(revised, patched, patchable, original);
    }

    protected abstract void testMerge(T patchable, T original, T revised, T patched) throws IOException;
}

Fix backward merge test object order


package org.torproject.jtor.directory;

import org.torproject.jtor.data.HexDigest;
import org.torproject.jtor.data.Timestamp;
import org.torproject.jtor.data.exitpolicy.ExitPorts;

public interface RouterStatus {
	String getNickname();
	HexDigest getIdentity();
	HexDigest getDescriptorDigest();
	Timestamp getPublicationTime();
	int getRouterPort();
	boolean isDirectory();
	int getDirectoryPort();
	boolean hasFlag(String flag);
	String getVersion();
	int getEstimatedBandwidth();
	int getMeasuredBandwidth();
	ExitPorts getExitPorts();
}

package org.torproject.jtor.directory;

import org.torproject.jtor.data.HexDigest;
import org.torproject.jtor.data.IPv4Address;
import org.torproject.jtor.data.Timestamp;
import org.torproject.jtor.data.exitpolicy.ExitPorts;

public interface RouterStatus {
	String getNickname();
	HexDigest getIdentity();
	HexDigest getDescriptorDigest();
	Timestamp getPublicationTime();
	IPv4Address getAddress();
	int getRouterPort();
	boolean isDirectory();
	int getDirectoryPort();
	boolean hasFlag(String flag);
	String getVersion();
	int getEstimatedBandwidth();
	int getMeasuredBandwidth();
	ExitPorts getExitPorts();
}

Allow access of IPv4Address stored in status


package org.komamitsu.fluency.sender.retry;

public abstract class RetryStrategy<C extends RetryStrategy.Config>
{
    protected final C config;

    public RetryStrategy(C config)
    {
        this.config = config;
    }

    public abstract long getNextIntervalMillis(int retryCount);

    public boolean isRetriedOver(int retryCount)
    {
        return retryCount > config.getMaxRetryCount();
    }

    public static abstract class Config<T extends RetryStrategy, C extends RetryStrategy.Config>
    {
        private int maxRetryCount = 8;

        public int getMaxRetryCount()
        {
            return maxRetryCount;
        }

        public C setMaxRetryCount(int maxRetryCount)
        {
            this.maxRetryCount = maxRetryCount;
            return (C)this;
        }

        public abstract T createInstance();
    }
}

package org.komamitsu.fluency.sender.retry;

public abstract class RetryStrategy<C extends RetryStrategy.Config>
{
    protected final C config;

    public RetryStrategy(C config)
    {
        this.config = config;
    }

    public abstract long getNextIntervalMillis(int retryCount);

    public boolean isRetriedOver(int retryCount)
    {
        return retryCount > config.getMaxRetryCount();
    }

    public static abstract class Config<T extends RetryStrategy, C extends RetryStrategy.Config>
    {
        private int maxRetryCount = 7;

        public int getMaxRetryCount()
        {
            return maxRetryCount;
        }

        public C setMaxRetryCount(int maxRetryCount)
        {
            this.maxRetryCount = maxRetryCount;
            return (C)this;
        }

        public abstract T createInstance();
    }
}

Change default retry to 7 from 8


/*
 * 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.addthis.hydra.job.spawn;

import com.yammer.metrics.core.Gauge;

class DownMinionGauge extends Gauge<Integer> {
    private Spawn spawn;

    public DownMinionGauge(Spawn spawn) {
        this.spawn = spawn;
    }

    @Override public Integer value() {
        int total = 0;
        if (spawn.monitored != null) {
            synchronized (spawn.monitored) {
                total = spawn.monitored.size();
            }
        }
        int up;
        if (spawn.minionMembers == null) {
            up = 0;
        } else {
            up = spawn.minionMembers.getMemberSetSize();
        }
        return total - up;
    }
}

/*
 * 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.addthis.hydra.job.spawn;

import com.addthis.hydra.job.mq.HostState;

import com.yammer.metrics.core.Gauge;

class DownMinionGauge extends Gauge<Integer> {
    private Spawn spawn;

    public DownMinionGauge(Spawn spawn) {
        this.spawn = spawn;
    }

    @Override public Integer value() {
        int down = 0;
        for (HostState host : spawn.listHostStatus(null)) {
            if (host != null && !host.isDead() && !host.isUp()) {
                down++;
            }
        }
        return down;
    }
}

Fix Spawn minionDown metric to correctly ignore failed hosts.


package com.cgi.eoss.ftep.api.controllers;

import com.cgi.eoss.ftep.api.security.FtepSecurityService;
import com.cgi.eoss.ftep.model.JobConfig;
import com.cgi.eoss.ftep.model.QJobConfig;
import com.cgi.eoss.ftep.model.QUser;
import com.cgi.eoss.ftep.persistence.dao.JobConfigDao;
import com.querydsl.core.types.dsl.NumberPath;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Getter
@Component
public class JobConfigsApiImpl extends BaseRepositoryApiImpl<JobConfig> {

    private final FtepSecurityService securityService;
    private final JobConfigDao dao;

    @Override
    NumberPath<Long> getIdPath() {
        return QJobConfig.jobConfig.id;
    }

    @Override
    QUser getOwnerPath() {
        return QJobConfig.jobConfig.owner;
    }

    @Override
    Class<JobConfig> getEntityClass() {
        return JobConfig.class;
    }

}

package com.cgi.eoss.ftep.api.controllers;

import com.cgi.eoss.ftep.api.security.FtepSecurityService;
import com.cgi.eoss.ftep.model.JobConfig;
import com.cgi.eoss.ftep.model.QJobConfig;
import com.cgi.eoss.ftep.model.QUser;
import com.cgi.eoss.ftep.persistence.dao.JobConfigDao;
import com.querydsl.core.types.dsl.NumberPath;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Getter
@Component
public class JobConfigsApiImpl extends BaseRepositoryApiImpl<JobConfig> {

    private final FtepSecurityService securityService;
    private final JobConfigDao dao;

    @Override
    public <S extends JobConfig> S save(S entity) {
        if (entity.getOwner() == null) {
            getSecurityService().updateOwnerWithCurrentUser(entity);
        }

        JobConfig existing = getDao().findOne(QJobConfig.jobConfig.owner.eq(entity.getOwner())
                .and(QJobConfig.jobConfig.service.eq(entity.getService()))
                .and(QJobConfig.jobConfig.inputs.eq(entity.getInputs())));
        if (existing != null) {
            entity.setId(existing.getId());
        }
        return getDao().save(entity);
    }

    @Override
    NumberPath<Long> getIdPath() {
        return QJobConfig.jobConfig.id;
    }

    @Override
    QUser getOwnerPath() {
        return QJobConfig.jobConfig.owner;
    }

    @Override
    Class<JobConfig> getEntityClass() {
        return JobConfig.class;
    }

}

Fix job config uniqueness check in POST API endpoint


package lighthouse.utils;

import org.slf4j.*;

import javax.annotation.*;
import java.util.*;

import static gnu.gettext.GettextResource.*;

public class I18nUtil {
    private static final Logger log = LoggerFactory.getLogger(I18nUtil.class);
    @Nullable public static ResourceBundle locale;

    static {
        try {
            locale = ResourceBundle.getBundle("lighthouse.locale.lighthouse");
            log.info("Using language translations for {}", locale.getLocale());
        } catch (MissingResourceException e) {
            // Ignore.
        }
    }

    public static String tr(String s) {
        if (locale != null)
            return gettext(locale, s);
        else
            return s;
    }
}

package lighthouse.utils;

import org.jetbrains.annotations.*;
import org.slf4j.*;

import javax.annotation.Nullable;
import java.util.*;

import static gnu.gettext.GettextResource.*;

public class I18nUtil {
    private static final Logger log = LoggerFactory.getLogger(I18nUtil.class);
    @Nullable private static ResourceBundle locale;

    public static ResourceBundle translations = new ResourceBundle() {
        @Override
        protected Object handleGetObject(String key) {
            if (locale == null)
                return key;
            else
                try {
                    return locale.getObject(key);
                } catch (MissingResourceException e) {
                    return key;
                }
        }

        @Override
        public boolean containsKey(String key) {
            return true;
        }

        @NotNull
        @Override
        public Enumeration<String> getKeys() {
            if (locale != null)
                return locale.getKeys();
            else
                return Collections.emptyEnumeration();
        }
    };

    static {
        try {
            locale = ResourceBundle.getBundle("lighthouse.locale.lighthouse");
            log.info("Using language translations for {}", locale.getLocale());
        } catch (MissingResourceException e) {
            // Ignore.
        }
    }

    public static String tr(String s) {
        if (locale != null)
            return gettext(locale, s);
        else
            return s;
    }
}

Fix the case where a translation is missing and it's loaded via FXML with a custom ResourceBundle that never throws an error, it always returns the key (English string) if a real translation is missing.


package com.alexstyl.specialdates.events.namedays.calendar.resource;

import com.alexstyl.specialdates.events.namedays.NamedayLocale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

class NamedayJSONResourceProvider {

    private final NamedayJSONResourceLoader loader;

    NamedayJSONResourceProvider(NamedayJSONResourceLoader loader) {
        this.loader = loader;
    }

    NamedayJSON getNamedayJSONFor(NamedayLocale locale) throws JSONException {
        JSONObject json = loader.loadJSON(locale);
        JSONArray data = json.getJSONArray("data");
        JSONArray special = json.getJSONArray("special");
        return new NamedayJSON(data, special);
    }

}

package com.alexstyl.specialdates.events.namedays.calendar.resource;

import com.alexstyl.specialdates.events.namedays.NamedayLocale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

class NamedayJSONResourceProvider {

    private final NamedayJSONResourceLoader loader;
    private final JSONArray jsonArray = new JSONArray();

    NamedayJSONResourceProvider(NamedayJSONResourceLoader loader) {
        this.loader = loader;
    }

    NamedayJSON getNamedayJSONFor(NamedayLocale locale) throws JSONException {
        JSONObject json = loader.loadJSON(locale);
        JSONArray data = json.getJSONArray("data");
        JSONArray special = getSpecialOf(json);
        return new NamedayJSON(data, special);
    }

    private JSONArray getSpecialOf(JSONObject json) throws JSONException {
        if (json.has("special")) {
            return json.getJSONArray("special");
        }
        return jsonArray;
    }

}

Return empty JSONArray if no Special is found


package com.xeiam.xchange.quoine;

import si.mazi.rescu.SynchronizedValueFactory;

import com.xeiam.xchange.BaseExchange;
import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.ExchangeSpecification;
import com.xeiam.xchange.quoine.service.polling.QuoineAccountService;
import com.xeiam.xchange.quoine.service.polling.QuoineMarketDataService;
import com.xeiam.xchange.quoine.service.polling.QuoineTradeService;

public class QuoineExchange extends BaseExchange implements Exchange {

  public static final String KEY_USER_ID = "KEY_USER_ID";
  public static final String KEY_DEVICE_NAME = "KEY_DEVICE_NAME";
  public static final String KEY_USER_TOKEN = "KEY_USER_TOKEN";

  @Override
  public void applySpecification(ExchangeSpecification exchangeSpecification) {

    super.applySpecification(exchangeSpecification);

    this.pollingMarketDataService = new QuoineMarketDataService(this);
    this.pollingAccountService = new QuoineAccountService(this);
    this.pollingTradeService = new QuoineTradeService(this);
  }

  @Override
  public ExchangeSpecification getDefaultExchangeSpecification() {

    ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass().getCanonicalName());
    exchangeSpecification.setSslUri("https://quoine-stag4.herokuapp.com");
    exchangeSpecification.setExchangeName("Quoine");
    return exchangeSpecification;
  }

  @Override
  public SynchronizedValueFactory<Long> getNonceFactory() {

    // not used by this exchange
    return null;
  }
}

package com.xeiam.xchange.quoine;

import si.mazi.rescu.SynchronizedValueFactory;

import com.xeiam.xchange.BaseExchange;
import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.ExchangeSpecification;
import com.xeiam.xchange.quoine.service.polling.QuoineAccountService;
import com.xeiam.xchange.quoine.service.polling.QuoineMarketDataService;
import com.xeiam.xchange.quoine.service.polling.QuoineTradeService;

public class QuoineExchange extends BaseExchange implements Exchange {

  public static final String KEY_USER_ID = "KEY_USER_ID";
  public static final String KEY_DEVICE_NAME = "KEY_DEVICE_NAME";
  public static final String KEY_USER_TOKEN = "KEY_USER_TOKEN";

  @Override
  public void applySpecification(ExchangeSpecification exchangeSpecification) {

    super.applySpecification(exchangeSpecification);

    this.pollingMarketDataService = new QuoineMarketDataService(this);
    this.pollingAccountService = new QuoineAccountService(this);
    this.pollingTradeService = new QuoineTradeService(this);
  }

  @Override
  public ExchangeSpecification getDefaultExchangeSpecification() {

    ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass().getCanonicalName());
    exchangeSpecification.setSslUri("https://api.quoine.com");
    exchangeSpecification.setExchangeName("Quoine");
    return exchangeSpecification;
  }

  @Override
  public SynchronizedValueFactory<Long> getNonceFactory() {

    // not used by this exchange
    return null;
  }
}

Replace obsolete staging endpoint with api.quoine.com


/**
 * Copyright (C) 2015 android10.org. All rights reserved.
 * @author Fernando Cejas (the android10 coder)
 */
package com.fernandocejas.android10.sample.presentation.internal.di.modules;

import android.app.Application;
import android.content.Context;
import android.view.LayoutInflater;
import com.fernandocejas.android10.sample.data.executor.JobExecutor;
import com.fernandocejas.android10.sample.domain.executor.PostExecutionThread;
import com.fernandocejas.android10.sample.domain.executor.ThreadExecutor;
import com.fernandocejas.android10.sample.presentation.UIThread;
import com.fernandocejas.android10.sample.presentation.internal.di.components.ForApplication;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;

/**
 * Dagger module that provides objects which will live during the application lifecycle.
 */
@Module
public final class ApplicationModule {

  private final Application application;

  public ApplicationModule(Application application) {
    this.application = application;
  }

  @Provides @Singleton @ForApplication Context provideApplicationContext() {
    return this.application;
  }

  @Provides @Singleton LayoutInflater provideLayoutInflater() {
    return LayoutInflater.from(this.application);
  }

  @Provides @Singleton ThreadExecutor provideThreadExecutor(JobExecutor jobExecutor) {
    return jobExecutor;
  }

  @Provides @Singleton PostExecutionThread providePostExecutionThread(UIThread uiThread) {
    return uiThread;
  }
}

/**
 * Copyright (C) 2015 android10.org. All rights reserved.
 * @author Fernando Cejas (the android10 coder)
 */
package com.fernandocejas.android10.sample.presentation.internal.di.modules;

import android.content.Context;
import android.view.LayoutInflater;
import com.fernandocejas.android10.sample.data.executor.JobExecutor;
import com.fernandocejas.android10.sample.domain.executor.PostExecutionThread;
import com.fernandocejas.android10.sample.domain.executor.ThreadExecutor;
import com.fernandocejas.android10.sample.presentation.AndroidApplication;
import com.fernandocejas.android10.sample.presentation.UIThread;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;

/**
 * Dagger module that provides objects which will live during the application lifecycle.
 */
@Module
public class ApplicationModule {
  private final AndroidApplication application;

  public ApplicationModule(AndroidApplication application) {
    this.application = application;
  }

  @Provides @Singleton Context provideApplicationContext() {
    return this.application;
  }

  @Provides @Singleton LayoutInflater provideLayoutInflater() {
    return LayoutInflater.from(this.application);
  }

  @Provides @Singleton ThreadExecutor provideThreadExecutor(JobExecutor jobExecutor) {
    return jobExecutor;
  }

  @Provides @Singleton PostExecutionThread providePostExecutionThread(UIThread uiThread) {
    return uiThread;
  }
}

Fix Application module removing wrong type.


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

package com.androidzeitgeist.webcards.processing.pre;

import android.net.Uri;

import okhttp3.Request;

/**
 * Google+ uses a JavaScript based redirector. This pre processor will extract the actual URL from
 * the redirector URL and create a new request.
 */
public class GooglePlusPreProcessor implements PreProcessor {
    private static final String URL_PREFIX = "https://plus.url.google.com/url?q=";

    @Override
    public Request process(Request request) {
        final String url = request.url().toString();

        if (url.startsWith(URL_PREFIX)) {
            final String actualUrl = Uri.parse(url).getQueryParameter("q");

            return request.newBuilder()
                    .url(actualUrl)
                    .build();
        }

        return request;
    }
}

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

package com.androidzeitgeist.webcards.processing.pre;

import android.net.Uri;

import okhttp3.Request;

/**
 * Google+ uses a JavaScript based redirector. This pre processor will extract the actual URL from
 * the redirector URL and create a new request.
 */
public class GooglePlusPreProcessor implements PreProcessor {
    private static final String URL_PREFIX = "://plus.url.google.com/url?q=";

    @Override
    public Request process(Request request) {
        final String url = request.url().toString();

        if (url.contains(URL_PREFIX)) {
            final String actualUrl = Uri.parse(url).getQueryParameter("q");

            if (actualUrl != null) {
                return request.newBuilder()
                        .url(actualUrl)
                        .build();
            }
        }

        return request;
    }
}

Make Google+ pre processor less strict.


/*
 * ******************************************************************************
 *  Copyright 2011-2015 CovertJaguar
 *
 *  This work (the API) is licensed under the "MIT" License, see LICENSE.md for details.
 * ***************************************************************************
 */
package mods.railcraft.api.core;

import com.mojang.authlib.GameProfile;

/**
 * Implemented by objects that can be owned.
 * <p/>
 * Among other uses, when used on a Tile Entity, the Magnifying Glass can be used to inspect the owner.
 *
 * @author CovertJaguar <http://www.railcraft.info/>
 */
public interface IOwnable {
    /**
     * Returns the GameProfile of the owner of the object.
     *
     */
    GameProfile getOwner();

    /**
     * Returns a localization tag (object-tag.name) that can be used in chat messages and such.
     *
     */
    String getLocalizationTag();
}

/*
 * ******************************************************************************
 *  Copyright 2011-2015 CovertJaguar
 *
 *  This work (the API) is licensed under the "MIT" License, see LICENSE.md for details.
 * ***************************************************************************
 */
package mods.railcraft.api.core;

import com.mojang.authlib.GameProfile;
import net.minecraft.world.IWorldNameable;

/**
 * Implemented by objects that can be owned.
 * <p/>
 * Among other uses, when used on a Tile Entity, the Magnifying Glass can be used to inspect the owner.
 *
 * @author CovertJaguar <http://www.railcraft.info/>
 */
public interface IOwnable extends IWorldNameable {
    /**
     * Returns the GameProfile of the owner of the object.
     */
    GameProfile getOwner();
}

Use the new IWorldNameable interface where possible to keep things standardized.


package org.cyclops.everlastingabilities.ability.config;

import net.minecraft.init.MobEffects;
import net.minecraft.item.EnumRarity;
import org.cyclops.cyclopscore.helper.MinecraftHelpers;
import org.cyclops.everlastingabilities.ability.AbilityTypePotionEffectSelf;
import org.cyclops.everlastingabilities.core.config.extendedconfig.AbilityConfig;

/**
 * Config for an ability.
 * @author rubensworks
 *
 */
public class AbilitySaturationConfig extends AbilityConfig {

    /**
     * The unique instance.
     */
    public static AbilityConfig _instance;

    /**
     * Make a new instance.
     */
    public AbilitySaturationConfig() {
        super(
                true,
                "saturation",
                "Reduce hunger",
                new AbilityTypePotionEffectSelf("saturation", EnumRarity.RARE, 3, 30, MobEffects.SATURATION) {
                    @Override
                    protected int getDuration(int tickModulus) {
                        return 1;
                    }

                    @Override
                    protected int getTickModulus() {
                        return MinecraftHelpers.SECOND_IN_TICKS * 5;
                    }
                }
        );
    }
}

package org.cyclops.everlastingabilities.ability.config;

import net.minecraft.init.MobEffects;
import net.minecraft.item.EnumRarity;
import org.cyclops.cyclopscore.helper.MinecraftHelpers;
import org.cyclops.everlastingabilities.ability.AbilityTypePotionEffectSelf;
import org.cyclops.everlastingabilities.core.config.extendedconfig.AbilityConfig;

/**
 * Config for an ability.
 * @author rubensworks
 *
 */
public class AbilitySaturationConfig extends AbilityConfig {

    /**
     * The unique instance.
     */
    public static AbilityConfig _instance;

    /**
     * Make a new instance.
     */
    public AbilitySaturationConfig() {
        super(
                true,
                "saturation",
                "Reduce hunger",
                new AbilityTypePotionEffectSelf("saturation", EnumRarity.EPIC, 3, 30, MobEffects.SATURATION) {
                    @Override
                    protected int getDuration(int tickModulus) {
                        return 1;
                    }

                    @Override
                    protected int getTickModulus() {
                        return MinecraftHelpers.SECOND_IN_TICKS * 5;
                    }
                }
        );
    }
}

Mark saturation as an epic ability


package com.tidyjava.bp.rss;

import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.SyndFeedOutput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import static org.springframework.http.MediaType.APPLICATION_XML_VALUE;

@Controller
public class RssController {

    @Autowired
    private RssFeedGenerator rssFeedGenerator;

    @RequestMapping(path = "/rss/", produces = APPLICATION_XML_VALUE)
    @ResponseBody
    public String rss() throws Exception {
        SyndFeed feed = rssFeedGenerator.generate();
        return new SyndFeedOutput().outputString(feed);
    }
}

package com.tidyjava.bp.rss;

import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.SyndFeedOutput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import static org.springframework.http.MediaType.APPLICATION_XML_VALUE;

@Controller
public class RssController {

    @Autowired
    private RssFeedGenerator rssFeedGenerator;

    @RequestMapping(path = "/rss", produces = APPLICATION_XML_VALUE)
    @ResponseBody
    public String rss() throws Exception {
        SyndFeed feed = rssFeedGenerator.generate();
        return new SyndFeedOutput().outputString(feed);
    }
}

Support RSS path without trailing slash


package net.kencochrane.raven.marshaller.json;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public abstract class AbstractInterfaceBindingTest {
    private JsonFactory jsonFactory;
    private ObjectMapper mapper;
    private ByteArrayOutputStream jsonContentStream;

    @Before
    protected void setUp() throws Exception {
        jsonFactory = new JsonFactory();
        mapper = new ObjectMapper();
    }

    protected JsonGenerator getJsonGenerator() throws IOException {
        jsonContentStream = new ByteArrayOutputStream();
        return jsonFactory.createJsonGenerator(jsonContentStream);
    }

    protected JsonParser getJsonParser() throws IOException {
        return jsonFactory.createJsonParser(jsonContentStream.toByteArray());
    }

    protected ObjectMapper getMapper() {
        return mapper;
    }
}

package net.kencochrane.raven.marshaller.json;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public abstract class AbstractInterfaceBindingTest {
    private JsonFactory jsonFactory;
    private ObjectMapper mapper;
    private ByteArrayOutputStream jsonContentStream;

    @Before
    protected void setUp() throws Exception {
        jsonFactory = new JsonFactory();
        mapper = new ObjectMapper();
    }

    protected JsonGenerator getJsonGenerator() throws IOException {
        jsonContentStream = new ByteArrayOutputStream();
        return jsonFactory.createGenerator(jsonContentStream);
    }

    protected JsonParser getJsonParser() throws IOException {
        return jsonFactory.createParser(jsonContentStream.toByteArray());
    }

    protected ObjectMapper getMapper() {
        return mapper;
    }
}

Remove call to deprecated methods


package config;

import heufybot.core.Logger;
import heufybot.utils.FileUtils;

import java.util.HashMap;

import org.yaml.snakeyaml.Yaml;

public class ServerConfig extends GlobalConfig
{
	@SuppressWarnings("unchecked")
	public void loadServerConfig(String fileName, HashMap<String, Object> globalSettings)
	{
		this.settings = globalSettings;
		if(fileName == null)
		{
			Logger.error("Config", "No seperate server configs found. Using the settings from the global config instead.");
			return;
		}

		Yaml yaml = new Yaml();
		String settingsYaml = FileUtils.readFile(fileName);
		HashMap<String, Object> serverSettings = (HashMap<String, Object>) yaml.load(settingsYaml);

		for(String setting : serverSettings.keySet())
		{
			settings.put(setting, serverSettings.get(setting));
		}
	}
}

package config;

import heufybot.core.Logger;
import heufybot.utils.FileUtils;

import java.util.HashMap;

import org.yaml.snakeyaml.Yaml;

public class ServerConfig extends GlobalConfig
{
	@SuppressWarnings("unchecked")
	public void loadServerConfig(String fileName, HashMap<String, Object> globalSettings)
	{
		this.settings = (HashMap<String, Object>) globalSettings.clone();
		if(fileName == null)
		{
			Logger.error("Config", "No seperate server configs found. Using the settings from the global config instead.");
			return;
		}

		Yaml yaml = new Yaml();
		String settingsYaml = FileUtils.readFile(fileName);
		HashMap<String, Object> serverSettings = (HashMap<String, Object>) yaml.load(settingsYaml);

		for(String setting : serverSettings.keySet())
		{
			settings.put(setting, serverSettings.get(setting));
		}
	}
}

Stop the server configs from overwriting the global one


// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.util.SystemInfo;

public abstract class RemoteDesktopService {
  private static volatile RemoteDesktopService ourInstance;

  public static RemoteDesktopService getInstance() {
    RemoteDesktopService service = ourInstance;
    if (service == null) {
      ourInstance = service = ServiceManager.getService(RemoteDesktopService.class);
    }
    return service;
  }

  public static boolean isRemoteSession() {
    if (!SystemInfo.isWindows) return false;
    return ApplicationManager.getApplication() != null && getInstance().isRemoteDesktopConnected();
  }

  public abstract boolean isRemoteDesktopConnected();
}

// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.util.SystemInfo;

public abstract class RemoteDesktopService {
  private static volatile RemoteDesktopService ourInstance;

  public static RemoteDesktopService getInstance() {
    RemoteDesktopService service = ourInstance;
    if (service == null) {
      ourInstance = service = ServiceManager.getService(RemoteDesktopService.class);
    }
    return service;
  }

  public static boolean isRemoteSession() {
    if (!SystemInfo.isWindows) return false;
    if (ApplicationManager.getApplication() == null) return false;
    RemoteDesktopService instance = getInstance();
    return instance != null && instance.isRemoteDesktopConnected();
  }

  public abstract boolean isRemoteDesktopConnected();
}

Fix NPE at IDE restart


package starpunk;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.tools.imagepacker.TexturePacker2;

public class Main
{
  public static void main( final String[] args )
  {
    final TexturePacker2.Settings settings = new TexturePacker2.Settings();
    settings.maxWidth = 1024;
    settings.maxHeight = 1024;
    TexturePacker2.process( settings, "src/main/resources", "target/assets", "game.atlas" );

    final LwjglApplicationConfiguration configuration = new LwjglApplicationConfiguration();
    configuration.fullscreen = false;
    configuration.width = StarPunkGame.WIDTH;
    configuration.height = StarPunkGame.HEIGHT;
		configuration.useGL20 = true;
		configuration.vSyncEnabled = true;
    configuration.title = "Star Punk";
    new LwjglApplication( new StarPunkGame(), configuration );
  }
}

package starpunk;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

public class Main
{
  public static void main( final String[] args )
  {
    final LwjglApplicationConfiguration configuration = new LwjglApplicationConfiguration();
    configuration.fullscreen = false;
    configuration.width = StarPunkGame.WIDTH;
    configuration.height = StarPunkGame.HEIGHT;
		configuration.useGL20 = true;
		configuration.vSyncEnabled = true;
    configuration.title = "Star Punk";
    new LwjglApplication( new StarPunkGame(), configuration );
  }
}

Remove texture packing as that is now done as part of the texture pipeline


package seedu.watodo.ui;

import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import seedu.watodo.model.task.ReadOnlyTask;

//@@author A0139845R-reused
public class TaskCard extends UiPart<Region> {

    private static final String FXML = "TaskListCard.fxml";

    @FXML
    private HBox cardPane;
    @FXML
    private Label description;
    @FXML
    private Label status;
    @FXML
    private Label id;
    @FXML
    private Label startDate;
    @FXML
    private Label endDate;
    @FXML
    private FlowPane tags;

    public TaskCard(ReadOnlyTask task, int displayedIndex) {
        super(FXML);
        description.setText(task.getDescription().fullDescription);
        id.setText(displayedIndex + ". ");

        if (task.getStartDate() != null) {
            startDate.setText("Start Task From " + task.getStartDate());
        } else {
            startDate.setText("");
        }

        if (task.getEndDate() != null) {
            endDate.setText("Do Task By " + task.getEndDate());
        } else {
            endDate.setText("");
        }

        status.setText(task.getStatus().toString());

        initTags(task);
    }

    private void initTags(ReadOnlyTask person) {
        person.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName)));
    }
}

package seedu.watodo.ui;

import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import seedu.watodo.model.task.ReadOnlyTask;

//@@author A0139845R-reused
public class TaskCard extends UiPart<Region> {

    private static final String FXML = "TaskListCard.fxml";

    @FXML
    private HBox cardPane;
    @FXML
    private Label description;
    @FXML
    private Label status;
    @FXML
    private Label id;
    @FXML
    private Label startDate;
    @FXML
    private Label endDate;
    @FXML
    private FlowPane tags;

    public TaskCard(ReadOnlyTask task, int displayedIndex) {
        super(FXML);
        description.setText(task.getDescription().fullDescription);
        id.setText(displayedIndex + ". ");

        if (task.getStartDate() != null) {
            startDate.setText("Start Task From " + task.getStartDate());
        } else {
            startDate.setText("");
        }

        if (task.getEndDate() != null) {
            endDate.setText("Do Task By " + task.getEndDate());
        } else {
            endDate.setText("");
        }

        status.setText(task.getStatus().toString());
        if (task.getStatus().toString().equals("Done")) {
            cardPane.setStyle("-fx-background-color: #2bba36;");
        }

        initTags(task);
    }

    private void initTags(ReadOnlyTask person) {
        person.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName)));
    }
}

Add more visual aid to marking tasks


package me.eddiep.minecraft.ubotpatcher;

import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class UbotPatcher extends JavaPlugin {

    @Override
    public void onEnable() {
        getLogger().info("Searching for jar files...");

        File[] jars = getDataFolder().listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.getName().endsWith("jar");
            }
        });

        if (jars == null) {
            getLogger().info("No jar files found!");
            getServer().getPluginManager().disablePlugin(this);
            return;
        }

        getLogger().info(jars.length + " jar files found!");

        for (File f : jars) {
            getLogger().info("Moving " + f.getName() + "...");
            File target = new File(getDataFolder().getParentFile(), f.getName());

            try {
                Files.move(f.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        getLogger().info("Patching complete!");
        getServer().getPluginManager().disablePlugin(this);
    }
}

package me.eddiep.minecraft.ubotpatcher;

import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class UbotPatcher extends JavaPlugin {
    @Override
    public void onEnable() {
        getLogger().info("Searching for jar files...");

        File[] jars = getDataFolder().listFiles(pathname -> pathname.getName().endsWith("jar"));

        if (jars == null) {
            getLogger().info("No jar files found!");
            getServer().getPluginManager().disablePlugin(this);
            return;
        }

        getLogger().info(jars.length + " jar files found!");

        for (File f : jars) {
            getLogger().info("Moving " + f.getName() + "...");
            File target = new File(getDataFolder().getParentFile(), f.getName());
            try {
                Files.move(f.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        getLogger().info("Patching complete!");
        getServer().getPluginManager().disablePlugin(this);
    }
}

Update do using lambda expression


package uk.ac.ebi.quickgo.ontology;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalTime;

/**
 * Holds values related to the operation of the Ontology REST service.
 * <p>
 * Created by Tony on 04-Apr-17.
 */
@Component
@ConfigurationProperties(prefix = "ontology.cache.control.time")
public class OntologyRestProperties {

    private static final int MINUTES = 0;
    private static final int DEFAULT_START_HOURS = 18;
    private static final int DEFAULT_END_HOURS = 17;
    private LocalTime startTime = LocalTime.of(DEFAULT_START_HOURS, MINUTES);
    private LocalTime endTime = LocalTime.of(DEFAULT_END_HOURS, MINUTES);
    private long midnightToEndCacheTime;

    public void setStart(int hours) {
        startTime = LocalTime.of(hours, MINUTES);
    }

    public void setEnd(int hours) {
        endTime = LocalTime.of(hours, MINUTES);
        this.midnightToEndCacheTime = Duration.between(LocalTime.MIDNIGHT, endTime).getSeconds();
    }

    public LocalTime getStartTime() {
        return startTime;
    }

    public LocalTime getEndTime() {
        return endTime;
    }

    public long midnightToEndCacheTime() {
        return midnightToEndCacheTime;
    }
}

package uk.ac.ebi.quickgo.ontology;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalTime;

/**
 * Holds values related to the operation of the Ontology REST service.
 * <p>
 * Created by Tony on 04-Apr-17.
 */
@Component
@ConfigurationProperties(prefix = "ontology.cache.control.time")
public class OntologyRestProperties {

    private static final int MINUTES = 0;
    private static final int DEFAULT_START_HOURS = 18;
    private static final int DEFAULT_END_HOURS = 17;
    private LocalTime startTime = LocalTime.of(DEFAULT_START_HOURS, MINUTES);
    private LocalTime endTime = LocalTime.of(DEFAULT_END_HOURS, MINUTES);
    private long midnightToEndCacheTime;

    public void setStart(int hours) {
        startTime = LocalTime.of(hours, MINUTES);
    }

    public void setEnd(int hours) {
        endTime = LocalTime.of(hours, MINUTES);
        this.midnightToEndCacheTime = Duration.between(LocalTime.MIN, endTime).getSeconds();
    }

    public LocalTime getStartTime() {
        return startTime;
    }

    public LocalTime getEndTime() {
        return endTime;
    }

    public long midnightToEndCacheTime() {
        return midnightToEndCacheTime;
    }
}

Replace LocalTime.MIDNIGHT with LocalTime.MIN as this is correct i.e. start of day to finish time, not end of day to finish time!


package sg.ncl.service.authentication;

import org.springframework.stereotype.Service;
import sg.ncl.service.authentication.data.jpa.entities.CredentialsEntity;
import sg.ncl.service.authentication.data.jpa.repositories.CredentialsRepository;
import sg.ncl.service.authentication.exceptions.CredentialsNotFoundException;

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

/**
 * @author Christopher Zhong
 */
@Service
public class AuthenticationService {

    private final CredentialsRepository credentialsRepository;

    @Inject
    protected AuthenticationService(final CredentialsRepository credentialsRepository) {
        this.credentialsRepository = credentialsRepository;
    }

    public String login(final String username, String password) {
        // find the credentials first
        final CredentialsEntity credentials = credentialsRepository.findByUsername(username);
        if (credentials == null) {
            throw new CredentialsNotFoundException();
        }
        // TODO compare password
        // TODO remove existing JWT token
        // TODO generate a new JWT token
        // TODO sign JWT token
        // TODO return JWT token
        return UUID.randomUUID().toString();
    }

    public void logout() {}

}

package sg.ncl.service.authentication;

import org.springframework.stereotype.Service;
import sg.ncl.service.authentication.data.jpa.entities.CredentialsEntity;
import sg.ncl.service.authentication.data.jpa.repositories.CredentialsRepository;
import sg.ncl.service.authentication.exceptions.CredentialsNotFoundException;

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

/**
 * @author Christopher Zhong
 */
@Service
public class AuthenticationService {

    private final CredentialsRepository credentialsRepository;

    @Inject
    protected AuthenticationService(final CredentialsRepository credentialsRepository) {
        this.credentialsRepository = credentialsRepository;
    }

    public String login(final String username, String password) {
        // find the credentials first
        final CredentialsEntity credentials = credentialsRepository.findByUsername(username);
        if (credentials == null) {
            throw new CredentialsNotFoundException();
        }
        // TODO compare password
        // TODO remove existing JWT token
        // TODO generate a new JWT token
        // TODO sign JWT token
        // TODO return JWT token
        return UUID.randomUUID().toString();
    }

}

Remove `logout` method as it is not required for JWT token (DEV-99)


package andraus.bluetoothhidemu.spoof;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;

public final class BluetoothAdapterSpooferFactory {

    private static BluetoothAdapterSpoofer mInstance = null;

    /**
     *
     * @param appContext
     * @param adapter
     * @return
     */
    public static BluetoothAdapterSpoofer getInstance(Context appContext, BluetoothAdapter adapter) {
        if (mInstance == null) {
            mInstance = new BluetoothAdapterSpooferMotoReflect(adapter);
            //mInstance = new BluetoothAdapterSpooferGeneric(appContext, adapter);
        }

        return mInstance;
    }

}

package andraus.bluetoothhidemu.spoof;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;

public final class BluetoothAdapterSpooferFactory {

    private static BluetoothAdapterSpoofer mInstance = null;

    /**
     *
     * @param appContext
     * @param adapter
     * @return
     */
    public static BluetoothAdapterSpoofer getInstance(Context appContext, BluetoothAdapter adapter) {
        if (mInstance == null) {
            //mInstance = new BluetoothAdapterSpooferMotoReflect(adapter);
            mInstance = new BluetoothAdapterSpooferGeneric(appContext, adapter);
        }

        return mInstance;
    }

}

Switch to hid_emu generic implementation for spoofing


package fi.helsinki.cs.tmc.cli.command;

import fi.helsinki.cs.tmc.cli.Application;
import fi.helsinki.cs.tmc.cli.CliContext;
import fi.helsinki.cs.tmc.cli.io.TestIo;

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

public class DocumentCommandTest {

    private Application app;
    private CliContext ctx;
    private TestIo io;

    @Before
    public void setUp() {
        io = new TestIo();
        ctx = new CliContext(io);
        app = new Application(ctx);
    }

    @Test
    public void run() throws InterruptedException {
        app = new Application(ctx);

        String[] args = {"document", "-s", "0"};
        app.run(args);
        io.assertContains("dev team");
    }
}

package fi.helsinki.cs.tmc.cli.command;

import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;

import fi.helsinki.cs.tmc.cli.Application;
import fi.helsinki.cs.tmc.cli.CliContext;
import fi.helsinki.cs.tmc.cli.io.EnvironmentUtil;
import fi.helsinki.cs.tmc.cli.io.TestIo;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(EnvironmentUtil.class)
public class DocumentCommandTest {

    private Application app;
    private CliContext ctx;
    private TestIo io;

    @Before
    public void setUp() {
        io = new TestIo();
        ctx = new CliContext(io);
        app = new Application(ctx);

        mockStatic(EnvironmentUtil.class);
        when(EnvironmentUtil.getTerminalWidth()).thenReturn(100);
    }

    @Test
    public void run() throws InterruptedException {
        when(EnvironmentUtil.isWindows()).thenReturn(false);
        app = new Application(ctx);

        String[] args = {"document", "-s", "0"};
        app.run(args);
        io.assertContains("Original dev team");
    }

    @Test
    public void failOnWindows() throws InterruptedException {
        when(EnvironmentUtil.isWindows()).thenReturn(true);
        app = new Application(ctx);

        String[] args = {"document", "-s", "0"};
        app.run(args);
        io.assertContains("Command document doesn't exist");
    }
}

Fix document command test in Windows.


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

package io.spine.server.storage.memory;

import io.spine.server.aggregate.AggregateStorageTruncationTest;
import org.junit.jupiter.api.DisplayName;

@DisplayName("`AggregateStorage` running in-memory after truncation should")
public class InMemoryAggregateStorageTruncationTest extends AggregateStorageTruncationTest {

}

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

package io.spine.server.storage.memory;

import io.spine.server.aggregate.AggregateStorageTruncationTest;
import org.junit.jupiter.api.DisplayName;

@DisplayName("`InMemoryAggregateStorage`")
class InMemoryAggregateStorageTruncationTest extends AggregateStorageTruncationTest {
}

Use a proper display name for the test class descendant.


package org.wildfly.swarm.examples.ds.deployment;

import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.wildfly.swarm.Swarm;
import org.wildfly.swarm.container.Container;
import org.wildfly.swarm.datasources.DatasourceArchive;
import org.wildfly.swarm.jaxrs.JAXRSArchive;
import org.wildfly.swarm.spi.api.JARArchive;

/**
 * @author Bob McWhirter
 */
public class Main {

    public static void main(String[] args) throws Exception {

        Container container = new Container();

        container.start();

        // Create a JDBC driver deployment using maven groupId:artifactId
        // The version is resolved from your pom.xml's <dependency>
        container.deploy(Swarm.artifact("com.h2database:h2", "h2"));

        // Create a DS deployment
        JARArchive dsArchive = ShrinkWrap.create(JARArchive.class);
        dsArchive.as(DatasourceArchive.class).dataSource("ExampleDS", (ds) -> {
            ds.connectionUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
            ds.driverName("h2");
            ds.userName("sa");
            ds.password("sa");
        });

        // Deploy the datasource
        container.deploy(dsArchive);

        JAXRSArchive appDeployment = ShrinkWrap.create(JAXRSArchive.class);
        appDeployment.addResource(MyResource.class);

        // Deploy your app
        container.deploy(appDeployment);

    }
}

package org.wildfly.swarm.examples.ds.deployment;

import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.wildfly.swarm.Swarm;
import org.wildfly.swarm.container.Container;
import org.wildfly.swarm.datasources.DatasourceArchive;
import org.wildfly.swarm.jaxrs.JAXRSArchive;
import org.wildfly.swarm.spi.api.JARArchive;

/**
 * @author Bob McWhirter
 */
public class Main {

    public static void main(String[] args) throws Exception {

        Container container = new Container();

        container.start();

        // Create a JDBC driver deployment using maven groupId:artifactId
        // The version is resolved from your pom.xml's <dependency>
        container.deploy(Swarm.artifact("com.h2database:h2", "h2"));

        // Create a DS deployment
        DatasourceArchive dsArchive = ShrinkWrap.create(DatasourceArchive.class);
        dsArchive.dataSource("ExampleDS", (ds) -> {
            ds.connectionUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
            ds.driverName("h2");
            ds.userName("sa");
            ds.password("sa");
        });

        // Deploy the datasource
        container.deploy(dsArchive);

        JAXRSArchive appDeployment = ShrinkWrap.create(JAXRSArchive.class);
        appDeployment.addResource(MyResource.class);

        // Deploy your app
        container.deploy(appDeployment);

    }
}

Adjust the ds deployment example to use the directly-usable DatasourceArchive.


package io.github.elytra.movingworld.common.asm.coremod;

import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin;

import org.spongepowered.asm.launch.MixinBootstrap;
import org.spongepowered.asm.mixin.Mixins;

import java.util.Map;

@IFMLLoadingPlugin.MCVersion(value = "1.10.2")
public class MovingWorldCoreMod implements IFMLLoadingPlugin {

    public MovingWorldCoreMod() {
        MixinBootstrap.init();
        Mixins.addConfiguration("mixins.movingworld.json");
    }

    @Override
    public String[] getASMTransformerClass() {
        return null;
    }

    @Override
    public String getModContainerClass() {
        return "io.github.elytra.movingworld.common.asm.coremod.MovingWorldModContainer";
    }

    @Override
    public String getSetupClass() {
        return null;
    }

    @Override
    public void injectData(Map<String, Object> data) {
    }

    @Override
    public String getAccessTransformerClass() {
        return "io.github.elytra.movingworld.common.asm.coremod.MovingWorldAccessTransformer";
    }

}

package io.github.elytra.movingworld.common.asm.coremod;

import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin;

import org.spongepowered.asm.launch.MixinBootstrap;
import org.spongepowered.asm.mixin.Mixins;

import java.util.Map;

@IFMLLoadingPlugin.MCVersion(value = "1.11")
public class MovingWorldCoreMod implements IFMLLoadingPlugin {

    public MovingWorldCoreMod() {
        MixinBootstrap.init();
        Mixins.addConfiguration("mixins.movingworld.json");
    }

    @Override
    public String[] getASMTransformerClass() {
        return null;
    }

    @Override
    public String getModContainerClass() {
        return "io.github.elytra.movingworld.common.asm.coremod.MovingWorldModContainer";
    }

    @Override
    public String getSetupClass() {
        return null;
    }

    @Override
    public void injectData(Map<String, Object> data) {
    }

    @Override
    public String getAccessTransformerClass() {
        return "io.github.elytra.movingworld.common.asm.coremod.MovingWorldAccessTransformer";
    }

}

Adjust mc version number in core mod.


package guitests;

public class UndoCommandTest {

}

package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import seedu.address.logic.commands.UndoCommand;
import seedu.address.testutil.TestTask;
import seedu.address.testutil.TestUtil;

public class UndoCommandTest extends TaskManagerGuiTest {

    private TestTask[] expectedList = td.getTypicalTasks();

    /**
     * Tries to undo an add command
     */
    @Test
        TestTask taskToAdd = td.alice;
        commandBox.runCommand(taskToAdd.getAddCommand());
        assertUndoSuccess(expectedList);
    }

}

Add test case for undo add command


/*
 * Copyright 2011-2016 B2i Healthcare Pte Ltd, http://b2i.sg
 *
 * 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.b2international.snowowl.core.api;

import bak.pcj.LongCollection;

/**
 * @since 4.6
 */
public interface ITreeComponent {

	/**
	 * @return the ancestor IDs of this component
	 */
	LongCollection getAncestors();

	/**
	 * @return the direct parent IDs of this component
	 */
	LongCollection getParents();

}

/*
 * Copyright 2011-2016 B2i Healthcare Pte Ltd, http://b2i.sg
 *
 * 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.b2international.snowowl.core.api;

import com.b2international.commons.collections.primitive.LongCollection;

/**
 * @since 4.6
 */
public interface ITreeComponent {

	/**
	 * @return the ancestor IDs of this component
	 */
	LongCollection getAncestors();

	/**
	 * @return the direct parent IDs of this component
	 */
	LongCollection getParents();

}

Update class in com.b2international.snowowl.core bundle


package org.jvirtanen.parity.net.poe;

import static java.nio.charset.StandardCharsets.*;

import java.nio.ByteBuffer;

class ByteBuffers {

    private static final byte SPACE = ' ';

    static String getString(ByteBuffer buffer, int length) {
        byte[] bytes = new  byte[length];

        buffer.get(bytes);

        return new String(bytes, US_ASCII);
    }

    static void putString(ByteBuffer buffer, String value, int length) {
        byte[] bytes = value.getBytes(US_ASCII);

        int i = 0;

        for (; i < Math.min(bytes.length, length); i++)
            buffer.put(bytes[i]);

        for (; i < length; i++)
            buffer.put(SPACE);
    }

}

package org.jvirtanen.parity.net.poe;

import static java.nio.charset.StandardCharsets.*;

import java.nio.ByteBuffer;

class ByteBuffers {

    private static final byte SPACE = ' ';

    static String getString(ByteBuffer buffer, int length) {
        byte[] bytes = new  byte[length];

        buffer.get(bytes);

        return new String(bytes, US_ASCII);
    }

    static void putString(ByteBuffer buffer, String value, int length) {
        int i = 0;

        for (; i < Math.min(value.length(), length); i++)
            buffer.put((byte)value.charAt(i));

        for (; i < length; i++)
            buffer.put(SPACE);
    }

}

Improve string encoding in network protocols


package test.com.github.tmurakami.dexopener;

import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.v4.app.FragmentActivity;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.willReturn;

public class MyFragmentTest {

    @Rule
    public final ActivityTestRule<FragmentActivity> rule = new ActivityTestRule<>(FragmentActivity.class, false, false);

    @Mock
    MyService service;

    private final MyFragment target = new MyFragment();

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        target.service = service;
    }

    @Test
    public void testOnCreate() {
        Object o = new Object();
        willReturn(o).given(service).doIt();
        rule.launchActivity(null).getSupportFragmentManager().beginTransaction().add(target, null).commit();
        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
        assertEquals(o, target.result);
    }

}

package test.com.github.tmurakami.dexopener;

import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.v4.app.FragmentActivity;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.willReturn;

public class MyFragmentTest {

    @Rule
    public final ActivityTestRule<FragmentActivity> rule = new ActivityTestRule<>(FragmentActivity.class);

    @Mock
    MyService service;

    private final MyFragment target = new MyFragment();

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        target.service = service;
    }

    @Test
    public void testOnCreate() {
        Object o = new Object();
        willReturn(o).given(service).doIt();
        rule.getActivity().getSupportFragmentManager().beginTransaction().add(target, null).commit();
        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
        assertEquals(o, target.result);
    }

}

Fix to work on CI


package tc.oc.commons.bukkit.chat;

import net.md_5.bungee.api.chat.BaseComponent;
import org.bukkit.entity.Player;
import tc.oc.commons.core.chat.Component;
import tc.oc.commons.core.chat.Components;

public class LegacyPlayerAudience extends PlayerAudience {

    private BaseComponent recentHotbarMessage;

    public LegacyPlayerAudience(Player player) {
        super(player);
    }

    @Override
    public void sendHotbarMessage(BaseComponent message) {
        // Do not spam hot bar messages, as the protocol converts
        // them to regular chat messages.
        if(!Components.equals(message, recentHotbarMessage)) {
            super.sendHotbarMessage(message);
            recentHotbarMessage = message;
        }
    }

    @Override
    public void showTitle(BaseComponent title, BaseComponent subtitle, int inTicks, int stayTicks, int outTicks) {
        super.sendMessage(new Component(title).extra(" ").extra(subtitle));
    }
}

package tc.oc.commons.bukkit.chat;

import net.md_5.bungee.api.chat.BaseComponent;
import org.bukkit.entity.Player;
import tc.oc.commons.core.chat.Components;
import tc.oc.commons.core.stream.Collectors;

import java.util.stream.Stream;

public class LegacyPlayerAudience extends PlayerAudience {

    private BaseComponent recentHotbarMessage;

    public LegacyPlayerAudience(Player player) {
        super(player);
    }

    @Override
    public void sendHotbarMessage(BaseComponent message) {
        // Do not spam hot bar messages, as the protocol converts
        // them to regular chat messages.
        if(!Components.equals(message, recentHotbarMessage)) {
            emphasize(message);
            recentHotbarMessage = message;
        }
    }

    @Override
    public void showTitle(BaseComponent title, BaseComponent subtitle, int inTicks, int stayTicks, int outTicks) {
        emphasize(Components.join(Components.space(), Stream.of(title, subtitle).filter(msg -> msg != null).collect(Collectors.toImmutableList())));
    }

    protected void emphasize(BaseComponent message) {
        sendMessage(Components.blank());
        sendMessage(message);
        sendMessage(Components.blank());
    }

}

Make titles and hotbars more visible


package com.boundary.metrics.vmware.client.client.subaccount;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class SubaccountInfo {

    @JsonProperty
    @NotEmpty
    private String email;

    @JsonProperty
    @NotEmpty
    private String apiToken;

    public String getCredentials() {
        return email + ":" + apiToken;
    }
}

package com.boundary.metrics.vmware.client.client.subaccount;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class SubAccountInfo {

    @JsonProperty
    @NotEmpty
    private String email;

    @JsonProperty
    @NotEmpty
    private String apiToken;

    public String getCredentials() {
        return email + ":" + apiToken;
    }
}

Change class name to match file name


package org.lamport.tla.toolbox.jcloud;

public class EC2CloudTLCInstanceParameters extends CloudTLCInstanceParameters {

	@Override
	public String getOwnerId() {
		// ubuntu official
		return "owner-id=owner-id=099720109477;state=available;image-type=machine";
	}

	@Override
	public String getCloudProvier() {
		return "aws-ec2";
	}

	@Override
	public String getImageId() {
		// ubuntu 64bit 14.04 precise paravirtual release
		// https://cloud-images.ubuntu.com/releases/14.04/release/
		return "us-east-1/ami-30837058";
	}

	@Override
	public String getHardwareId() {
		return "m2.4xlarge";
	}

	@Override
	public String getJavaSystemProperties() {
		return "-Dtlc2.tool.fp.FPSet.impl=tlc2.tool.fp.OffHeapDiskFPSet";
	}

	@Override
	public String getJavaVMArgs() {
		return "-Xmx24G -Xms24G -XX:MaxDirectMemorySize=32g";
	}

	@Override
	public String getTLCParameters() {
		return "-workers 12";
	}
}

package org.lamport.tla.toolbox.jcloud;

public class EC2CloudTLCInstanceParameters extends CloudTLCInstanceParameters {

	@Override
	public String getOwnerId() {
		// ubuntu official
		return "owner-id=owner-id=099720109477;state=available;image-type=machine";
	}

	@Override
	public String getCloudProvier() {
		return "aws-ec2";
	}

	@Override
	public String getImageId() {
		// ubuntu 64bit 14.04 trusty paravirtual release
		// https://cloud-images.ubuntu.com/releases/14.04/release/
		return "us-east-1/ami-e411d98c";
	}

	@Override
	public String getHardwareId() {
		return "m2.4xlarge";
	}

	@Override
	public String getJavaSystemProperties() {
		return "-Dtlc2.tool.fp.FPSet.impl=tlc2.tool.fp.OffHeapDiskFPSet";
	}

	@Override
	public String getJavaVMArgs() {
		return "-Xmx24G -Xms24G -XX:MaxDirectMemorySize=32g";
	}

	@Override
	public String getTLCParameters() {
		return "-workers 12";
	}
}

Use most recent Trusty Tahir image 14.4.1