package com.github.dockerjava.okhttp;

import com.github.dockerjava.transport.DomainSocket;

import javax.net.SocketFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

class UnixSocketFactory extends SocketFactory {

    private final String socketPath;

    UnixSocketFactory(String socketPath) {
        this.socketPath = socketPath;
    }

    @Override
    public Socket createSocket() {
        try {
            return DomainSocket.get(socketPath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Socket createSocket(String s, int i) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Socket createSocket(String s, int i, InetAddress inetAddress, int i1) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Socket createSocket(InetAddress inetAddress, int i) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Socket createSocket(InetAddress inetAddress, int i, InetAddress inetAddress1, int i1) {
        throw new UnsupportedOperationException();
    }
}

package com.github.dockerjava.okhttp;

import com.github.dockerjava.transport.UnixSocket;

import javax.net.SocketFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

class UnixSocketFactory extends SocketFactory {

    private final String socketPath;

    UnixSocketFactory(String socketPath) {
        this.socketPath = socketPath;
    }

    @Override
    public Socket createSocket() {
        try {
            return UnixSocket.get(socketPath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Socket createSocket(String s, int i) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Socket createSocket(String s, int i, InetAddress inetAddress, int i1) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Socket createSocket(InetAddress inetAddress, int i) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Socket createSocket(InetAddress inetAddress, int i, InetAddress inetAddress1, int i1) {
        throw new UnsupportedOperationException();
    }
}

Use UnixDocket in OkHttp as well

Use UnixDocket in OkHttp as well


package ru.stqa.pft.addressbook.tests;

import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.ContactData;

/**
 * Created by gis on 09.11.2016.
 */
public class ContactModificationTests extends TestBase {

    @Test
    public void testContactModification() {
        app.getNavigationHelper().gotoHome();
        app.getContactHelper().initContactModification();
        ContactData contactData = new ContactData();
        contactData
                .setFirstname("Lee")
                .setLastname("Chan")
                .setTitle("Mr.")
                .setAddress("Flat D, 6/F, Golden Industrial Center, Block 4, 182-190 Tai Lin Pai Road, Kwai Chung")
                .setHomePhone("(852) 2877-8933")
                .setEmail("hongkong@ihg.com");

        app.getContactHelper().fillContactForm(contactData);
        app.getContactHelper().submitContactModification();
        app.getNavigationHelper().gotoHomePage();
    }
}

Revert "Revert "add line separator""

Revert "Revert "add line separator""

This reverts commit 41e1b3ffd43fd15eba9aff564e90abc91dc5f49d.


// Copyright (c) 2014 Eugene Zhuk.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.

package com.ezhuk.wear.common;

import com.google.android.gms.wearable.DataEvent;

import junit.framework.TestCase;

public class DataListenerTest extends TestCase {
    private static final String DATA_PATH = "/data";

    private static class MockCallback implements DataListener.Callback {
        @Override
        public void onDataChanged(DataEvent event) {
            // empty
        }
    }

    protected void setUp() {
        // empty
    }

    protected void tearDown() {
        // empty
    }

    public void testAddCallback() {
        DataListener listener = new DataListener();
        listener.addCallback(DATA_PATH, new MockCallback());
        assertNotNull(listener.getCallback(DATA_PATH));
    }

    public void testRemoveCallback() {
        DataListener listener = new DataListener();
        listener.addCallback(DATA_PATH, new MockCallback());
        listener.removeCallback(DATA_PATH);
        assertNull(listener.getCallback(DATA_PATH));
    }
}

// Copyright (c) 2014 Eugene Zhuk.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.

package com.ezhuk.wear.common;

import android.net.Uri;

import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataItem;

import junit.framework.TestCase;

import org.mockito.Mockito;

public class DataListenerTest extends TestCase {
    private static final String DATA_PATH = "/data";

    protected void setUp() {
        // empty
    }

    protected void tearDown() {
        // empty
    }

    public void testAddCallback() {
        DataListener listener = new DataListener();
        assertNull(listener.getCallback(DATA_PATH));

        listener.addCallback(DATA_PATH, Mockito.mock(DataListener.Callback.class));
        assertNotNull(listener.getCallback(DATA_PATH));
    }

    public void testRemoveCallback() {
        DataListener listener = new DataListener();
        assertNull(listener.getCallback(DATA_PATH));

        listener.addCallback(DATA_PATH, Mockito.mock(DataListener.Callback.class));
        assertNotNull(listener.getCallback(DATA_PATH));

        listener.removeCallback(DATA_PATH);
        assertNull(listener.getCallback(DATA_PATH));
    }

    public void testDataChanged() {
        DataItem item = Mockito.mock(DataItem.class);
        Mockito.when(item.getUri()).thenReturn(Uri.parse(DATA_PATH));

        DataEvent event = Mockito.mock(DataEvent.class);
        Mockito.when(event.getType()).thenReturn(DataEvent.TYPE_CHANGED);
        Mockito.when(event.getDataItem()).thenReturn(item);

        DataListener listener = new DataListener();
        DataListener.Callback callback = Mockito.mock(DataListener.Callback.class);
        listener.addCallback(DATA_PATH, callback);

        // TODO

        Mockito.verify(callback).onDataChanged(event);
        Mockito.verifyNoMoreInteractions(callback);
    }
}

Use mockito in data listener tests.

Use mockito in data listener tests.


import guiLayer.startUpFrame;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.SQLException;

public class startUI extends Thread {
    private static JPanel startupFrame;

    public void run() {
        try {
            startUI();
        } catch (ClassNotFoundException | UnsupportedLookAndFeelException | IllegalAccessException | InstantiationException | SQLException e) {
            System.out.println("An error occured, oh shit.");
        }
    }
    // Start up everything
    public static void startUI() throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException, SQLException {
        // Setup the window decorator
        JFrame.setDefaultLookAndFeelDecorated(true);
        //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

        // Load the UI
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    final JFrame frame = new JFrame();
                    frame.setTitle("Morocco Holiday Center");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setBounds(100, 100, 660, 430);
                    frame.setVisible(true);

                    startupFrame = new JPanel();
                    startupFrame.setBorder(new EmptyBorder(5, 5, 5, 5));
                    frame.setContentPane(startupFrame);
                    startupFrame.setLayout(null);

                    startUpFrame startUpFrame = new startUpFrame(frame);
                    frame.setContentPane(startUpFrame);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

import guiLayer.startUpFrame;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.SQLException;

public class startUI extends Thread {
    private static JPanel startupFrame;

    public void run() {
        try {
            startUI();
        } catch (ClassNotFoundException | UnsupportedLookAndFeelException | IllegalAccessException | InstantiationException | SQLException e) {
            System.out.println("An error occured, oh shit.");
        }
    }
    // Start up everything
    public static void startUI() throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException, SQLException {
        // Setup the window decorator
        JFrame.setDefaultLookAndFeelDecorated(true);
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

        // Load the UI
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    final JFrame frame = new JFrame();
                    frame.setTitle("Morocco Holiday Center");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setBounds(100, 100, 660, 430);
                    frame.setVisible(true);

                    startupFrame = new JPanel();
                    startupFrame.setBorder(new EmptyBorder(5, 5, 5, 5));
                    frame.setContentPane(startupFrame);
                    startupFrame.setLayout(null);

                    startUpFrame startUpFrame = new startUpFrame(frame);
                    frame.setContentPane(startUpFrame);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

Make the UI use the native look and feel of the system itself.. Don't hardcode it!


package com.gramboid.rxappfocus;

import android.app.Activity;
import android.app.Application;
import android.app.Application.ActivityLifecycleCallbacks;

import rx.Observable;
import rx.subjects.PublishSubject;

/**
 * Provides Observables to monitor app visibility.
 */
public class AppFocusProvider {

    private boolean changingConfig;
    private int     foregroundCounter;

    private final PublishSubject<Boolean> subject = PublishSubject.create();

    private final ActivityLifecycleCallbacks callbacks = new DefaultActivityLifecycleCallbacks() {

        @Override
        public void onActivityStarted(Activity activity) {
            if (changingConfig) {
                // ignore activity start, just a config change
                changingConfig = false;
            } else {
                incrementVisibleCounter();
            }
        }

        @Override
        public void onActivityStopped(Activity activity) {
            if (activity.isChangingConfigurations()) {
                // ignore activity stop, just a config change
                changingConfig = true;
            } else {
                decrementVisibleCounter();
            }
        }

    };

    private void incrementVisibleCounter() {
        final boolean justBecomingVisible = !isVisible();
        foregroundCounter++;
        if (justBecomingVisible) {
            subject.onNext(true);
        }
    }

    private void decrementVisibleCounter() {
        foregroundCounter--;
        if (!isVisible()) {
            subject.onNext(false);
        }
    }

    public AppFocusProvider(Application app) {
        app.registerActivityLifecycleCallbacks(callbacks);
    }

    public boolean isVisible() {
        return foregroundCounter > 0;
    }

    public Observable<Boolean> getAppFocus() {
        return subject;
    }

}

package com.gramboid.rxappfocus;

import android.app.Activity;
import android.app.Application;
import android.app.Application.ActivityLifecycleCallbacks;

import rx.Observable;
import rx.subjects.ReplaySubject;

/**
 * Provides Observables to monitor app visibility.
 */
public class AppFocusProvider {

    private boolean changingConfig;
    private int     foregroundCounter;

    private final ReplaySubject<Boolean> subject = ReplaySubject.createWithSize(1);

    private final ActivityLifecycleCallbacks callbacks = new DefaultActivityLifecycleCallbacks() {

        @Override
        public void onActivityStarted(Activity activity) {
            if (changingConfig) {
                // ignore activity start, just a config change
                changingConfig = false;
            } else {
                incrementVisibleCounter();
            }
        }

        @Override
        public void onActivityStopped(Activity activity) {
            if (activity.isChangingConfigurations()) {
                // ignore activity stop, just a config change
                changingConfig = true;
            } else {
                decrementVisibleCounter();
            }
        }

    };

    private void incrementVisibleCounter() {
        final boolean justBecomingVisible = !isVisible();
        foregroundCounter++;
        if (justBecomingVisible) {
            subject.onNext(true);
        }
    }

    private void decrementVisibleCounter() {
        foregroundCounter--;
        if (!isVisible()) {
            subject.onNext(false);
        }
    }

    public AppFocusProvider(Application app) {
        app.registerActivityLifecycleCallbacks(callbacks);
    }

    public boolean isVisible() {
        return foregroundCounter > 0;
    }

    public Observable<Boolean> getAppFocus() {
        return subject;
    }

}

Allow late subscribers to immediately get the visibility status


package fr.neamar.kiss.pojo;

import java.util.Comparator;

public class PojoComparator implements Comparator<Pojo> {
    @Override
    public int compare(Pojo lhs, Pojo rhs) {
        return (lhs.relevance < rhs.relevance ? 1 : (lhs.relevance == rhs.relevance ? 0 : -1));
    }
}

package fr.neamar.kiss.pojo;

import java.util.Comparator;

public class PojoComparator implements Comparator<Pojo> {
    @Override
    public int compare(Pojo lhs, Pojo rhs) {
        return rhs.relevance - lhs.relevance;
    }
}

Improve comparison between two pojos

Improve comparison between two pojos


package com.sloshydog.eventuate.inmemory;

import com.sloshydog.eventuate.api.Event;
import com.sloshydog.eventuate.api.EventSpecification;
import com.sloshydog.eventuate.api.EventStore;
import com.sloshydog.eventuate.api.EventStream;

public class InMemoryEventStore implements EventStore {

    @Override
    public void store(Event applicationEvent) {

    }

    @Override
    public EventStream getMatching(EventSpecification eventSpecification) {
        return null;
    }
}

package com.sloshydog.eventuate.inmemory;

import com.sloshydog.eventuate.api.Event;
import com.sloshydog.eventuate.api.EventSpecification;
import com.sloshydog.eventuate.api.EventStore;
import com.sloshydog.eventuate.api.EventStream;

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

public class InMemoryEventStore implements EventStore {
    private final List<Event> events = new ArrayList<Event>();

    @Override
    public void store(Event applicationEvent) {
        events.add(applicationEvent);
    }

    @Override
    public EventStream getMatching(EventSpecification eventSpecification) {
        return new EventStream() {
            @Override
            public Iterator<Event> iterator() {
                return events.iterator();
            }
        };
    }
}

Implement the in memory event store so unit test passes.


package org.rmatil.sync.persistence.core.dht;

import net.tomp2p.peers.Number160;
import net.tomp2p.utils.Utils;
import org.rmatil.sync.persistence.api.IPathElement;

import java.security.PublicKey;

/**
 * A path element representing data in the DHT
 */
public class DhtPathElement implements IPathElement {

    /**
     * The content key of the path element which should be used
     */
    protected String contentKey;

    /**
     * The domain protection key which should be used
     */
    protected Number160 domainProtectionKey;

    /**
     * @param contentKey A string which gets used as content key in the DHT
     * @param domainProtectionKey A public key which is used for to access and/or modify the path in the DHT
     */
    public DhtPathElement(String contentKey, PublicKey domainProtectionKey) {
        this.contentKey = contentKey;
        this.domainProtectionKey = Utils.makeSHAHash(domainProtectionKey.getEncoded());
    }

    /**
     * Returns the content key
     *
     * @return A string representing the path of the element
     */
    @Override
    public String getPath() {
        return this.contentKey;
    }

    /**
     * Returns the domain protection key which is used
     * to access and/or modify the content in the DHT
     *
     * @return The domain protection key
     */
    public Number160 getDomainProtectionKey() {
        return domainProtectionKey;
    }
}

package org.rmatil.sync.persistence.core.dht;

import net.tomp2p.peers.Number160;
import net.tomp2p.utils.Utils;
import org.rmatil.sync.persistence.api.IPathElement;

import java.security.Key;

/**
 * A path element representing data in the DHT
 */
public class DhtPathElement implements IPathElement {

    /**
     * The content key of the path element which should be used
     */
    protected String contentKey;

    /**
     * The domain protection key which should be used
     */
    protected Number160 domainProtectionKey;

    /**
     * @param contentKey A string which gets used as content key in the DHT
     * @param domainProtectionKey A public key which is used to access the path in the DHT
     */
    public DhtPathElement(String contentKey, Key domainProtectionKey) {
        this.contentKey = contentKey;
        this.domainProtectionKey = Utils.makeSHAHash(domainProtectionKey.getEncoded());
    }

    /**
     * Returns the content key
     *
     * @return A string representing the path of the element
     */
    @Override
    public String getPath() {
        return this.contentKey;
    }

    /**
     * Returns the domain protection key which is used
     * to access the content in the DHT
     *
     * @return The domain protection key
     */
    public Number160 getDomainProtectionKey() {
        return domainProtectionKey;
    }
}

Use a generic key instead of PublicKey

Use a generic key instead of PublicKey


package com.nitorcreations.willow.servers;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import org.apache.shiro.guice.web.ShiroWebModule;
import org.eclipse.sisu.space.SpaceModule;
import org.eclipse.sisu.space.URLClassSpace;
import org.eclipse.sisu.wire.WireModule;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;

public class WillowServletContextListener extends GuiceServletContextListener {
  private ServletContext servletContext;

  @Override
  public void contextInitialized(ServletContextEvent servletContextEvent) {
    this.servletContext = servletContextEvent.getServletContext();
    super.contextInitialized(servletContextEvent);
  }

  @Override
  protected Injector getInjector() {
    ClassLoader classloader = getClass().getClassLoader();
    return  Guice.createInjector(
      new WireModule(new ApplicationServletModule(),
        new WillowShiroModule(servletContext),
        ShiroWebModule.guiceFilterModule(),
        new SpaceModule(
          new URLClassSpace(classloader)
          )));
  }
}

package com.nitorcreations.willow.servers;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import org.apache.shiro.guice.web.ShiroWebModule;
import org.eclipse.sisu.space.SpaceModule;
import org.eclipse.sisu.space.URLClassSpace;
import org.eclipse.sisu.wire.WireModule;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;

public class WillowServletContextListener extends GuiceServletContextListener {
  private ServletContext servletContext;

  @Override
  public void contextInitialized(ServletContextEvent servletContextEvent) {
    this.servletContext = servletContextEvent.getServletContext();
    super.contextInitialized(servletContextEvent);
  }

  @Override
  protected Injector getInjector() {
    ClassLoader classloader = getClass().getClassLoader();
    return  Guice.createInjector(
      new WireModule(new ApplicationServletModule(),
        getShiroModule(), ShiroWebModule.guiceFilterModule(),
        new SpaceModule(
          new URLClassSpace(classloader)
          )));
  }
  protected ShiroWebModule getShiroModule() {
    return new WillowShiroModule(servletContext);
  }
}

Put shiro module into an easily overridable function


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kawansoft.aceql.gui.util;

/**
 *
 * @author Nicolas de Pomereu
 */
public class AceQLManagerUtil {

    public static void systemExitWrapper() {
        System.exit(0);

    }

    public static void printEvent(Object obj) {
        boolean print = false;
        if (print) {
            System.out.println(obj);
        }
    }

}

Refactor and follow codacy.com best practices


/*
 * *
 *  * LayoutUtil.java
 *  * as part of mkcommons-android
 *  *
 *  * Created by michaelkuck, last updated on 7/25/14 1:00 PM
 *  * Unless otherwise stated in a separate LICENSE file for this project
 *  * or agreed via contract, all rights reserved by the author.
 *
 */

package com.michael_kuck.android.mkcommons;

import android.content.Context;
import android.graphics.Point;
import android.util.TypedValue;

/**
 * Created by michaelkuck on 7/25/14.
 */
public class LayoutUtil {

    public static Point dpToP(final Context context, final Point point) {
        int x = (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, point.x, context.getResources().getDisplayMetrics());
        int y = (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, point.y, context.getResources().getDisplayMetrics());
        return new Point(x, y);
    }

    public static int dpToP(final Context context, final int pixel) {
        return (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, pixel, context.getResources().getDisplayMetrics());
    }

}

/*
 * *
 *  * LayoutUtil.java
 *  * as part of mkcommons-android
 *  *
 *  * Created by michaelkuck, last updated on 7/25/14 1:00 PM
 *  * Unless otherwise stated in a separate LICENSE file for this project
 *  * or agreed via contract, all rights reserved by the author.
 *
 */

package com.michael_kuck.android.mkcommons;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.graphics.PointF;
import android.util.TypedValue;

/**
 * Created by michaelkuck on 7/25/14.
 */
public class LayoutUtil {

    public static float pixelFromDp(final float dpPixel) {
        final Resources resources = Android.getApplication().getResources();
        final float pixel = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpPixel, resources.getDisplayMetrics());
        return pixel;
    }

    public static int pixelFromDp(final int dpPixel) {
        return (int) pixelFromDp((float)dpPixel);
    }

    public static PointF pixelsFromDpPoint(final PointF dpPixels) {
        final PointF pixels = new PointF(pixelFromDp(dpPixels.x), pixelFromDp(dpPixels.y));
        return pixels;
    }

    public static Point pixelsFromDpPoint(final Point dpPixels) {
        final Point pixels = new Point(pixelFromDp(dpPixels.x), pixelFromDp(dpPixels.y));
        return pixels;
    }

}

Add methods for converting resolution independent pixels (dp) to real pixels and the other way round.


package org.jboss.rhiot.services.api;

/**
 * Created by sstark on 5/25/16.
 */
public interface IRHIoTTagScanner {
}

package org.jboss.rhiot.services.api;

/**
 * Created by sstark on 5/25/16.
 */
public interface IRHIoTTagScanner {
   // Metrics keys
   // Set 1, the tag data sent on every advertisement event
   static final String TAG_TEMP = "rhiotTag.temperature";
   static final String TAG_KEYS = "rhiotTag.keys";
   static final String TAG_LUX = "rhiotTag.lux";
   // Set 2, the game state information sent on an event such as a key press or state timeout
   static final String TAG_PREV_STATE = "rhiotTag.prevState";
   static final String TAG_NEW_STATE = "rhiotTag.newState";
   static final String TAG_EVENT = "rhiotTag.event";
   // Set 3, the game progress information sent while the game is active.
   static final String TAG_GAME_TIME_LEFT = "rhiotTag.gameTimeLeft";
   static final String TAG_GAME_SCORE = "rhiotTag.gameScore";
   static final String TAG_SHOOTING_TIME_LEFT = "rhiotTag.shootingTimeLeft";
   static final String TAG_SHOTS_LEFT = "rhiotTag.shotsLeft";
   // Set 4, the information about a hit on the light sensor sent when a sensor reading above a threshold value is detected
   static final String TAG_HIT_SCORE = "rhiotTag.hitScore";
   static final String TAG_HIT_RINGS_OFF_CENTER = "rhiotTag.hitRingsOffCenter";
   // Set 5, the information about the game scores sent on each game end
   static final String GW_LAST_GAME_SCORE = "rhiotTagGW.score";
   static final String GW_LAST_GAME_SCORE_HITS = "rhiotTagGW.hits";
   static final String GW_LAST_GAME_SCORE_TAG_ADDRESS = "rhiotTagGW.scoreTagAddress";
   // Set 6, the information about the high game scores sent on game end when a new high score is achieved
   static final String GW_HIGH_GAME_SCORE = "rhiotTagGW.highScore";
   static final String GW_HIGH_GAME_SCORE_HITS = "rhiotTagGW.highScoreHits";
   static final String GW_HIGH_GAME_SCORE_TAG_ADDRESS = "rhiotTagGame.highScoreTagAddress";

   // REST endpoints
   String CLOUD_PW_PATH = "/cloud-password";
   String TAG_INFO_PATH = "/tags";
   String GAMESM_DIGRAPH_PATH = "/gamesm-digraph";
   String GAMESM_INFO_PATH = "/gamesm";
}

Add constants for the msg metrics and rest endpoints


package net.symphonious.commonjs;

import org.junit.Test;

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

public class CommonJsCompilerTest
{
    private static final String SIMPLE_JAVASCRIPT = "console.log('Hello World!');";

    private final InMemoryModuleLoader moduleLoader = new InMemoryModuleLoader();
    private final CommonJsCompiler compiler = new CommonJsCompiler(moduleLoader);

    @Test
    public void shouldCompileFileWithNoDependencies() throws Exception
    {
        moduleLoader.addModule("main", SIMPLE_JAVASCRIPT);

        assertThat(compiler.compile("main"), is(SIMPLE_JAVASCRIPT));
    }
}

package net.symphonious.commonjs;

import org.junit.Test;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

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

public class CommonJsCompilerTest
{
    private static final String SIMPLE_JAVASCRIPT = "'Hello world!';";

    private final InMemoryModuleLoader moduleLoader = new InMemoryModuleLoader();
    private final CommonJsCompiler compiler = new CommonJsCompiler(moduleLoader);

    @Test
    public void shouldCompileFileWithNoDependencies() throws Exception
    {
        moduleLoader.addModule("main", SIMPLE_JAVASCRIPT);

        assertScriptProducesOutput(compiler.compile("main"), "Hello world!");
    }

    private void assertScriptProducesOutput(final String script, final String expectedOutput) throws ScriptException
    {
        final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        final ScriptEngine javascriptEngine = scriptEngineManager.getEngineByMimeType("text/javascript");
        assertThat(javascriptEngine.eval(script), is(expectedOutput));
    }
}

Move test to asserting the result of the script instead of doing a simple text comparison.


/**
 * Common utility classes.
 */
package com.github.dkorotych.test.utils;

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

/**
 * Common utility classes.
 */
package {{packageName}}.utils;

Fix generated package name Added license information


package com.lasarobotics.library;

import com.lasarobotics.library.util.MathUtil;

import org.junit.Test;

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

/**
 * Basic unit tests
 */
public class MathUtilTest {

    @Test
    public void deadbandTest_ValueLessThanDedband_ReturnsZero(){
        assertThat(MathUtil.deadband(10,5), is(0.0));
    }
    @Test
    public void deadbandTest_GreatLessThanDedband_ReturnsValue(){
        assertThat(MathUtil.deadband(10,11), is(11.0));
    }
}

package com.lasarobotics.library;

import com.lasarobotics.library.util.MathUtil;

import org.junit.Test;

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

/**
 * Basic unit tests
 */
public class MathUtilTest {

    @Test
    public void deadbandTest_ValueLessThanDedband_ReturnsZero(){
        assertThat(MathUtil.deadband(10,5), is(1.0));
    }
    @Test
    public void deadbandTest_GreatLessThanDedband_ReturnsValue(){
        assertThat(MathUtil.deadband(10,11), is(11.0));
    }
}

Break unit tests to verify travis functionality


package com.github.pedrovgs.nox.path;

/**
 * Spiral Path implementation used to place NoxItem objects in a equiangular spiral starting from
 * the center of the view. NoxItem instances in this path will have the same size.
 *
 * @author Pedro Vicente Gomez Sanchez.
 */
class SpiralPath extends Path {

  SpiralPath(PathConfig pathConfig) {
    super(pathConfig);
  }

  @Override public void calculate() {
    int numberOfItems = getPathConfig().getNumberOfElements();
    float centerY =
        (getPathConfig().getViewHeight() / 2) - (getPathConfig().getFirstItemSize() / 2);
    float centerX = (getPathConfig().getViewWidth() / 2) + (getPathConfig().getFirstItemSize() / 2);
    float angle = getPathConfig().getFirstItemSize();
    for (int i = 0; i < numberOfItems; i++) {
      double x = centerX + (angle * i * Math.cos(i));
      setNoxItemLeftPosition(i, (float) x);
      double y = centerY + (angle * i * Math.sin(i));
      setNoxItemTopPosition(i, (float) y);
    }
  }

  protected float getFirstItemLeftPosition() {
    return getPathConfig().getFirstItemMargin();
  }
}

package com.github.pedrovgs.nox.path;

/**
 * Spiral Path implementation used to place NoxItem objects in a equiangular spiral starting from
 * the center of the view. NoxItem instances in this path will have the same size. This path is
 * based on the Archimedean Spiral.
 *
 * @author Pedro Vicente Gomez Sanchez.
 */
class SpiralPath extends Path {

  SpiralPath(PathConfig pathConfig) {
    super(pathConfig);
  }

  @Override public void calculate() {
    int numberOfItems = getPathConfig().getNumberOfElements();
    float centerY =
        (getPathConfig().getViewHeight() / 2) - (getPathConfig().getFirstItemSize() / 2);
    float centerX = (getPathConfig().getViewWidth() / 2) + (getPathConfig().getFirstItemSize() / 2);
    float angle = getPathConfig().getFirstItemSize();
    for (int i = 0; i < numberOfItems; i++) {
      double x = centerX + (angle * i * Math.cos(i));
      setNoxItemLeftPosition(i, (float) x);
      double y = centerY + (angle * i * Math.sin(i));
      setNoxItemTopPosition(i, (float) y);
    }
  }
}

Remove unused method and add some javadoc.


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

/**
 * Given an array of elements, write a method to multiply every value for the rest of elements and
 * return a new array with this values. Can you resolve this problem without use "/" operator?
 */
public class MultiplyArrayElements {
}

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

/**
 * Given an array of elements, write a method to multiply every value for the rest of elements and
 * return a new array with this values. Can you resolve this problem without use "/" operator?
 */
public class MultiplyArrayElements {

  /**
   * Iterative solution to solve this problem. The complexity order of this algorithm is O(N) time
   * and space terms where N is the number of elements in the input array.
   */
  public int[] multiply(int[] input) {
    if (input == null) {
      throw new IllegalArgumentException("You can't pass a null array as input.");
    }
    if (input.length == 0) {
      return input;
    }

    int[] front = new int[input.length];
    int[] rear = new int[input.length];
    int[] output = new int[input.length];

    front[0] = 1;
    rear[input.length - 1] = 1;
    for (int i = 1; i < input.length; i++) {
      front[i] = front[i - 1] * input[i - 1];
    }
    for (int i = input.length - 2; i >= 0; i--) {
      rear[i] = rear[i + 1] * input[i + 1];
    }
    for (int i = 0; i < input.length; i++) {
      output[i] = front[i] * rear[i];
    }
    return output;
  }
}

Add iterative solution to problem 39

Add iterative solution to problem 39


package fuzion24.device.vulnerability.util;

public enum CPUArch {
    ARM("armeabi"),
    ARM7("armeabi-v7a"),
    ARM8("arm64"),
    X86("x86"),
    X64("x64"),
    MIPS("MIPS"),
    ALL("ALL");

    private final String arch;

    public String getArch(){
        return arch;
    }

    CPUArch(String archString){
        arch = archString;
    }

}

package fuzion24.device.vulnerability.util;

public enum CPUArch {
    ARM("armeabi"),
    ARM7("armeabi-v7a"),
    ARM8("arm64-v8a"),
    X86("x86"),
    X64("x64"),
    MIPS("MIPS"),
    ALL("ALL");

    private final String arch;

    public String getArch(){
        return arch;
    }

    CPUArch(String archString){
        arch = archString;
    }

}

Add proper string for arm64 arch

Add proper string for arm64 arch


package sizebay.catalog.client.model;

import java.io.Serializable;
import java.util.Map;
import lombok.*;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
@NoArgsConstructor
public class ProductBasicInformation implements Serializable {

	long id;
	@NonNull String name;
	@NonNull String permalink;
	String genderTheWearWasDesignedFor;
	String coverImage;
	int isShoe;
	@Deprecated int szbMainCategoryId; // FIXME Remove this field after legacy virtual dead
	@Deprecated int szbSubCategoryId; // FIXME Remove this field after legacy virtual dead
	@Deprecated String szbMainCategoryName = null; // FIXME Remove this field after legacy virtual dead
	@Deprecated String szbSubCategoryName = null; // FIXME Remove this field after legacy virtual dead
	String categoryName;
	String modelingName;
	@Deprecated boolean bottomOnly;
	ClothesType clothesType;
	String sizeType;
	Boolean status;
	Product.AgeGroupEnum ageGroup = null;
	Map<String, ModelingSizeMeasures> measures;
	Boolean accessory;
}

package sizebay.catalog.client.model;

import java.io.Serializable;
import java.util.Map;
import lombok.*;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
@NoArgsConstructor
public class ProductBasicInformation implements Serializable {

	long id;
	@NonNull String name;
	@NonNull String permalink;
	String genderTheWearWasDesignedFor;
	String coverImage;
	int isShoe;
	@Deprecated int szbMainCategoryId; // FIXME Remove this field after legacy virtual dead
	@Deprecated int szbSubCategoryId; // FIXME Remove this field after legacy virtual dead
	@Deprecated String szbMainCategoryName = null; // FIXME Remove this field after legacy virtual dead
	@Deprecated String szbSubCategoryName = null; // FIXME Remove this field after legacy virtual dead
	String categoryName;
	String modelingName;
	@Deprecated boolean bottomOnly;
	ClothesType clothesType;
	String sizeType;
	Boolean status;
	Product.AgeGroupEnum ageGroup = null;
	Map<String, ModelingSizeMeasures> measures;
	Boolean accessory;
	int strongBrandId;
	String strongBrandName;
	int strongCategoryTypeId;
	String strongCategoryTypeName;
	int strongCategoryId;
	String strongCategoryName;
	int strongSubcategoryId;
	String strongSubcategoryName;
	int strongModelId;
	String strongModelName;
}

Add strong attributes of Sizebay

Fix: Add strong attributes of Sizebay


/*
    ChargeTime.eu - Java-OCA-OCPP

    MIT License

    Copyright (C) 2016-2018 Thomas Volden <tv@chargetime.eu>

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

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

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
 */
@XmlSchema(
        elementFormDefault = XmlNsForm.QUALIFIED,
        namespace="urn://Ocpp/Cs/2015/10/",
        xmlns={
                @XmlNs(namespaceURI = "urn://Ocpp/Cs/2015/10/", prefix = "ns")
        })
package eu.chargetime.ocpp.model.core;

import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

/*
    ChargeTime.eu - Java-OCA-OCPP

    MIT License

    Copyright (C) 2016-2018 Thomas Volden <tv@chargetime.eu>

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

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

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
 */
@XmlSchema(elementFormDefault = XmlNsForm.QUALIFIED, namespace = "urn://Ocpp/Cs/2015/10/")
package eu.chargetime.ocpp.model.core;

import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

Modify package info with the default namespace


package com.health.input;

import java.util.List;

import com.health.Record;
import com.health.Table;

<<<<<<< HEAD
/**
 * A class for functions with can be called on all input formats.
 *
 */
=======
>>>>>>> made a special class for input functions as ignore last
public class InputFunctions {

  /**
   * Deletes the last x lines which are not needed as specified by the user.
   *
   * @param table
   *          Gets the table with the redundant lines.
   * @param config
   *          Gets the InputDescriptor which is used to create the original file.
   * @return the new table with deleted lines.
   */
  public static Table deleteLastLines(final Table table, final InputDescriptor config) {

    int deletions = config.getIgnoreLast();
    int size = table.size();
    List<Record> tab = table.getRecords();
    while (deletions > 0) {
      table.removeRecord(tab.get(size));
      size--;
      deletions--;
    }
    return table;
  }

}

package com.health.input;

import java.util.List;

import com.health.Record;
import com.health.Table;

/**
 * A class for functions with can be called on all input formats.
 */
public class InputFunctions {

    /**
     * Deletes the last x lines which are not needed as specified by the user.
     *
     * @param table
     *            Gets the table with the redundant lines.
     * @param config
     *            Gets the InputDescriptor which is used to create the original
     *            file.
     * @return the new table with deleted lines.
     */
    public static Table deleteLastLines(final Table table, final InputDescriptor config) {
        int deletions = config.getIgnoreLast();
        int size = table.size();
        List<Record> tab = table.getRecords();

        while (deletions > 0) {
            table.removeRecord(tab.get(size));
            size--;
            deletions--;
        }

        return table;
    }
}

Revert "xls Parser fix for ignore last lines"


/*
 * 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.lucene;

/** Lucene's package information, including version. * */
public final class LucenePackage {

  private LucenePackage() {} // can't construct

  /** Return Lucene's package, including version information. */
  public static Package get() {
    return LucenePackage.class.getPackage();
  }
}

/*
 * 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.lucene;

/** Lucene's package information, including version. */
public final class LucenePackage {

  private LucenePackage() {} // can't construct

  /** Return Lucene's package, including version information. */
  public static Package get() {
    return LucenePackage.class.getPackage();
  }
}

Correct extra * in javadoc.

Correct extra * in javadoc.


package uk.ac.ebi.biosamples.neo;

import java.util.Collection;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.stereotype.Component;

import uk.ac.ebi.biosamples.messages.threaded.MessageBuffer;
import uk.ac.ebi.biosamples.neo.model.NeoSample;
import uk.ac.ebi.biosamples.neo.repo.NeoSampleRepository;

@Component
public class NeoMessageBuffer extends MessageBuffer<NeoSample, NeoSampleRepository> {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	private Random random = new Random();

	public NeoMessageBuffer(NeoSampleRepository repository) {
		super(repository);
	}

	@Override
	protected void save(NeoSampleRepository repository, Collection<NeoSample> samples) {
		int retryCount = 0;
		while (retryCount < 100) {
			try {
				//this will have its own transaction
				repository.save(samples);
				return;
			} catch (ConcurrencyFailureException e) {
				retryCount += 1 ;
				log.info("Retrying due to transient exception. Attempt number "+retryCount);
				try {
					Thread.sleep(random.nextInt(400)+100);
				} catch (InterruptedException e1) {
					//do nothing
				}
			}
		}
		log.warn("Unable to save within "+retryCount+" retries");
	}

}

package uk.ac.ebi.biosamples.neo;

import java.util.Collection;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.stereotype.Component;

import uk.ac.ebi.biosamples.messages.threaded.MessageBuffer;
import uk.ac.ebi.biosamples.neo.model.NeoSample;
import uk.ac.ebi.biosamples.neo.repo.NeoSampleRepository;

@Component
public class NeoMessageBuffer extends MessageBuffer<NeoSample, NeoSampleRepository> {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	private Random random = new Random();

	public NeoMessageBuffer(NeoSampleRepository repository) {
		super(repository);
	}

	@Override
	protected void save(NeoSampleRepository repository, Collection<NeoSample> samples) {
		int retryCount = 0;
		while (retryCount < 100) {
			try {
				//this will have its own transaction
				repository.save(samples);
				return;
			} catch (ConcurrencyFailureException e) {
				retryCount += 1 ;
				log.warn("Retrying due to transient exception. Attempt number "+retryCount);
				try {
					Thread.sleep(random.nextInt(400)+100);
				} catch (InterruptedException e1) {
					//do nothing
				}
			}
		}
		throw new RuntimeException("Unable to save within "+retryCount+" retries");
	}

}

Tweak to error message propagation

Tweak to error message propagation


package io.doist.recyclerviewext.flippers;

import android.support.v4.view.ViewCompat;
import android.view.View;

/**
 * Flips between views with a common ancestor using a {@link FlipperAnimator}.
 */
public class Flipper {
    private FlipperAnimator mFlipperAnimator = new DefaultFlipperAnimator();

    public FlipperAnimator getFlipperAnimator() {
        return mFlipperAnimator;
    }

    public void setFlipperAnimator(FlipperAnimator flipperAnimator) {
        mFlipperAnimator = flipperAnimator;
    }

    public void replace(View outView, View inView) {
        replaceInternal(outView, inView, true);
    }

    public void replaceNoAnimation(View outView, View inView) {
        replaceInternal(outView, inView, false);
    }

    protected void replaceInternal(View outView, View inView, boolean animate) {
        if (animate && mFlipperAnimator != null && ViewCompat.isLaidOut(inView)) {
            mFlipperAnimator.animateFlip(outView, inView);
        } else {
            if (mFlipperAnimator != null && mFlipperAnimator.isAnimating()) {
                outView.animate().cancel();
                inView.animate().cancel();
            }
            outView.setVisibility(View.GONE);
            inView.setVisibility(View.VISIBLE);
        }
    }
}

package io.doist.recyclerviewext.flippers;

import android.support.v4.view.ViewCompat;
import android.view.View;

/**
 * Flips between views with a common ancestor using a {@link FlipperAnimator}.
 */
public class Flipper {
    private FlipperAnimator mFlipperAnimator = new DefaultFlipperAnimator();

    public FlipperAnimator getFlipperAnimator() {
        return mFlipperAnimator;
    }

    public void setFlipperAnimator(FlipperAnimator flipperAnimator) {
        mFlipperAnimator = flipperAnimator;
    }

    public void replace(View outView, View inView) {
        replaceInternal(outView, inView, true);
    }

    public void replaceNoAnimation(View outView, View inView) {
        replaceInternal(outView, inView, false);
    }

    protected void replaceInternal(View outView, View inView, boolean animate) {
        if (animate && mFlipperAnimator != null && ViewCompat.isLaidOut(outView)) {
            mFlipperAnimator.animateFlip(outView, inView);
        } else {
            if (mFlipperAnimator != null && mFlipperAnimator.isAnimating()) {
                outView.animate().cancel();
                inView.animate().cancel();
            }
            outView.setVisibility(View.GONE);
            inView.setVisibility(View.VISIBLE);
        }
    }
}

Fix anchor used to check if animations should run


package org.nuxeo.drive.service.impl;

import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.nuxeo.ecm.core.api.IdRef;

public class RootDefinitionsHelper {

    public static Map<String, Set<IdRef>> parseRootDefinitions(String rootDefinitions) {
        Map<String, Set<IdRef>> lastActiveRootRefs = new LinkedHashMap<String, Set<IdRef>>();
        if (rootDefinitions != null) {
            String[] rootDefinitionComponents = StringUtils.split(
                    rootDefinitions, ",");
            for (String rootDefinition : rootDefinitionComponents) {
                String[] rootComponents = StringUtils.split(rootDefinition, ":");
                String repoName = rootComponents[0].trim();
                Set<IdRef> refs = lastActiveRootRefs.get(repoName);
                if (refs == null) {
                    refs = new HashSet<IdRef>();
                    lastActiveRootRefs.put(repoName, refs);
                }
                refs.add(new IdRef(rootComponents[1].trim()));
            }
        }
        return lastActiveRootRefs;
    }

}

package org.nuxeo.drive.service.impl;

import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.nuxeo.ecm.core.api.IdRef;

public class RootDefinitionsHelper {

    private RootDefinitionsHelper() {
        // Utility class
    }

    public static Map<String, Set<IdRef>> parseRootDefinitions(
            String rootDefinitions) {
        Map<String, Set<IdRef>> lastActiveRootRefs = new LinkedHashMap<String, Set<IdRef>>();
        if (rootDefinitions != null) {
            String[] rootDefinitionComponents = StringUtils.split(
                    rootDefinitions, ",");
            for (String rootDefinition : rootDefinitionComponents) {
                String[] rootComponents = StringUtils.split(rootDefinition, ":");
                String repoName = rootComponents[0].trim();
                Set<IdRef> refs = lastActiveRootRefs.get(repoName);
                if (refs == null) {
                    refs = new HashSet<IdRef>();
                    lastActiveRootRefs.put(repoName, refs);
                }
                refs.add(new IdRef(rootComponents[1].trim()));
            }
        }
        return lastActiveRootRefs;
    }

}

NXP-11577: Fix Sonar Major violation: Hide Utility Class Constructor


package com.innovattic.logeverywhere;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Jelle on 6-7-2015.
 */
public class MainActivity extends Activity
{

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

	@OnClick(R.id.start_service)
	protected void startService()
	{
		startService(new Intent(this, LogService.class));
	}

	@OnClick(R.id.stop_service)
	protected void stopService()
	{
		stopService(new Intent(this, LogService.class));
	}

}

package com.innovattic.logeverywhere;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Jelle on 6-7-2015.
 */
public class MainActivity extends Activity
{

	private static final String TAG = MainActivity.class.getSimpleName();

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

//	@OnClick(R.id.grant_permission)
//	protected void grantPermission()
//	{
//		try {
//			final java.lang.Process process = Runtime.getRuntime().exec(
//					"pm grant com.innovattic.logeverywhere android.permission.READ_LOGS"
//			);
//			final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
//			String line = "";
//			while ((line = reader.readLine()) != null) {
//				Toast.makeText(this, line, Toast.LENGTH_SHORT).show();
//				Log.e(TAG, line);
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}
//
	@OnClick(R.id.start_service)
	protected void startService()
	{
		startService(new Intent(this, LogService.class));
	}

	@OnClick(R.id.stop_service)
	protected void stopService()
	{
		stopService(new Intent(this, LogService.class));
	}

}

Add (failed) attempt to grant ourselves READ_LOGS permission


package com.marverenic.music.ui.settings;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;

import com.marverenic.music.R;
import com.marverenic.music.ui.BaseActivity;

public class SettingsActivity extends BaseActivity {

    public static Intent newIntent(Context context) {
        return new Intent(context, SettingsActivity.class);
    }

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        if (getSupportActionBar() != null
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getSupportActionBar()
                    .setElevation(getResources().getDimension(R.dimen.header_elevation));
        }

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.pref_fragment_container, new PreferenceFragment())
                    .commit();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                if (!getSupportFragmentManager().popBackStackImmediate()) {
                    super.onOptionsItemSelected(item);
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onBackPressed() {
        if (!getSupportFragmentManager().popBackStackImmediate()) {
            super.onBackPressed();
        }
    }
}

package com.marverenic.music.ui.settings;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBar;

import com.marverenic.music.R;
import com.marverenic.music.ui.BaseActivity;

public class SettingsActivity extends BaseActivity {

    public static Intent newIntent(Context context) {
        return new Intent(context, SettingsActivity.class);
    }

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        setSupportActionBar(findViewById(R.id.toolbar));
        ActionBar toolbar = getSupportActionBar();
        toolbar.setDisplayShowHomeEnabled(true);
        toolbar.setDisplayHomeAsUpEnabled(true);
        toolbar.setHomeButtonEnabled(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            toolbar.setElevation(getResources().getDimension(R.dimen.header_elevation));
        }

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.pref_fragment_container, new PreferenceFragment())
                    .commit();
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        if (!getSupportFragmentManager().popBackStackImmediate()) {
            finish();
        }
        return true;
    }

    @Override
    public void onBackPressed() {
        if (!getSupportFragmentManager().popBackStackImmediate()) {
            super.onBackPressed();
        }
    }
}

Fix missing up button on settings page

Fix missing up button on settings page


package org.ovirt.engine.core.bll.storage.repoimage;

import java.util.List;

import org.ovirt.engine.core.bll.QueriesCommandBase;
import org.ovirt.engine.core.bll.storage.domain.IsoDomainListSyncronizer;
import org.ovirt.engine.core.common.businessentities.storage.RepoImage;
import org.ovirt.engine.core.common.queries.GetImagesListParametersBase;
import org.ovirt.engine.core.compat.Guid;

public abstract class GetImagesListQueryBase<P extends GetImagesListParametersBase> extends QueriesCommandBase<P> {

    public GetImagesListQueryBase(P parameters) {
        super(parameters);
    }

    @Override
    protected void executeQueryCommand() {
        // Fetch all the Iso files of a given type for storage pool with active storage domain of this domain Id.
        getQueryReturnValue().setReturnValue(getUserRequestForStorageDomainRepoFileList());
    }

    /**
     * @return The storage domain to get the images from
     */
    protected abstract Guid getStorageDomainIdForQuery();

    protected List<RepoImage> getUserRequestForStorageDomainRepoFileList() {
        return IsoDomainListSyncronizer.getInstance().getUserRequestForStorageDomainRepoFileList
                (getStorageDomainIdForQuery(), getParameters().getImageType(), getParameters().getForceRefresh());
    }
}

package org.ovirt.engine.core.bll.storage.repoimage;

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

import org.ovirt.engine.core.bll.QueriesCommandBase;
import org.ovirt.engine.core.bll.storage.domain.IsoDomainListSyncronizer;
import org.ovirt.engine.core.common.businessentities.storage.RepoImage;
import org.ovirt.engine.core.common.queries.GetImagesListParametersBase;
import org.ovirt.engine.core.compat.Guid;

public abstract class GetImagesListQueryBase<P extends GetImagesListParametersBase> extends QueriesCommandBase<P> {

    public GetImagesListQueryBase(P parameters) {
        super(parameters);
    }

    @Override
    protected void executeQueryCommand() {
        // Fetch all the Iso files of a given type for storage pool with active storage domain of this domain Id.
        getQueryReturnValue().setReturnValue(getUserRequestForStorageDomainRepoFileList());
    }

    /**
     * @return The storage domain to get the images from
     */
    protected abstract Guid getStorageDomainIdForQuery();

    protected List<RepoImage> getUserRequestForStorageDomainRepoFileList() {
        Guid storageDomainId = getStorageDomainIdForQuery();
        if (Guid.Empty.equals(storageDomainId)) {
            return new ArrayList<>();
        }

        return IsoDomainListSyncronizer.getInstance().getUserRequestForStorageDomainRepoFileList
                (storageDomainId, getParameters().getImageType(), getParameters().getForceRefresh());
    }
}

Fix ISO Domain List refresh NPE

core: Fix ISO Domain List refresh NPE

Fix ISO DomainList refresh NPE when no ISO domain
is configured.

Change-Id: Ied2b1490d8f66bb40f6f456d2d39bb05120e97d3
Bug-Url: https://bugzilla.redhat.com/1291202
Signed-off-by: Marek Libra <e8e92ef0eef30bdb5bafbacaf4ac8261fffd12ff@redhat.com>


/**
 *
 */
package org.corpus_tools.atomic.api.commands;

import org.corpus_tools.atomic.api.editors.DocumentGraphEditor;
import org.corpus_tools.salt.common.SDocumentGraph;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PlatformUI;

/**
 * TODO Description
 *
 * @author Stephan Druskat <mail@sdruskat.net>
 *
 */
public class DocumentGraphAwareHandler extends AbstractHandler {

	private final SDocumentGraph graph;

	/**
	 *
	 */
	public DocumentGraphAwareHandler() {
		IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
		if (editor instanceof DocumentGraphEditor) {
			graph = ((DocumentGraphEditor) editor).getGraph();
		}
		else {
			graph = null;
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
	 */
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * @return the graph
	 */
	public final SDocumentGraph getGraph() {
		return graph;
	}

}

/**
 *
 */
package org.corpus_tools.atomic.api.commands;

import org.corpus_tools.atomic.api.editors.DocumentGraphEditor;
import org.corpus_tools.salt.common.SDocumentGraph;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PlatformUI;

/**
 * TODO Description
 *
 * @author Stephan Druskat <mail@sdruskat.net>
 *
 */
public abstract class DocumentGraphAwareHandler extends AbstractHandler {

	private final SDocumentGraph graph;

	/**
	 *
	 */
	public DocumentGraphAwareHandler() {
		IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
		if (editor instanceof DocumentGraphEditor) {
			graph = ((DocumentGraphEditor) editor).getGraph();
		}
		else {
			graph = null;
		}
	}

	/**
	 * @return the graph
	 */
	public final SDocumentGraph getGraph() {
		return graph;
	}
}

Add API for handler that know the SDocumentGraph of the editor


package com.kiselev.reflection.ui.bytecode.agent;

import com.kiselev.reflection.ui.bytecode.holder.ByteCodeHolder;

import java.lang.instrument.Instrumentation;
import java.util.List;

/**
 * Created by Vadim Kiselev on 6/12/2017.
 */
public class Agent {

    public static void agentmain(String args, Instrumentation instrumentation) {
        try {
            instrumentation.addTransformer(new Transformer(), true);
            Class[] allLoadedClasses = instrumentation.getAllLoadedClasses();

            for (Class loadedClass : allLoadedClasses) {
                if (!loadedClass.isArray()) {
                    instrumentation.retransformClasses(loadedClass);
                }
            }

        } catch (Exception exception) {
            // sin
        }
    }
}

package com.kiselev.reflection.ui.bytecode.agent;

import java.lang.instrument.Instrumentation;

/**
 * Created by Vadim Kiselev on 6/12/2017.
 */
public class Agent {

    public static void agentmain(String args, Instrumentation instrumentation) {
        try {
            instrumentation.addTransformer(new Transformer(), true);
            Class[] allLoadedClasses = instrumentation.getAllLoadedClasses();

            for (Class loadedClass : allLoadedClasses) {
                if (!loadedClass.isArray()) {
                    instrumentation.retransformClasses(loadedClass);
                }
            }
        } catch (Exception exception) {
            // sin
        }
    }
}

Fix agent class after merging

Fix agent class after merging


/*
 * 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.amber.server;

/**
 * An OAuth Server provides the functionality required to deliver OAuth Provider
 * functionality. It can be exposed by wrapping it in an HTTP layer, e.g. that
 * provided by the Servlet Spec or perhaps directly exposed by a custom HTTP
 * server.
 *
 * @version $Id$
 */
public abstract class OAuthServer implements OAuthnServer, OAuthzServer {

	/**
	 * @return access storage
	 */
	protected abstract AccessStorage getAccessStorage();

	/**
	 * @return consumer storage
	 */
	protected abstract ConsumerStorage getConsumerStorage();

	/**
	 * @return token storage
	 */
	protected abstract TokenStorage getTokenStorage();

}

/*
 * 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.amber.server;

/**
 * An OAuth Server provides the functionality required to deliver OAuth Provider
 * functionality. It can be exposed by wrapping it in an HTTP layer, e.g. that
 * provided by the Servlet Spec or perhaps directly exposed by a custom HTTP
 * server.
 *
 * @version $Id$
 */
public abstract class OAuthServer implements OAuthnServer, OAuthzServer {

}

Revert previous commit adding storage methods

git-svn-id: 522c0d53943162a6437d919c1900af0a20491c0c@962477 13f79535-47bb-0310-9956-ffa450edef68


/*
 * 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.jmeter.testelement.property;

import java.util.Collection;
import java.util.Iterator;

public class PropertyIteratorImpl implements PropertyIterator {

    Iterator iter;

    public PropertyIteratorImpl(Collection value) {
        iter = value.iterator();
    }

    public PropertyIteratorImpl() {
    }

    public void setCollection(Collection value) {
        iter = value.iterator();
    }

    public boolean hasNext() {
        return iter.hasNext();
    }

    public JMeterProperty next() {
        return (JMeterProperty) iter.next();
    }

    /**
     * @see org.apache.jmeter.testelement.property.PropertyIterator#remove()
     */
    public void remove() {
        iter.remove();
    }

}

/*
 * 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.jmeter.testelement.property;

import java.util.Collection;
import java.util.Iterator;

public class PropertyIteratorImpl implements PropertyIterator {

    private final Iterator<JMeterProperty> iter;

    public PropertyIteratorImpl(Collection<JMeterProperty> value) {
        iter = value.iterator();
    }

    /** {@inheritDoc} */
    public boolean hasNext() {
        return iter.hasNext();
    }

    /** {@inheritDoc} */
    public JMeterProperty next() {
        return iter.next();
    }

    /** {@inheritDoc} */
    public void remove() {
        iter.remove();
    }

}

Tidy types
Make class final and remove unused ctor/setter

git-svn-id: https://svn.apache.org/repos/asf/jakarta/jmeter/trunk@804702 13f79535-47bb-0310-9956-ffa450edef68

Former-commit-id: a37b5f7b7d8cc52c9947bc15230d1a7f0e972d06


package com.oneandone.snmpman;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.kohsuke.args4j.Option;

import java.io.File;

/** The command-line options for the {@link Snmpman} application. */
@Slf4j
public final class CommandLineOptions {

    /** The {@code Snmpman} configuration. */
    @Option(name = "-c", aliases = "--configuration", usage = "the path to the configuration XML", required = true)
    @Getter private File configurationFile;

    /** Flag that defines that a help message should be displayed when {@code true}. */
    @Option(name = "-h", aliases = "--help", usage = "print the help message", help = true)
    @Getter private boolean showHelp = false;
}

package com.oneandone.snmpman;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.kohsuke.args4j.Option;

import java.io.File;

/** The command-line options for the {@link Snmpman} application. */
@Slf4j
public final class CommandLineOptions {

    /** The {@code Snmpman} configuration. */
    @Option(name = "-c", aliases = "--configuration", usage = "the path to the configuration YAML", required = true)
    @Getter private File configurationFile;

    /** Flag that defines that a help message should be displayed when {@code true}. */
    @Option(name = "-h", aliases = "--help", usage = "print the help message", help = true)
    @Getter private boolean showHelp = false;
}

Fix typo -> config is YAML now

Fix typo -> config is YAML now


package org.callimachusproject.webdriver.pages;

import org.callimachusproject.webdriver.helpers.WebBrowserDriver;
import org.openqa.selenium.By;

public class DigestUserEdit extends CalliPage {

	public DigestUserEdit(WebBrowserDriver driver) {
		super(driver);
	}

	public FileUploadForm openPhotoUpload() {
		driver.click(By.cssSelector("#photo label.control-label a"));
		driver.waitForScript();
		driver.focusInFrame("photo");
		driver.waitForScript();
		final DigestUserEdit edit = this;
		return new FileUploadForm(driver) {
			@Override
			public DigestUserEdit uploadAs(String fileName) {
				driver.click(By.id("upload"));
				driver.focusInFrame("photo", "save-as___");
				driver.type(By.id("label"), fileName);
				driver.focusInFrame("photo");
				driver.click(By.xpath("(//button[@type='button'])[2]"));
				return edit;
			}
		};
	}

	public CalliPage save() {
		driver.click(By.id("save"));
		return page();
	}

}

package org.callimachusproject.webdriver.pages;

import org.callimachusproject.webdriver.helpers.WebBrowserDriver;
import org.openqa.selenium.By;

public class DigestUserEdit extends CalliPage {

	public DigestUserEdit(WebBrowserDriver driver) {
		super(driver);
	}

	public FileUploadForm openPhotoUpload() {
		driver.click(By.cssSelector("#photo label.control-label a"));
		driver.waitForScript();
		driver.focusInFrame("photo");
		driver.waitForScript();
		final DigestUserEdit edit = this;
		return new FileUploadForm(driver) {
			@Override
			public DigestUserEdit uploadAs(String fileName) {
				driver.click(By.id("upload"));
				driver.focusInFrame("photo", "save-as___");
				driver.type(By.id("label"), fileName);
				driver.focusInFrame("photo");
				driver.click(By.xpath("(//button[@type='button'])[2]"));
				return edit;
			}
		};
	}

	public CalliPage save() {
		driver.focusInTopWindow();
		driver.click(By.id("save"));
		return page();
	}

}

Switch focus back to top window

Switch focus back to top window


package roycurtis.signshopexport.json;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;

public class Exclusions implements ExclusionStrategy
{
    @Override
    public boolean shouldSkipField(FieldAttributes f)
    {
        String name = f.getName();

        return
            // Ignore dynamic CraftBukkit handle field
            name.equalsIgnoreCase("handle")
            // Ignore book page contents
            || name.equalsIgnoreCase("pages")
            // Ignore unsupported tags
            || name.equalsIgnoreCase("unhandledTags")
            // Ignore redundant data object
            || name.equalsIgnoreCase("data")
            // Ignore hide flags
            || name.equalsIgnoreCase("hideFlag")
            // Ignore shield patterns
            || name.equalsIgnoreCase("blockEntityTag");
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz)
    {
        String name = clazz.getSimpleName();

        if ( name.equalsIgnoreCase("ItemStack") )
        if ( clazz.getTypeName().startsWith("net.minecraft.server") )
            return true;

        return name.equalsIgnoreCase("ChatComponentText");
    }
}

package roycurtis.signshopexport.json;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;

public class Exclusions implements ExclusionStrategy
{
    @Override
    public boolean shouldSkipField(FieldAttributes f)
    {
        String name = f.getName();

        return
            // Ignore dynamic CraftBukkit handle field
            name.equalsIgnoreCase("handle")
            // Ignore book page contents
            || name.equalsIgnoreCase("pages")
            // Ignore unsupported tags
            || name.equalsIgnoreCase("unhandledTags")
            // Ignore redundant data object
            || name.equalsIgnoreCase("data")
            // Ignore hide flags
            || name.equalsIgnoreCase("hideFlag")
            // Ignore skull profiles
            || name.equalsIgnoreCase("profile")
            // Ignore shield patterns
            || name.equalsIgnoreCase("blockEntityTag");
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz)
    {
        String name = clazz.getSimpleName();

        if ( name.equalsIgnoreCase("ItemStack") )
        if ( clazz.getTypeName().startsWith("net.minecraft.server") )
            return true;

        return name.equalsIgnoreCase("ChatComponentText");
    }
}

Exclude skull profile tags from export

Exclude skull profile tags from export


/*
 * 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.karaf.util;

import java.io.Closeable;
import java.io.IOException;

public class StreamUtils {

    private StreamUtils() {
    }

    public static void close(Closeable... closeables) {
        for (Closeable c : closeables) {
            try {
                c.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }

}

/*
 * 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.karaf.util;

import java.io.Closeable;
import java.io.IOException;

public class StreamUtils {

    private StreamUtils() {
    }

    public static void close(Closeable... closeables) {
        for (Closeable c : closeables) {
            try {
            	if (c != null) {
            		c.close();
            	}
            } catch (IOException e) {
                // Ignore
            }
        }
    }

}

Make sure StreamUtil.close also works for null

git-svn-id: 71d8a689455c5fbb0f077bc40adcfc391e14cb9d@1541134 13f79535-47bb-0310-9956-ffa450edef68


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

package org.springframework.core.testfixture.aot.generator.visibility;

import org.springframework.core.ResolvableType;

public class PublicFactoryBean<T> {

	private final Class<T> type;

	public PublicFactoryBean(Class<T> type) {
		this.type = type;
	}

	public static PublicFactoryBean<ProtectedType> protectedTypeFactoryBean() {
		return new PublicFactoryBean<>(ProtectedType.class);
	}

	public static ResolvableType resolveToProtectedGenericParameter() {
		return ResolvableType.forClassWithGenerics(PublicFactoryBean.class, ProtectedType.class);
	}

}

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

package org.springframework.core.testfixture.aot.generator.visibility;

import org.springframework.core.ResolvableType;

public class PublicFactoryBean<T> {

	PublicFactoryBean(Class<T> type) {
	}

	public static PublicFactoryBean<ProtectedType> protectedTypeFactoryBean() {
		return new PublicFactoryBean<>(ProtectedType.class);
	}

	public static ResolvableType resolveToProtectedGenericParameter() {
		return ResolvableType.forClassWithGenerics(PublicFactoryBean.class, ProtectedType.class);
	}

}

Clean up warnings in test fixture

Clean up warnings in test fixture


package fr.synchrotron.soleil.ica.ci.lib.mongodb.domainobjects.project;

import fr.synchrotron.soleil.ica.ci.lib.mongodb.domainobjects.artifact.DeveloperDocument;

import java.util.List;

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

    private String org;

    private String name;

    private List<DeveloperDocument> developers;

    private String description;

    private String scmConnection;

    private String language;

    public String getOrg() {
        return org;
    }

    public void setOrg(String org) {
        this.org = org;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<DeveloperDocument> getDevelopers() {
        return developers;
    }

    public void setDevelopers(List<DeveloperDocument> developers) {
        this.developers = developers;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getScmConnection() {
        return scmConnection;
    }

    public void setScmConnection(String scmConnection) {
        this.scmConnection = scmConnection;
    }

    public MavenProjectInfo getMaven() {
        return maven;
    }

    public void setMaven(MavenProjectInfo maven) {
        this.maven = maven;
    }
}

package fr.synchrotron.soleil.ica.ci.lib.mongodb.domainobjects.project;

import fr.synchrotron.soleil.ica.ci.lib.mongodb.domainobjects.artifact.DeveloperDocument;

import java.util.List;

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

    private String org;

    private String name;

    private List<DeveloperDocument> developers;

    private String description;

    private String scmConnection;

    private String language;

    public String getOrg() {
        return org;
    }

    public void setOrg(String org) {
        this.org = org;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<DeveloperDocument> getDevelopers() {
        return developers;
    }

    public void setDevelopers(List<DeveloperDocument> developers) {
        this.developers = developers;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getScmConnection() {
        return scmConnection;
    }

    public void setScmConnection(String scmConnection) {
        this.scmConnection = scmConnection;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }
}

Change Elements from Import And Export

Change Elements from Import And Export


package com.nirima.jenkins.plugins.docker;

import hudson.slaves.OfflineCause;

/**
 * @author Kanstantsin Shautsou
 */
public class DockerOfflineCause extends OfflineCause {
    @Override
    public String toString() {
        return "Shutting down Docker";
    }
}

package com.nirima.jenkins.plugins.docker;

import hudson.slaves.OfflineCause;

/**
 * @author Kanstantsin Shautsou
 */
public class DockerOfflineCause extends OfflineCause {
    @Override
    public String toString() {
        return "Shutting down Docker container";
    }
}

Clarify the offline cause text.

Clarify the offline cause text.

We are shutting down the container, not the entire docker engine.


package com.sandbox.runtime.js.serializers;

import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.ScriptEngine;
import javax.script.ScriptException;

/**
 * Created by nickhoughton on 16/07/2015.
 */
public class NashornSerializer {

    private static final Logger logger = LoggerFactory.getLogger(NashornSerializer.class);

    private ScriptObjectMirror jsonParser;

    public NashornSerializer(ScriptObjectMirror jsonParser) {
        this.jsonParser = jsonParser;
    }

    private static NashornSerializer instance = null;
    public static NashornSerializer instance(){
        if(instance == null){
            try {
                ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(new String[]{"--no-java"});
                instance = new NashornSerializer((ScriptObjectMirror) engine.eval("JSON"));
            } catch (ScriptException e) {
                logger.error("Error starting nashorn serialiser!", e);
            }
        }
        return instance;
    }

    public String serialize(Object value){
        Object result = jsonParser.callMember("stringify", value, null, 2);
        return (String) result;
    }

}

package com.sandbox.runtime.js.serializers;

import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.ScriptEngine;
import javax.script.ScriptException;

/**
 * Created by nickhoughton on 16/07/2015.
 */
public class NashornSerializer {

    private static final Logger logger = LoggerFactory.getLogger(NashornSerializer.class);

    private ScriptObjectMirror jsonParser;

    public NashornSerializer(ScriptObjectMirror jsonParser) {
        this.jsonParser = jsonParser;
    }

    private static NashornSerializer instance = null;
    public static NashornSerializer instance(){
        if(instance == null){
            try {
                ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(new String[]{"--no-java"});
                instance = new NashornSerializer((ScriptObjectMirror) engine.eval("JSON"));
            } catch (ScriptException e) {
                logger.error("Error starting nashorn serialiser!", e);
            }
        }
        return instance;
    }

    public String serialize(Object value){
        Object result = jsonParser.callMember("stringify", value, null, 2);
        if(!(result instanceof String)){
            result = "null";
            logger.warn("Serialized unsupported object, returning null..");
        }
        return (String) result;
    }

}

Return null for undefined values.

Fix: Return null for undefined values.


package org.webik.storm.StormUnit.trident.mock;

import java.util.LinkedList;
import java.util.List;

import storm.trident.operation.TridentCollector;

public class MockCollector implements TridentCollector{

	protected LinkedList<List<Object>> tuplesList = new LinkedList<List<Object>>();

	protected Throwable lastError = null;

	public void emit( List<Object> values ) {
		tuplesList.add( values );

	}

	public void reportError(Throwable t) {
		lastError = t;
	}

	public List<Object> getEmmitedTuple( int offset ){
		return tuplesList.get( offset );
	}

	public List<Object> getEmmitedTuple(){
		return tuplesList.getLast();
	}

	public boolean assertTuplesListSize( int expectedSize ){
		return tuplesList.size() == expectedSize;
	}

	public boolean assertTuple( List<Object> expectedTuple ){
		return getEmmitedTuple().equals( expectedTuple );
	}

	public boolean assertTuple( int offset, List<Object> expectedTuple ){
		return getEmmitedTuple(offset).equals( expectedTuple );
	}

	public boolean assertError(){
		return lastError != null;
	}

	public Throwable getLastError(){
		return lastError;
	}
}

package org.webik.storm.StormUnit.trident.mock;

import java.util.LinkedList;
import java.util.List;

import storm.trident.operation.TridentCollector;

public class MockCollector implements TridentCollector{

	protected LinkedList<List<Object>> tuplesList = new LinkedList<List<Object>>();

	protected Throwable lastError = null;

	public void emit( List<Object> values ) {
		tuplesList.add( values );

	}

	public void reportError(Throwable t) {
		lastError = t;
	}

	public List<Object> getEmmitedTuple( int offset ){
		if( tuplesList.isEmpty() ){
			return null;
		}

		return tuplesList.get( offset );
	}

	public List<Object> getEmmitedTuple(){

		if( tuplesList.isEmpty() ){
			return null;
		}

		return tuplesList.getLast();
	}

	public boolean assertTuplesListSize( int expectedSize ){
		return tuplesList.size() == expectedSize;
	}

	public boolean assertTuple( List<Object> expectedTuple ){
		List<Object> tuple = getEmmitedTuple();

		if( tuple == null ){
			return false;
		}

		return tuple.equals( expectedTuple );
	}

	public boolean assertTuple( int offset, List<Object> expectedTuple ){
		List<Object> tuple = getEmmitedTuple( offset );

		if( tuple == null ){
			return false;
		}

		return tuple.equals( expectedTuple );
	}

	public boolean assertError(){
		return lastError != null;
	}

	public Throwable getLastError(){
		return lastError;
	}
}

Check if tuple list is empty

Check if tuple list is empty


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

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.context.annotation.Import;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({ ZipkinServerConfiguration.class })
public @interface EnableZipkinServer {

}

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

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.context.annotation.Import;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({ ZipkinServerConfiguration.class, ZipkinQueryApiV1.class })
public @interface EnableZipkinServer {

}

Add @RestController to default server config


/*
 * 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.camel.test.infra.aws2.services;

public class AWSSQSLocalContainerService extends AWSLocalContainerService {

    public AWSSQSLocalContainerService() {
        super("localstack/localstack:0.12.5", Service.SQS);
    }
}

/*
 * 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.camel.test.infra.aws2.services;

public class AWSSQSLocalContainerService extends AWSLocalContainerService {

    public AWSSQSLocalContainerService() {
        super("localstack/localstack:0.12.6", Service.SQS);
    }
}

Upgrade Localstack image to 0.12.6 for SQS too


package com.example.android.waitlist.data;

// TODO (1) extend the SQLiteOpenHelper class
public class WaitlistDbHelper {

    // TODO (2) Create a static final String called DATABASE_NAME and set it to "waitlist.db"

    // TODO (3) Create a static final int called DATABASE_VERSION and set it to 1

    // TODO (4) Create a Constructor that takes a context and calls the parent constructor

    // TODO (5) Override the onCreate method

        // TODO (6) Inside, create an String query called SQL_CREATE_WAITLIST_TABLE that will create the table

        // TODO (7) Execute the query by calling execSQL on sqLiteDatabase and pass the string query SQL_CREATE_WAITLIST_TABLE

    // TODO (8) Override the onUpgrade method

        // TODO (9) Inside, execute a drop table query, and then call onCreate to re-create it

}

package com.example.android.waitlist.data;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.android.waitlist.data.WaitlistContract.WaitlistEntry;

// TODO (1) extend the SQLiteOpenHelper class
public class WaitlistDbHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "waitlist.db";

    public static final int DATABASE_VERSION = 1;

    public WaitlistDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String SQL_CREATE_WAITLIST_TABLE= "CREATE TABLE " +
                WaitlistEntry.TABLE_NAME + "(" +
                WaitlistEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                WaitlistEntry.COLUMN_GUEST_NAME + " TEXT NOT NULL, " +
                WaitlistEntry.COLUMN_PARTY_SIZE + " INTEGER NOT NULL, " +
                WaitlistEntry.COLUMN_TIMESTAMP + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP)";
        db.execSQL(SQL_CREATE_WAITLIST_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + WaitlistEntry.TABLE_NAME);
        onCreate(db);
    }

    // TODO (2) Create a static final String called DATABASE_NAME and set it to "waitlist.db"

    // TODO (3) Create a static final int called DATABASE_VERSION and set it to 1

    // TODO (4) Create a Constructor that takes a context and calls the parent constructor

    // TODO (5) Override the onCreate method

        // TODO (6) Inside, create an String query called SQL_CREATE_WAITLIST_TABLE that will create the table

        // TODO (7) Execute the query by calling execSQL on sqLiteDatabase and pass the string query SQL_CREATE_WAITLIST_TABLE

    // TODO (8) Override the onUpgrade method

        // TODO (9) Inside, execute a drop table query, and then call onCreate to re-create it

}

Complete TODOs for T07.02 CreateTheDatabase exercise