package org.jsmpp.session;

import org.jsmpp.bean.DeliverSm;
import org.jsmpp.extra.ProcessMessageException;

/**
 * This listener will listen to every incomming short message, recognized by
 * deliver_sm command. The logic on this listener should be accomplish in a
 * short time, because the deliver_sm_resp will be processed after the logic
 * executed. Normal logic will be return the deliver_sm_resp with zero valued
 * command_status, or throw {@link ProcessMessageException} that gave non-zero
 * valued command_status (in means negative response) depends on the given error
 * code specified on the {@link ProcessMessageException}.
 *
 * @author uudashr
 * @version 1.0
 * @since 2.0
 *
 */
public interface MessageReceiverListener {

    /**
     * Event that called when an short message accepted.
     *
     * @param deliverSm is the deliver_sm command.
     * @throws ProcessMessageException throw if there should be return Non-OK
     *         command_status for the response.
     */
    public void onAcceptDeliverSm(DeliverSm deliverSm)
            throws ProcessMessageException;
}

package org.jsmpp.session;

import org.jsmpp.bean.DeliverSm;
import org.jsmpp.extra.ProcessMessageException;

/**
 * This listener will listen to every incoming short message, recognized by
 * deliver_sm command. The logic on this listener should be accomplish in a
 * short time, because the deliver_sm_resp will be processed after the logic
 * executed. Normal logic will be return the deliver_sm_resp with zero valued
 * command_status, or throw {@link ProcessMessageException} that gave non-zero
 * valued command_status (in means negative response) depends on the given error
 * code specified on the {@link ProcessMessageException}.
 *
 * @author uudashr
 * @version 1.0
 * @since 2.0
 *
 */
public interface MessageReceiverListener {

    /**
     * Event that called when an short message accepted.
     *
     * @param deliverSm is the deliver_sm command.
     * @throws ProcessMessageException throw if there should be return Non-OK
     *         command_status for the response.
     */
    public void onAcceptDeliverSm(DeliverSm deliverSm)
            throws ProcessMessageException;
}

Update the comment spelling :-p

Update the comment spelling :-p


package com.minelittlepony.pony.data;

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

public enum PonyWearable implements ITriggerPixelMapped<PonyWearable> {
    NONE(0),
    SADDLE_BAGS(0xff0000),
    HAT(0x00ff00);

    private int triggerValue;

    PonyWearable(int pixel) {
        triggerValue = pixel;
    }

    @Override
    public int getTriggerPixel() {
        return triggerValue;
    }

    public static PonyWearable[] flags(boolean[] flags) {
        List<PonyWearable> wears = new ArrayList<PonyWearable>();
        PonyWearable[] values = values();
        for (int i = 0; i < values.length; i++) {
            if (flags[i]) wears.add(values[i]);
        }
        return wears.toArray(new PonyWearable[wears.size()]);
    }
}

package com.minelittlepony.pony.data;

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

public enum PonyWearable implements ITriggerPixelMapped<PonyWearable> {
    NONE(0),
    SADDLE_BAGS(255),
    HAT(100);

    private int triggerValue;

    PonyWearable(int pixel) {
        triggerValue = pixel;
    }

    @Override
    public int getTriggerPixel() {
        return triggerValue;
    }

    public static PonyWearable[] flags(boolean[] flags) {
        List<PonyWearable> wears = new ArrayList<PonyWearable>();
        PonyWearable[] values = values();
        for (int i = 0; i < values.length; i++) {
            if (flags[i]) wears.add(values[i]);
        }
        return wears.toArray(new PonyWearable[wears.size()]);
    }
}

Fix trigger pixel for saddlebags

Fix trigger pixel for saddlebags


/*
 * Copyright (C) 2012 The Cat Hive Developers.
 *
 * 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.
 */

/**
 * Gravatar implementation for JavaFX 2.
 * See {@link http://en.gravatar.com/site/implement/images/} for further details.
 */

package com.cathive.fx.gravatar;

/*
 * Copyright (C) 2012 The Cat Hive Developers.
 *
 * 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.
 */

/**
 * Gravatar implementation for JavaFX 2.
 */

package com.cathive.fx.gravatar;

Remove superflous information from Javadoc


package uk.ac.cam.gpe21.droidssl.mitm.cert;

import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.generators.RSAKeyPairGenerator;
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;

import java.math.BigInteger;
import java.security.SecureRandom;

public final class KeyPairGenerator {
	private static final BigInteger PUBLIC_EXPONENT = new BigInteger("10001", 16); /* 65537 */
	private static final int KEY_LENGTH = 2048;

	private final SecureRandom random = new SecureRandom();

	public AsymmetricCipherKeyPair generate() {
		RSAKeyPairGenerator keyGenerator = new RSAKeyPairGenerator();
		keyGenerator.init(new RSAKeyGenerationParameters(
			PUBLIC_EXPONENT, random, KEY_LENGTH, 95 /* certainty in % */
		));
		return keyGenerator.generateKeyPair();
	}
}

package uk.ac.cam.gpe21.droidssl.mitm.cert;

import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.generators.RSAKeyPairGenerator;
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
import org.bouncycastle.crypto.util.PrivateKeyInfoFactory;
import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory;
import org.bouncycastle.jcajce.DefaultJcaJceHelper;

import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public final class KeyPairGenerator {
	private static final BigInteger PUBLIC_EXPONENT = new BigInteger("10001", 16); /* 65537 */
	private static final int KEY_LENGTH = 2048;

	public static KeyPair toJca(AsymmetricCipherKeyPair keyPair) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
		SubjectPublicKeyInfo publicKey = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(keyPair.getPublic());
		PrivateKeyInfo privateKey = PrivateKeyInfoFactory.createPrivateKeyInfo(keyPair.getPrivate());

		KeyFactory keyFactory = new DefaultJcaJceHelper().createKeyFactory("RSA"); // TODO should we really assume RSA?
		return new KeyPair(
			keyFactory.generatePublic(new X509EncodedKeySpec(publicKey.getEncoded())),
			keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKey.getEncoded()))
		);
	}

	private final SecureRandom random = new SecureRandom();

	public AsymmetricCipherKeyPair generate() {
		RSAKeyPairGenerator keyGenerator = new RSAKeyPairGenerator();
		keyGenerator.init(new RSAKeyGenerationParameters(
			PUBLIC_EXPONENT, random, KEY_LENGTH, 95 /* certainty in % */
		));
		return keyGenerator.generateKeyPair();
	}
}

Add method to convert Bouncy Castle key pairs to Java's KeyPair object.


package net.floodlightcontroller.odin.master;

import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;

import net.floodlightcontroller.util.MACAddress;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;

public class LvapHandoffResource extends ServerResource {
	@SuppressWarnings("unchecked")
	@Post
    public void store(String flowmod) {
    	OdinMaster oc = (OdinMaster) getContext().getAttributes().
        					get(OdinMaster.class.getCanonicalName());

    	ObjectMapper mapper = new ObjectMapper();

		HashMap<String, String> fmdata;
		try {
			fmdata = mapper.readValue(flowmod, HashMap.class);

			String staHwAddress = fmdata.get("clientHwAddress");
	        String apIpAddress= fmdata.get("apIpAddress");

	        oc.handoffClientToAp(PoolManager.GLOBAL_POOL, MACAddress.valueOf(staHwAddress), InetAddress.getByName(apIpAddress));
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}

package net.floodlightcontroller.odin.master;

import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;

import net.floodlightcontroller.util.MACAddress;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;

public class LvapHandoffResource extends ServerResource {
	@SuppressWarnings("unchecked")
	@Post
    public void store(String flowmod) {
    	OdinMaster oc = (OdinMaster) getContext().getAttributes().
        					get(OdinMaster.class.getCanonicalName());

    	ObjectMapper mapper = new ObjectMapper();

		HashMap<String, String> fmdata;
		try {
			fmdata = mapper.readValue(flowmod, HashMap.class);

			String staHwAddress = fmdata.get("clientHwAddress");
	        String apIpAddress= fmdata.get("apIpAddress");
	        String poolName = fmdata.get("poolName");

	        oc.handoffClientToAp(poolName, MACAddress.valueOf(staHwAddress), InetAddress.getByName(apIpAddress));
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}

Update REST API for LVAP handoffs

Update REST API for LVAP handoffs


package io.plumery.core;

/**
 * The role interface representing a command
 */
public abstract class Command implements Action {
    public int originalVersion;
    public ID id;
}

package io.plumery.core;

/**
 * The role interface representing a command
 */
public abstract class Command implements Action {
    public int originalVersion;
}

Remove ID from the base class to support semantic ids per related aggregate root


package controllers.application;

import play.mvc.*;
import play.data.Form;
import static play.data.Form.*;

import views.formdata.*;

public class Section0 extends Controller {
    private static final Form<EthicsTriageForm> triageForm = form(EthicsTriageForm.class);

    public static Result section0(Long id) {
        return section0((EthicsTriageForm) null);
    }

    public static Result section0(EthicsTriageForm data) {
        Form<EthicsTriageForm> triageForm = this.triageForm;

        if (data != null) {
            triageForm.fill(data);
            // re-fill with data for editing...
        } else {
            // here we would retrieve a filled form from the database, if available
        }

        return ok(views.html.application.section0.render(triageForm));
    }

    public static Result section0_post(Long id) {
        if (request().body().isMaxSizeExceeded()) {
            return badRequest("Too much data!");
        }

        Form<EthicsTriageForm> triageForm = triageForm.bindFromRequest();

        if (triageForm.hasErrors()) {
            System.out.println(triageForm.errorsAsJson());
            return badRequest(views.html.application.section0.render(triageForm));
        }

        EthicsTriageForm data = triageForm.get();
        System.out.println(data);

        return section0(data);
    }
}

package controllers.application;

import play.mvc.*;
import play.data.Form;
import static play.data.Form.*;

import views.formdata.*;

public class Section0 extends Controller {
    private static final Form<EthicsTriageForm> triageForm = form(EthicsTriageForm.class);

    public static Result section0(Long id) {
        return section0((EthicsTriageForm) null);
    }

    public static Result section0(EthicsTriageForm data) {
        Form<EthicsTriageForm> filledTriageForm = triageForm;

        if (data != null) {
            filledTriageForm = filledTriageForm.fill(data);
            // re-fill with data for editing...
        } else {
            // here we would retrieve a filled form from the database, if available
        }

        return ok(views.html.application.section0.render(filledTriageForm));
    }

    public static Result section0_post(Long id) {
        if (request().body().isMaxSizeExceeded()) {
            return badRequest("Too much data!");
        }

        Form<EthicsTriageForm> filledForm = triageForm.bindFromRequest();
        if(filledForm.hasErrors()) {
            System.out.println(triageForm.errorsAsJson());
            return badRequest(views.html.application.section0.render(triageForm));

        } else {
            EthicsTriageForm data = filledForm.get();
            System.out.println(data);

            return section0(data);
        }
    }
}

Clean up form handling some more

Clean up form handling some more


package org.elasticsearch.analysis;

import org.elasticsearch.common.settings.Settings;

public class VietnameseConfig {
    public static final String DEFAULT_DICT_PATH = "/usr/share/tokenizer/dicts";
    public final String dictPath;
    public final Boolean keepPunctuation;
    public final Boolean splitHost;
    public final Boolean splitURL;

    public VietnameseConfig(Settings settings) {
        dictPath = settings.get("dict_path", DEFAULT_DICT_PATH);
        keepPunctuation = settings.getAsBoolean("keep_punctuation", Boolean.FALSE);
        splitHost = settings.getAsBoolean("split_host", Boolean.FALSE);
        splitURL = settings.getAsBoolean("split_url", Boolean.FALSE);
    }

}

package org.elasticsearch.analysis;

import org.elasticsearch.common.settings.Settings;

public class VietnameseConfig {
    public static final String DEFAULT_DICT_PATH = "/usr/local/share/tokenizer/dicts";
    public final String dictPath;
    public final Boolean keepPunctuation;
    public final Boolean splitHost;
    public final Boolean splitURL;

    public VietnameseConfig(Settings settings) {
        dictPath = settings.get("dict_path", DEFAULT_DICT_PATH);
        keepPunctuation = settings.getAsBoolean("keep_punctuation", Boolean.FALSE);
        splitHost = settings.getAsBoolean("split_host", Boolean.FALSE);
        splitURL = settings.getAsBoolean("split_url", Boolean.FALSE);
    }

}

Update default dict path to /usr/local/share/tokenizer/dicts


package net.ltgt.cookietests;

public interface Constants {
  String TEST_COOKIE_NAME = "$Secure-Foo";
  String TEST_COOKIE_VALUE = "value";

  String TEST_COOKIE = TEST_COOKIE_NAME + "=" + TEST_COOKIE_VALUE;
  String TEST_SET_COOKIE = TEST_COOKIE + ";Path=/;HttpOnly";
}

package net.ltgt.cookietests;

public interface Constants {
  String TEST_COOKIE_NAME = "__Secure-Foo";
  String TEST_COOKIE_VALUE = "value";

  String TEST_COOKIE = TEST_COOKIE_NAME + "=" + TEST_COOKIE_VALUE;
  String TEST_SET_COOKIE = TEST_COOKIE + ";Path=/;HttpOnly";
}

Update to new naming: using double-underscore prefix instead of dollar


//First algo problem in the question bank

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    static int solveMeFirst(int a, int b) {
      return a+b;

   }

 public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a;
        a = in.nextInt();
        int b;
        b = in.nextInt();
        int sum;
        sum = solveMeFirst(a, b);
        System.out.println(sum);
   }
}

Add a comment in the file

Add a comment in the file


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

package org.perfclipse;

/**
 * @author kuba
 *
 */
public class PerfClipseConstants {

	public static final String PERFCAKE_BUNDLE = "org.perfcake";
	public static final String PERFCAKE_SENDER_PACKAGE = "org.perfcake.message.sender";
	public static final String PERFCAKE_GENERATOR_PACKAGE = "org.perfcake.message.generator";
	public static final String PERFCAKE_REPORTER_PACKAGE = "org.perfcake.reporting.reporters";
	public static final String PERFCAKE_DESTINATION_PACKAGE = "org.perfcake.reporting.destinations";
	public static final String PERFCAKE_VALIDATOR_PACKAGE = "org.perfcake.validation";
}

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

package org.perfclipse;

/**
 * @author kuba
 *
 */
public class PerfClipseConstants {

	public static final String PERFCAKE_BUNDLE = "org.perfcake";
	public static final String PERFCAKE_XML_SCHEMA_PATH = "schemas/perfcake-scenario-1.0.xsd";
	public static final String PERFCAKE_SENDER_PACKAGE = "org.perfcake.message.sender";
	public static final String PERFCAKE_GENERATOR_PACKAGE = "org.perfcake.message.generator";
	public static final String PERFCAKE_REPORTER_PACKAGE = "org.perfcake.reporting.reporters";
	public static final String PERFCAKE_DESTINATION_PACKAGE = "org.perfcake.reporting.destinations";
	public static final String PERFCAKE_VALIDATOR_PACKAGE = "org.perfcake.validation";
}

Add path to XML schema

Add path to XML schema


package drones.messages;

import java.io.Serializable;

/**
 * Created by brecht on 4/20/15.
 */
public class JPEGFrameMessage implements Serializable {

    private String imageData;

    public JPEGFrameMessage(String imageData) {
        this.imageData = imageData;
    }

    public String getImageData() {
        return imageData;
    }
}

package drones.messages;

import java.io.Serializable;

/**
 * Created by brecht on 4/20/15.
 */
public class JPEGFrameMessage implements Serializable {

    private String imageData;

    /**
     *
     * @param imageData The image data as a base 64 string
     */
    public JPEGFrameMessage(String imageData) {
        this.imageData = imageData;
    }

    /**
     *
     * @return The image data as a base 64 string
     */
    public String getImageData() {
        return imageData;
    }
}

Add comments to JPEG message

Add comments to JPEG message


package powerups.core.boardpowerup;

import models.Club;
import powerups.Powerup;

import javax.xml.transform.Result;

public class Board extends Powerup {

    public Board(Club club) {
        super(club);

    }

    @Override
    public Result render() {
        return null;
    }
}

package powerups.core.boardpowerup;

import models.Club;
import powerups.Powerup;

public class Board extends Powerup {

    public Board(Club club) {
        super(club);

    }

    @Override
    public play.mvc.Result render() {
        return null;
    }
}

Change return type as per 5d74d94b...

Change return type as per 5d74d94b...


package ua.uagames.itwedding.v201605;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

package ua.uagames.itwedding.v201605;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.google.firebase.analytics.FirebaseAnalytics;

public class MainActivity extends AppCompatActivity {
    private WebView viewer;
    private FirebaseAnalytics analytics;
    private Bundle bundle;

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

        analytics = FirebaseAnalytics.getInstance(this);
        bundle = new Bundle();

        viewer = (WebView) findViewById(R.id.viewer);
        viewer.getSettings().setJavaScriptEnabled(true);
        viewer.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return false;
            }
        });

        viewer.loadUrl("https://drive.google.com/file/d/0B3qWNFQol8lIdDVnaGF1dkUzOFU/view?usp=sharing");

        bundle.putString("app_name", "IT Wedding v2016.05.");
        bundle.putString("app_event", "Create app and load content.");
        analytics.logEvent("app_statistics", bundle);
    }
}

Change project ITWeddingv2016.05. Add function for load content


package com.google.rolecall.authentication;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import com.google.rolecall.Constants;

import org.springframework.http.HttpHeaders;

public class CustomResponseAttributesFilter implements Filter {
  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    chain.doFilter(request, response);
    addSameSiteCookieAttribute((HttpServletResponse) response);
    addAuthorizatinAttribute((HttpServletResponse) response);
  }

  private void addSameSiteCookieAttribute(HttpServletResponse response) {
    response.setHeader(HttpHeaders.SET_COOKIE,
        String.format("%s; %s",response.getHeader(HttpHeaders.SET_COOKIE), "SameSite=None"));
  }

  private void addAuthorizatinAttribute(HttpServletResponse response) {
    response.setHeader(Constants.Headers.AUTHORIZATION, "Bearer");
  }
}

package com.google.rolecall.authentication;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import com.google.rolecall.Constants;

import org.springframework.http.HttpHeaders;

public class CustomResponseAttributesFilter implements Filter {
  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    chain.doFilter(request, response);
    addSameSiteCookieAttribute((HttpServletResponse) response);
    addAuthorizatinAttribute((HttpServletResponse) response);
  }

  private void addSameSiteCookieAttribute(HttpServletResponse response) {
    String header = response.getHeader(HttpHeaders.SET_COOKIE);
    if(header != null & !header.equals("")) {
      response.setHeader(HttpHeaders.SET_COOKIE,String.format("%s; %s", header, "SameSite=None"));
    }
  }

  private void addAuthorizatinAttribute(HttpServletResponse response) {
    response.setHeader(Constants.Headers.AUTHORIZATION, "Bearer");
  }
}

Set different on corner case

Set different on corner case


package org.kelcecil.globalgiving;

import org.kelcecil.globalgiving.action.GetThemes;
import org.kelcecil.globalgiving.model.Theme;

import java.util.List;

/**
 *
 */
public class GlobalGivingClient {

    /**
     * Constructor that uses all defaults including
     * api key from environment.
     */
    public GlobalGivingClient() {}

    /**
     *
     * @return Array of available themes.
     */
    public List<Theme> GetThemes() {
        return new GetThemes().Call();
    }
}

package org.kelcecil.globalgiving;

import org.kelcecil.globalgiving.action.GetThemes;
import org.kelcecil.globalgiving.action.GetThemesWithProjects;
import org.kelcecil.globalgiving.model.Theme;

import java.util.List;

/**
 *
 */
public class GlobalGivingClient {

    /**
     * Constructor that uses all defaults including
     * api key from environment.
     */
    public GlobalGivingClient() {}

    /**
     *
     * @return Array of available themes.
     */
    public List<Theme> getThemes() {
        return new GetThemes().Call();
    }

    public List<Theme> getThemesWithProjects() {
        return new GetThemesWithProjects().Call();
    }
}

Make methods begin with lowercase

Make methods begin with lowercase

Too much golang lately


package hudson.model;

import javax.annotation.PostConstruct;

/**
 * Marker interface for Descriptors which use xml persistent data, and as such need to load from disk when instantiated.
 *

 * {@link Descriptor#load()} method is annotated as {@link PostConstruct} so it get automatically invoked after
 * constructor and field injection.
 * @author Nicolas De Loof
 */
public interface PersistentDescriptor extends Saveable {

    @PostConstruct
    void load();
}

package hudson.model;

import javax.annotation.PostConstruct;

/**
 * Marker interface for Descriptors which use xml persistent data, and as such need to load from disk when instantiated.
 *

 * {@link Descriptor#load()} method is annotated as {@link PostConstruct} so it get automatically invoked after
 * constructor and field injection.
 * @author Nicolas De Loof
 * @since 2.140
 */
public interface PersistentDescriptor extends Saveable {

    @PostConstruct
    void load();
}

[JENKINS-52818] Add the missing @since
- avoid git-archeology to find when the interface was added


/*                                                                      *\
**                    SICU Stress Measurement System                    **
**                      Project P04  |  C380 Team A                     **
**          EBME 380: Biomedical Engineering Design Experience          **
**                    Case Western Reserve University                   **
**                          2016 Fall Semester                          **
\*                                                                      */

package edu.cwru.sicu_sms;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

/**
 * The main stage of the front-end program for interfacing with the electronic system.
 *
 * @since September 27, 2016
 * @author Ted Frohlich <ttf10@case.edu>
 * @author Abby Walker <amw138@case.edu>
 */
public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(
                getClass().getResource("sicu_sms.fxml")
        );
        primaryStage.setTitle("SICU Stress Measurement System");
        primaryStage.setScene(new Scene(root));
        primaryStage.setMaximized(true);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

/*                                                                      *\
**                    SICU Stress Measurement System                    **
**                      Project P04  |  C380 Team A                     **
**          EBME 380: Biomedical Engineering Design Experience          **
**                    Case Western Reserve University                   **
**                          2016 Fall Semester                          **
\*                                                                      */

package edu.cwru.sicu_sms;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;

/**
 * The main stage of the front-end program for interfacing with the electronic system.
 *
 * @since September 27, 2016
 * @author Ted Frohlich <ttf10@case.edu>
 * @author Abby Walker <amw138@case.edu>
 */
public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(
                getClass().getResource("sicu_sms.fxml")
        );
        primaryStage.getIcons().add(new Image(
                "http://s3.amazonaws.com/libapps/customers/558/images/CWRU_Logo.jpg"));
        primaryStage.setTitle("SICU Stress Measurement System");
        primaryStage.setScene(new Scene(root));
        primaryStage.setMaximized(true);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

Add icon to primary stage

Add icon to primary stage


package butterknife;

import android.support.annotation.ArrayRes;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.CLASS;

/**
 * Bind a field to the specified array resource ID. The type of array will be inferred from the
 * annotated element.
 *
 * String array:
 *

 * {@literal @}BindArray(R.array.countries) String[] countries;
 *

 *
 * Int array:
 *

 * {@literal @}BindArray(R.array.phones) int[] phones;
 *

 *
 * Text array:
 *

 * {@literal @}BindArray(R.array.options) CharSequence[] options;
 *

 *
 * {@link android.content.res.TypedArray}:
 *

 * {@literal @}BindArray(R.array.icons) TypedArray icons;
 *

 */
@Retention(CLASS) @Target(FIELD)
public @interface BindArray {
  /** Array resource ID to which the field will be bound. */
  @ArrayRes int value();
}

package butterknife;

import android.support.annotation.ArrayRes;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

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

/**
 * Bind a field to the specified array resource ID. The type of array will be inferred from the
 * annotated element.
 *
 * String array:
 *

 * {@literal @}BindArray(R.array.countries) String[] countries;
 *

 *
 * Int array:
 *

 * {@literal @}BindArray(R.array.phones) int[] phones;
 *

 *
 * Text array:
 *

 * {@literal @}BindArray(R.array.options) CharSequence[] options;
 *

 *
 * {@link android.content.res.TypedArray}:
 *

 * {@literal @}BindArray(R.array.icons) TypedArray icons;
 *

 */
@Retention(RUNTIME) @Target(FIELD)
public @interface BindArray {
  /** Array resource ID to which the field will be bound. */
  @ArrayRes int value();
}

Fix annotation retention for reflect usage


package cgeo.geocaching.utils;

import cgeo.geocaching.BuildConfig;

public class BranchDetectionHelper {

    // should contain the version name of the last feature release
    public static final String FEATURE_VERSION_NAME = "2022.10.16";

    // should contain version names of active bugfix releases since last feature release, oldest first
    // empty the part within curly brackets when creating a new release branch from master
    public static final String[] BUGFIX_VERSION_NAME = new String[]{ };

    private BranchDetectionHelper() {
        // utility class
    }

    /**
     * @return true, if BUILD_TYPE is not a nightly or debug build (e. g.: release, rc, legacy)
     */
    // BUILD_TYPE is detected as constant but can change depending on the build configuration
    @SuppressWarnings("ConstantConditions")
    public static boolean isProductionBuild() {
        return !(BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("nightly"));
    }

    /**
     * @return true, if BUILD_TYPE is a debug build. Nightly builds are **not** considered as developer build!
     */
    // BUILD_TYPE is detected as constant but can change depending on the build configuration
    @SuppressWarnings("ConstantConditions")
    public static boolean isDeveloperBuild() {
        return BuildConfig.BUILD_TYPE.equals("debug");
    }

}

package cgeo.geocaching.utils;

import cgeo.geocaching.BuildConfig;

public class BranchDetectionHelper {

    // should contain the version name of the last feature release
    public static final String FEATURE_VERSION_NAME = "2022.10.17";

    // should contain version names of active bugfix releases since last feature release, oldest first
    // empty the part within curly brackets when creating a new release branch from master
    public static final String[] BUGFIX_VERSION_NAME = new String[]{ };

    private BranchDetectionHelper() {
        // utility class
    }

    /**
     * @return true, if BUILD_TYPE is not a nightly or debug build (e. g.: release, rc, legacy)
     */
    // BUILD_TYPE is detected as constant but can change depending on the build configuration
    @SuppressWarnings("ConstantConditions")
    public static boolean isProductionBuild() {
        return !(BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("nightly"));
    }

    /**
     * @return true, if BUILD_TYPE is a debug build. Nightly builds are **not** considered as developer build!
     */
    // BUILD_TYPE is detected as constant but can change depending on the build configuration
    @SuppressWarnings("ConstantConditions")
    public static boolean isDeveloperBuild() {
        return BuildConfig.BUILD_TYPE.equals("debug");
    }

}

Prepare version number for upcoming release

(2nd try)


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

import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Scopes;

import static io.airlift.configuration.ConfigBinder.configBinder;
import static io.airlift.http.client.HttpClientBinder.httpClientBinder;
import static io.airlift.jaxrs.JaxrsBinder.jaxrsBinder;

public class ProxyModule
        implements Module
{
    @Override
    public void configure(Binder binder)
    {
        httpClientBinder(binder).bindHttpClient("proxy", ForProxy.class);

        configBinder(binder).bindConfig(ProxyConfig.class);
        configBinder(binder).bindConfig(JwtHandlerConfig.class, "proxy");

        jaxrsBinder(binder).bind(ProxyResource.class);

        binder.bind(JsonWebTokenHandler.class).in(Scopes.SINGLETON);
    }
}

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

import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Scopes;
import io.airlift.http.server.HttpServerConfig;

import static io.airlift.configuration.ConfigBinder.configBinder;
import static io.airlift.http.client.HttpClientBinder.httpClientBinder;
import static io.airlift.jaxrs.JaxrsBinder.jaxrsBinder;

public class ProxyModule
        implements Module
{
    @Override
    public void configure(Binder binder)
    {
        configBinder(binder).bindConfigDefaults(HttpServerConfig.class, httpServerConfig -> {
            httpServerConfig.setAdminEnabled(false);
        });

        httpClientBinder(binder).bindHttpClient("proxy", ForProxy.class);

        configBinder(binder).bindConfig(ProxyConfig.class);
        configBinder(binder).bindConfig(JwtHandlerConfig.class, "proxy");

        jaxrsBinder(binder).bind(ProxyResource.class);

        binder.bind(JsonWebTokenHandler.class).in(Scopes.SINGLETON);
    }
}

Disable Airlift admin servlet in Proxy

Disable Airlift admin servlet in Proxy

Same as e9c217ae4a3e1a3c73be5bcd417bb5cf1384eaca, this time for Presto
Proxy.


package net.aeten.core.spi;

/**
 *
 * @author Thomas Pérennou
 */
public @interface Configurations {
	Configuration[] value();
}

package net.aeten.core.spi;

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;

/**
 *
 * @author Thomas Pérennou
 */
@Documented
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.PACKAGE, ElementType.TYPE})
public @interface Configurations {
	Configuration[] value();
}

Add Documented, Retention and Target annotations


public final class Constants{
    private Constants() {}

    public static String getErrInfoString(String errCode){
        switch(errCode){
            //Sent by conversion server.
            case "ERR001":
                return "The number of parameter does not meet requirement.";
            case "ERR002":
                return "The converted value is not int or double.";
            case "ERR003":
                return "Conversion units are not recognized.";
            default:
                return null;
        }
    }
}

public final class Constants{
    private Constants() {}

    public static String getErrInfoString(String errCode){
        switch(errCode){
            //Sent by conversion server.
            case "ERR001":
                return "The number of parameter does not meet requirement.";
            case "ERR002":
                return "The converted value is not int or double.";
            case "ERR003":
                return "Conversion units are not recognized.";
            case "ERR008":
                return "Failure: Unit not existed.";
            case "ERR009":
                return "Failure: Server not found.";
            default:
                return null;
        }
    }
}

Add error 08 & 09

Add error 08 & 09


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

package org.qi4j.library.jmx;

import java.util.List;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import org.qi4j.api.service.ImportedServiceDescriptor;
import org.qi4j.api.service.ServiceImporter;
import org.qi4j.api.service.ServiceImporterException;

/**
 * Importer for the MBeanServer of the JVM. Either use the first server that can be located, or create a new one.
 */
public class MBeanServerImporter
    implements ServiceImporter
{
    public Object importService( ImportedServiceDescriptor serviceDescriptor )
        throws ServiceImporterException
    {
        List<MBeanServer> mbeanServers = MBeanServerFactory.findMBeanServer( null );
        if( mbeanServers.size() > 0 )
        {
            return mbeanServers.get( 0 );
        }
        else
        {
            return MBeanServerFactory.createMBeanServer("DefaultDomain");
        }
    }

    public boolean isActive( Object instance )
    {
        return true;
    }

    public boolean isAvailable( Object instance )
    {
        return true;
    }
}

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

package org.qi4j.library.jmx;

import org.qi4j.api.service.ImportedServiceDescriptor;
import org.qi4j.api.service.ServiceImporter;
import org.qi4j.api.service.ServiceImporterException;

import java.lang.management.ManagementFactory;

/**
 * Importer for the MBeanServer of the JVM. Either use the first server that can be located, or create a new one.
 */
public class MBeanServerImporter
    implements ServiceImporter
{
    public Object importService( ImportedServiceDescriptor serviceDescriptor )
        throws ServiceImporterException
    {
        return ManagementFactory.getPlatformMBeanServer();
    }

    public boolean isActive( Object instance )
    {
        return true;
    }

    public boolean isAvailable( Object instance )
    {
        return true;
    }
}

Use the Platform MBeanServer. This ensures that application MBeans are registered in the same MBeanServer as the platform MBeans.


package com.decker.Essentials;

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

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

import com.decker.Essentials.Category.Category;
import com.decker.Essentials.User.User;

public class Center extends org.sipc.se.plugin.PluginImpl
{

    Category category;
    public Center()
    {
	super();
	this.category=Category.getInstance();
    }

    @Override
    public void getResponse(HttpServletRequest request, HttpServletResponse response)
    {
	String url = request.getRequestURI();
	String target = url.substring(url.indexOf("Essentials") + "Essentials".length() + 1);
	OutputStream stream;
	try
	{
	    stream = response.getOutputStream();
	    byte[] resource=null;

	    if (target.matches(".*.exec"))
	    {
		//dynamic generate
		User current=new User(request.getCookies());
		resource = Command.Execute(current,request,response);
	    } else
	    {
		//static resource
		resource = ResourceManager.getInstance().getResource("Content/"+target);
	    }

	    if (resource.length == 0)
	    {
		response.setStatus(404);
	    }

	    stream.write(resource);

	} catch (IOException e)
	{

	}

    }

    @Override
    public String getUrl()
    {
	return "Essentials";
    }

    @Override
    public boolean onEnable()
    {
	// TODO Auto-generated method stub
	return true;
    }
}

package com.decker.Essentials;

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

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

import com.decker.Essentials.Category.Category;
import com.decker.Essentials.User.User;

public class Center extends org.sipc.se.plugin.PluginImpl
{

    Category category;
    public Center()
    {
	super();
	this.category=Category.getInstance();
    }

    @Override
    public void getResponse(HttpServletRequest request, HttpServletResponse response)
    {
	String url = request.getRequestURI();
	String target = url.substring(url.indexOf("Essentials") + "Essentials".length() + 1);
	OutputStream stream;
	try
	{
	    stream = response.getOutputStream();
	    byte[] resource=null;

	    if (target.matches(".*.exec"))
	    {
		//dynamic generate
		User current=new User(request.getCookies());
		response.setContentType("application/json");
		resource = Command.Execute(current,request,response);
	    } else
	    {
		//static resource
		resource = ResourceManager.getInstance().getResource("Content/"+target);
	    }

	    if (resource.length == 0)
	    {
		response.setStatus(404);
	    }

	    stream.write(resource);

	} catch (IOException e)
	{

	}

    }

    @Override
    public String getUrl()
    {
	return "Essentials";
    }

    @Override
    public boolean onEnable()
    {
	// TODO Auto-generated method stub
	return true;
    }
}

Change content type when execute command


package nl.tudelft.ti2306.blockchain;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

import nl.tudelft.ti2306.blockchain.datastructure.PeerGraph;

public class PeerGraphToViz implements Runnable {

    private PeerGraph graph;
    private String output;

    public PeerGraphToViz(PeerGraph graph, String output) {
        this.graph = graph;
        this.output = output;
    }

    @Override
    public void run() {
        try (PrintWriter out = new PrintWriter(new File(output))) {
            out.println("graph peergraph {");
            out.println("ratio=expand;");
            out.println("node[width=.40,height=.40, label=\"\"]");
            out.println("edge[arrowsize=\"0.3\"]");
            for (int i = 0; i < graph.getNodes().size(); i++) {
                out.println(i + " [label=" + i + " style=filled fillcolor=red]");
                for (int j = 0; j < graph.getEdges(i).size(); j++) {
                    int k = graph.getEdges(i).get(j);
                    if (i > k) continue;
                    out.println(i + "--" + k + " [color=black]");
                }
            }
            out.println("}");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}

package nl.tudelft.ti2306.blockchain;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

import nl.tudelft.ti2306.blockchain.datastructure.PeerGraph;

public class PeerGraphToViz implements Runnable {

    private PeerGraph graph;
    private String output;

    public PeerGraphToViz(PeerGraph graph, String output) {
        this.graph = graph;
        this.output = output;
    }

    @Override
    public void run() {
        try (PrintWriter out = new PrintWriter(new File(output))) {
            out.println("graph peergraph {");
            out.println("ratio=expand;");
            out.println("node[width=.40,height=.40, label=\"\"]");
            out.println("edge[arrowsize=\"0.3\"]");
            for (int i = 0; i < graph.getNodes().size(); i++) {
                double hue = i / (double) graph.getNodes().size();
                out.println(i + " [label=" + i + " style=filled fillcolor=\"" + hue + " 1.0 1.0\"]");
                for (int j = 0; j < graph.getEdges(i).size(); j++) {
                    int k = graph.getEdges(i).get(j);
                    if (i > k) continue;
                    out.println(i + "--" + k + " [color=black]");
                }
            }
            out.println("}");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}

Add colors to peer graph

Add colors to peer graph


// default package

/** Custom build program using {@code Bach.java} API. */
class Build {

  public static void main(String... args) {
    // Bach.main(args); // Delegate to Bach.java's default main program.

    var buildSummary = new Bach().build(project -> project.version("1-ea"));
    buildSummary.assertSuccessful();
  }
}

// default package

/** Custom build program using {@code Bach.java} API. */
class Build {

  public static void main(String... args) {
    new Bach().build(project -> project.version("1-ea")).assertSuccessful();
  }
}

Reduce custom build program to an one-liner


/*
 * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE)
 */
package org.ligoj.app.resource.security;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.Length;

import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * User.
 */
@Getter
@Setter
@EqualsAndHashCode(of = "name")
@NoArgsConstructor
@AllArgsConstructor
public class User {

	@NotBlank
	@NotNull
	private String name;

	@NotBlank
	@NotNull
	@Length(max = 250)
	private String password;

}

/*
 * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE)
 */
package org.ligoj.app.resource.security;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.Length;

import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * User.
 */
@Getter
@Setter
@EqualsAndHashCode(of = "name")
@NoArgsConstructor
@AllArgsConstructor
public class User {

	@NotBlank
	@NotNull
	private String name;

	@NotBlank
	@NotNull
	@Length(max = 4096)
	private String password;

}

Allow up to 4K credential data

Allow up to 4K credential data


/**
 * Copyright (c) 2016, All partners of the iTesla project (http://www.itesla-project.eu/consortium)
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
package eu.itesla_project.commons.tools;

import org.apache.commons.cli.CommandLine;

/**
 *
 * @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com>
 */
public interface Tool {

    /**
     * Get the command of the tool.
     */
    Command getCommand();

    /**
     * Run the tool.
     *
     * @param line the command line arguments
     * @param context tool execution context
     * @throws Exception if the command fails
     */
    default void run(CommandLine line, ToolRunningContext context) throws Exception {
    }

    @Deprecated
    default void run(CommandLine line) throws Exception {
        run(line, new ToolRunningContext());
    }

}

/**
 * Copyright (c) 2016, All partners of the iTesla project (http://www.itesla-project.eu/consortium)
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
package eu.itesla_project.commons.tools;

import org.apache.commons.cli.CommandLine;

/**
 *
 * @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com>
 */
public interface Tool {

    /**
     * Get the command of the tool.
     */
    Command getCommand();

    /**
     * Run the tool.
     *
     * @param line the command line arguments
     * @param context tool execution context
     * @throws Exception if the command fails
     */
    default void run(CommandLine line, ToolRunningContext context) throws Exception {
        run(line);
    }

    @Deprecated
    default void run(CommandLine line) throws Exception {
    }

}

Fix tool bug using old interface

Fix tool bug using old interface


package reversi.models;

import base.models.Board;

public class ReversiBoard extends Board<ReversiPiece>{

	//TODO: Implement board

	//TODO: Create function that shows the board in ASCII
}

package reversi.models;

import java.util.Map;

import base.models.Board;
import base.models.BoardPiece;
import base.models.Position;

public class ReversiBoard extends Board<ReversiPiece>{

	//TODO: Implement board

	//TODO: Create function that shows the board in ASCII

	private static final String[] columnAlpha = {"a","b","c","d","e","f","g","h"};

	public String DrawBoard(ReversiBoard board)
	{
		Map<Position, BoardPiece<ReversiPiece>> boardPieces = board.getBoardElements();

		StringBuilder builder = new StringBuilder();

		for (int c = 0; c < 8; c++) {

			String currentColumn = columnAlpha[c];

			builder.append(c);

			for (int r = 0; r < 8; r++) {

				builder.append("|");

				Integer currentRow = r;

				Position position = new Position(currentColumn, currentRow);

				BoardPiece<ReversiPiece> boardPiece = boardPieces.get(position);

				String representation = this.DrawElement(boardPiece);

				builder.append(representation);
			}

		}
		return board;

	}

	public String DrawElement(BoardPiece<ReversiPiece> piece)
	{
		String result = "";

		ReversiPiece reversiPiece = piece.getElement();

		if(reversiPiece == null)
			result = "_";
		else

		return result;
	}

}

Work on DrawBoard and DrawElement

Work on DrawBoard and DrawElement


package com.vaguehope.morrigan;

import org.kohsuke.args4j.Option;

public class Args {

	@Option(name = "-d", aliases = { "--dlna" }, usage = "Enable DLNA.") private boolean dlna;
	@Option(name = "-i", aliases = { "--interface" }, usage = "Hostname or IP address of interface to bind to.") private String iface;
	@Option(name = "-p", aliases = { "--port" }, usage = "Local port to bind HTTP UI to.") private int httpPort = -1;
	@Option(name = "-s", aliases = { "--ssh" }, usage = "Local port to bind SSH UI to.") private int sshPort = -1;
	@Option(name = "-v", aliases = { "--verbose" }, usage = "print log lines for various events.") private boolean verboseLog = false;

	public String getInterface () {
		return this.iface;
	}

	public int getHttpPort() {
		return this.httpPort;
	}

	public int getSshPort() {
		return this.sshPort;
	}

	public boolean isDlna() {
		return this.dlna;
	}

	public boolean isVerboseLog() {
		return this.verboseLog;
	}

}

package com.vaguehope.morrigan;

import org.kohsuke.args4j.Option;

public class Args {

	@Option(name = "--dlna", usage = "Enable DLNA.") private boolean dlna;
	@Option(name = "--interface", usage = "Hostname or IP address of interface to bind to.") private String iface;
	@Option(name = "--port", usage = "Local port to bind HTTP UI to.") private int httpPort = -1;
	@Option(name = "--ssh", usage = "Local port to bind SSH UI to.") private int sshPort = -1;
	@Option(name = "-v", aliases = { "--verbose" }, usage = "print log lines for various events.") private boolean verboseLog = false;

	public String getInterface () {
		return this.iface;
	}

	public int getHttpPort() {
		return this.httpPort;
	}

	public int getSshPort() {
		return this.sshPort;
	}

	public boolean isDlna() {
		return this.dlna;
	}

	public boolean isVerboseLog() {
		return this.verboseLog;
	}

}

Remove single char args, this is not an interactive tool.


// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// TODO: Remove this package on Vespa 8
@ExportPackage
package com.yahoo.vespaxmlparser;

import com.yahoo.osgi.annotation.ExportPackage;

// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// TODO: Remove this package on Vespa 9
@ExportPackage
package com.yahoo.vespaxmlparser;

import com.yahoo.osgi.annotation.ExportPackage;

Move TODO to Vespa 9 (was previously moved to 8 from 7)


package application.Actions;

import javafx.geometry.Point2D;
import application.SLogoCanvas;
import application.Turtle;

public class ForwardAction extends AbstractAction {

	public ForwardAction(double distance) {
		myValue = distance;
	}

	@Override
	public void update(Turtle turtle, SLogoCanvas canvas) {
		Point2D previousLocation = turtle.getLocation();

		double remainder = myValue;
		while (remainder > 0) {
			//I PROMISE I WILL COME UP WITH A BETTER SOLUTION
			//BUT MAYBE THIS IDEA WILL BE COOL FOR ANIMATING
			//PROBABLY SHOULDN'T BE IN THE FORWARD ACTION THOUGH
			if (turtle.getPen().isDashed() && myValue > 30) {
				canvas.displayLine(turtle.move(30));
				remainder -= 20;
			} else if (turtle.getPen().isDotted() && myValue > 5) {
				canvas.displayLine(turtle.move(5));
				remainder -= 5;
			} else {
				canvas.displayLine(turtle.move(1));
				remainder -= 1;
			}
		}
		// System.out.println("***Prior Location: " + prevLoc);
		// System.out.println("***Prior Location: " + turt.getLocation());
	}

	@Override
	public String toString() {
		return "fwd " + myValue;
	}

}

package application.Actions;

import javafx.geometry.Point2D;
import application.SLogoCanvas;
import application.Turtle;

public class ForwardAction extends AbstractAction {

	public ForwardAction(double distance) {
		myValue = distance;
	}

	@Override
	public void update(Turtle turtle, SLogoCanvas canvas) {
		Point2D previousLocation = turtle.getLocation();

		double remainder = myValue;
		while (remainder > 0) {
			//I PROMISE I WILL COME UP WITH A BETTER SOLUTION
			//BUT MAYBE THIS IDEA WILL BE COOL FOR ANIMATING
			//PROBABLY SHOULDN'T BE IN THE FORWARD ACTION THOUGH
			if (turtle.getPen().isDashed() && remainder >= 30) {
				canvas.displayLine(turtle.move(30));
				remainder -= 30;
			} else if (turtle.getPen().isDotted() && remainder >= 5) {
				canvas.displayLine(turtle.move(5));
				remainder -= 5;
			} else {
				canvas.displayLine(turtle.move(1));
				remainder -= 1;
			}
		}
		// System.out.println("***Prior Location: " + prevLoc);
		// System.out.println("***Prior Location: " + turt.getLocation());
	}

	@Override
	public String toString() {
		return "fwd " + myValue;
	}

}

Revert "Revert "fixed pen styling bug""

Revert "Revert "fixed pen styling bug""

This reverts commit d262982255df13839daae4fec30accd9617ed157.


package org.mozilla.mozstumbler;

import android.annotation.SuppressLint;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

final class DateTimeUtils {
    private static final DateFormat mISO8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");

    static final long MILLISECONDS_PER_DAY = 86400000;  // milliseconds/day

    private DateTimeUtils() {
    }

    @SuppressLint("SimpleDateFormat")
    static String formatDate(Date date) {
        return mISO8601Format.format(date);
    }

    static String formatTime(long time) {
        return formatDate(new Date(time));
    }

    static String formatTimeForLocale(long time) {
        return DateFormat.getDateTimeInstance().format(time);
    }

    static String formatCurrentTime() {
        return formatTime(System.currentTimeMillis());
    }
}

package org.mozilla.mozstumbler;

import android.annotation.SuppressLint;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

final class DateTimeUtils {
    private static final DateFormat mISO8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");

    static final long MILLISECONDS_PER_DAY = 86400000;  // milliseconds/day

    static {
        mISO8601Format.setTimeZone(TimeZone.getTimeZone("UTC"));
    }

    private DateTimeUtils() {
    }

    @SuppressLint("SimpleDateFormat")
    static String formatDate(Date date) {
        return mISO8601Format.format(date);
    }

    static String formatTime(long time) {
        return formatDate(new Date(time));
    }

    static String formatTimeForLocale(long time) {
        return DateFormat.getDateTimeInstance().format(time);
    }

    static String formatCurrentTime() {
        return formatTime(System.currentTimeMillis());
    }
}

Fix timezone in submitted data

Fix timezone in submitted data

SimpleDateFormat uses the system's default time zone by default.


/**
 * Copyright (C) 2000 - 2011 Silverpeas
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * As a special exception to the terms and conditions of version 3.0 of
 * the GPL, you may redistribute this Program in connection with Free/Libre
 * Open Source Software ("FLOSS") applications as described in Silverpeas's
 * FLOSS exception.  You should have received a copy of the text describing
 * the FLOSS exception, and it is also available here:
 * "http://repository.silverpeas.com/legal/licensing"
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.stratelia.webactiv;

public enum SilverpeasRole {
  admin, publisher, writer, user, reader, supervisor;

  public boolean isInRole(String role) {
    return this == valueOf(role);
  }
}

/**
 * Copyright (C) 2000 - 2011 Silverpeas
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * As a special exception to the terms and conditions of version 3.0 of
 * the GPL, you may redistribute this Program in connection with Free/Libre
 * Open Source Software ("FLOSS") applications as described in Silverpeas's
 * FLOSS exception.  You should have received a copy of the text describing
 * the FLOSS exception, and it is also available here:
 * "http://repository.silverpeas.com/legal/licensing"
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.stratelia.webactiv;

public enum SilverpeasRole {
  admin, publisher, writer, user, reader, supervisor, privilegedUser;

  public boolean isInRole(String role) {
    try {
      return this == valueOf(role);
    } catch(IllegalArgumentException ex) {
      return false;
    }
  }
}

Add privilegedUser and catch IllegalArgumentException


//
//  DefaultXalWindow.java
//  xal
//
//  Created by Thomas Pelaia on 7/18/06.
//  Copyright 2006 Oak Ridge National Lab. All rights reserved.
//

package xal.application;

/** provides a default implementation of the XAL window */
public class DefaultXalWindow extends XalWindow {
    /** serialization ID */
    private static final long serialVersionUID = 1L;

    /** Constructor */
    public DefaultXalWindow( final XalDocument aDocument ) {
		super( aDocument );
    }

    /**
	 * Indicates whether or not to display the toolbar.
	 * @return true to display the toolbar and false to hide it
     */
    public boolean usesToolbar() {
        return true;
    }
}

//
//  DefaultXalWindow.java
//  xal
//
//  Created by Thomas Pelaia on 7/18/06.
//  Copyright 2006 Oak Ridge National Lab. All rights reserved.
//

package xal.application;

/** provides a default implementation of the XAL window */
public class DefaultXalWindow extends XalWindow {
    /** serialization ID */
    private static final long serialVersionUID = 1L;

    /** indicates whether to display a toolbar */
    private final boolean DISPLAYS_TOOLBAR;

    /** Constructor */
    public DefaultXalWindow( final XalDocument aDocument ) {
		this( aDocument, true );
    }

    /** Constructor */
    public DefaultXalWindow( final XalDocument aDocument, final boolean displaysToolbar ) {
		super( aDocument );
        DISPLAYS_TOOLBAR = displaysToolbar;
    }

    /**
	 * Indicates whether or not to display the toolbar.
	 * @return true to display the toolbar and false to hide it
     */
    public boolean usesToolbar() {
        return DISPLAYS_TOOLBAR;
    }
}

Make the toolbar optional for the default XAL window.


package com.creatubbles.api.model.hashtag;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.jasminb.jsonapi.annotations.Id;
import com.github.jasminb.jsonapi.annotations.Type;

@Type("hashtags")
public class Hashtag {
    @Id
    private String id;

    @JsonProperty("is_official")
    private Boolean official = Boolean.FALSE;

    @JsonProperty("avatar_image_url")
    private AvatarImage avatarImage;

    @NonNull
    public String getId() {
        return id;
    }

    @Nullable
    public Boolean getOfficial() {
        return official;
    }

    @Nullable
    public AvatarImage getAvatarImage() {
        return avatarImage;
    }

    @Override
    public String toString() {
        return "Hashtag{" +
                "id='" + id + '\'' +
                ", official=" + official +
                ", avatarImage=" + avatarImage +
                '}';
    }
}

package com.creatubbles.api.model.hashtag;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.jasminb.jsonapi.annotations.Id;
import com.github.jasminb.jsonapi.annotations.Type;

@Type("hashtags")
public class Hashtag {
    @Id
    private String id;

    @JsonProperty("is_official")
    private Boolean official;

    @JsonProperty("avatar_image_url")
    private AvatarImage avatarImage;

    @JsonProperty("taggings_count")
    private Integer taggingsCount;

    @JsonProperty("followers_count")
    private Integer followersCount;

    @NonNull
    public String getId() {
        return id;
    }

    @Nullable
    public Boolean getOfficial() {
        return official;
    }

    @Nullable
    public AvatarImage getAvatarImage() {
        return avatarImage;
    }

    @Nullable
    public Integer getTaggingsCount() {
        return taggingsCount;
    }

    @Nullable
    public Integer getFollowersCount() {
        return followersCount;
    }

    @Override
    public String toString() {
        return "Hashtag{" +
                "id='" + id + '\'' +
                ", official=" + official +
                ", avatarImage=" + avatarImage +
                ", taggingsCount=" + taggingsCount +
                ", followersCount=" + followersCount +
                '}';
    }
}

Add new fields to hashtag model

Add new fields to hashtag model


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

package net.openhft.chronicle.core.util;

import org.jetbrains.annotations.NotNull;

/**
 * Created by peter on 23/06/15.
 */
public interface ReadResolvable<T> {
    @NotNull
    @SuppressWarnings("unchecked")
    static <T> T readResolve(Object o) {
        return (T) (o instanceof ReadResolvable ? ((ReadResolvable) o).readResolve() : o);
    }

    /**
     * Post deserialization step
     *
     * @return the object to use instead.
     */
    @NotNull
    T readResolve();
}

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

package net.openhft.chronicle.core.util;

import org.jetbrains.annotations.NotNull;

/**
 * Created by peter on 23/06/15.
 */
public interface ReadResolvable<T> {
    @SuppressWarnings("unchecked")
    static <T> T readResolve(Object o) {
        return (T) (o instanceof ReadResolvable ? ((ReadResolvable) o).readResolve() : o);
    }

    /**
     * Post deserialization step
     *
     * @return the object to use instead.
     */
    @NotNull
    T readResolve();
}

Refactor queue tests to store temporary files until target. Migrate some tests from Queue to Queue Enterprise.


package org.embulk.output.sftp.utils;

import org.embulk.EmbulkTestRuntime;
import org.junit.Rule;
import org.junit.Test;

import java.io.Closeable;

import static junit.framework.TestCase.fail;
import static org.junit.Assert.assertTrue;

public class TestTimeoutCloser
{
    @Rule
    public EmbulkTestRuntime runtime = new EmbulkTestRuntime();

    @Test
    public void testTimeoutAndResume()
    {
        TimeoutCloser closer = new TimeoutCloser(new Closeable()
        {
            @Override
            public void close()
            {
                try {
                    Thread.sleep(5000);
                }
                catch (InterruptedException e) {
                    fail("Failed to sleep");
                }
            }
        });
        closer.timeout = 1;
        long start = System.currentTimeMillis();
        closer.close();
        long duration = System.currentTimeMillis() - start;
        assertTrue("longer than 1s", duration > 1000);
        assertTrue("shorter than 5s", duration < 5000);
    }
}

package org.embulk.output.sftp.utils;

import org.embulk.EmbulkTestRuntime;
import org.junit.Rule;
import org.junit.Test;

import java.io.Closeable;
import java.util.concurrent.TimeoutException;

import static junit.framework.TestCase.fail;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;

public class TestTimeoutCloser
{
    @Rule
    public EmbulkTestRuntime runtime = new EmbulkTestRuntime();

    @Test
    public void testTimeoutAndAbort()
    {
        TimeoutCloser closer = new TimeoutCloser(new Closeable()
        {
            @Override
            public void close()
            {
                try {
                    Thread.sleep(5000);
                }
                catch (InterruptedException e) {
                    fail("Failed to sleep");
                }
            }
        });
        closer.timeout = 1;
        try {
            closer.close();
            fail("Should not finish");
        }
        catch (Exception e) {
            assertThat(e, instanceOf(RuntimeException.class));
            assertThat(e.getCause(), instanceOf(TimeoutException.class));
        }
    }
}

Update unit test of time-out closer

Update unit test of time-out closer


package org.twig.compiler;

import org.junit.Assert;
import org.junit.Test;
import org.twig.Environment;
import org.twig.exception.TwigRuntimeException;
import org.twig.template.Template;

public class RuntimeTemplateCompilerTests {
    @Test
    public void testCompileJavaCode() throws TwigRuntimeException {
        RuntimeTemplateCompiler runtimeCompiler = new RuntimeTemplateCompiler(new Environment());

        String sourceCode = "package org.twig.template;\n\n"
                + "public class TestTemplate extends org.twig.template.Template {\n"
                + "    protected String doRender(java.util.Map<String, ?> context) { return \"foo\"; }\n"
                + "    public String getTemplateName() { return \"foo\"; }\n"
                + "}\n";
        Template template = runtimeCompiler.compile(sourceCode, "org.twig.template.TestTemplate");

        Assert.assertEquals("Complied class method render() should return \"foo\"", "foo", template.render());
    }

    @Test(expected = TwigRuntimeException.class)
    public void testThrowsRuntimeErrorExceptionOnFailToCompile() throws TwigRuntimeException {
        RuntimeTemplateCompiler runtimeCompiler = new RuntimeTemplateCompiler(new Environment());

        String sourceCode = "invalid java code";

        runtimeCompiler.compile(sourceCode, "something");
    }
}

package org.twig.compiler;

import org.junit.Assert;
import org.junit.Test;
import org.twig.Environment;
import org.twig.exception.TwigRuntimeException;
import org.twig.template.Template;

public class RuntimeTemplateCompilerTests {
    @Test
    public void testCompileJavaCode() throws TwigRuntimeException {
        RuntimeTemplateCompiler runtimeCompiler = new RuntimeTemplateCompiler(new Environment());

        String sourceCode = "package org.twig.template;\n\n"
                + "public class TestTemplate extends org.twig.template.Template {\n"
                + "    protected String doRender(Context context) { return \"foo\"; }\n"
                + "    public String getTemplateName() { return \"foo\"; }\n"
                + "}\n";
        Template template = runtimeCompiler.compile(sourceCode, "org.twig.template.TestTemplate");

        Assert.assertEquals("Complied class method render() should return \"foo\"", "foo", template.render());
    }

    @Test(expected = TwigRuntimeException.class)
    public void testThrowsRuntimeErrorExceptionOnFailToCompile() throws TwigRuntimeException {
        RuntimeTemplateCompiler runtimeCompiler = new RuntimeTemplateCompiler(new Environment());

        String sourceCode = "invalid java code";

        runtimeCompiler.compile(sourceCode, "something");
    }
}

Fix failing runtime compiler tests

Fix failing runtime compiler tests


package training.taylor.timetracker.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import training.taylor.timetracker.core.dao.TimeEntry;

import java.util.List;

@Component
public class Tracker {
    @Autowired
    private List<TimeEntry> entries;

    public void add(TimeEntry entry) {
        entries.add(entry);
    }

    public void remove(TimeEntry entry) {
        entries.remove(entry);
    }

    public int size() {
        return entries.size();
    }

    public TimeEntry get(int index) {
        return entries.get(index);
    }
}

package training.taylor.timetracker.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import training.taylor.timetracker.core.dao.TimeEntry;

import java.util.List;

@Component
public class Tracker {
    @Autowired
    private List<TimeEntry> entries;

    public void add(TimeEntry entry) {
        entries.add(entry);
    }

    public void remove(TimeEntry entry) {
        if (true)
            entries.remove(entry);

        entries.remove(entry);
    }

    public int size() {
        return entries.size();
    }

    public TimeEntry get(int index) {
        try {

        } catch (Exception e) {

        }

        boolean valid = false;

        if (valid = true) {
            // whatever
        }

        return entries.get(index);
    }
}

Add back in violations to make things more interesting


package com.logicify.d2g.services;

import com.logicify.d2g.domain.User;
import com.logicify.d2g.dtos.incomingdtos.UserCreateIncomingDto;
import com.logicify.d2g.dtos.incomingdtos.UserUpdateIncomingDto;
import com.logicify.d2g.dtos.incomingdtos.UserUpdateStatusIncomingDto;
import com.logicify.d2g.dtos.outgoingdtos.UserOutgoingDto;
import com.logicify.d2g.dtos.outgoingdtos.UsersListOutgoingDto;
import com.logicify.d2g.utils.PasswordStorage;

import java.util.UUID;

/**
 * @author knorr
 */
public interface UserService {

    String createPasswordHash(String password) throws PasswordStorage.CannotPerformOperationException;

    void createUser(UserCreateIncomingDto userCreateIncomingDto) throws PasswordStorage.CannotPerformOperationException;

    UsersListOutgoingDto findAll();

    UserOutgoingDto findOne(UUID id);

    void delete(UUID id);

    void updateUser(UUID id, UserUpdateIncomingDto userUpdateIncomingDto) throws PasswordStorage.CannotPerformOperationException;

    void updateStatus(UUID id, UserUpdateStatusIncomingDto userUpdateStatusIncomingDto);

    /**
     * Returns user by it's UUID
     *
     * @param id user uuif
     * @return requested {@link User}
     */
     //TODO: Implement finding user by its uuid

}

package com.logicify.d2g.services;

import com.logicify.d2g.domain.User;
import com.logicify.d2g.dtos.domain.exceptions.ControllerException;
import com.logicify.d2g.dtos.incomingdtos.UserCreateIncomingDto;
import com.logicify.d2g.dtos.incomingdtos.UserUpdateIncomingDto;
import com.logicify.d2g.dtos.incomingdtos.UserUpdateStatusIncomingDto;
import com.logicify.d2g.dtos.outgoingdtos.UserOutgoingDto;
import com.logicify.d2g.dtos.outgoingdtos.UsersListOutgoingDto;

import java.util.UUID;

/**
 * @author knorr
 */
public interface UserService {

    String createPasswordHash(String password) throws  ControllerException;

    void createUser(UserCreateIncomingDto userCreateIncomingDto) throws ControllerException;

    UsersListOutgoingDto findAll();

    UserOutgoingDto findOne(UUID id) throws ControllerException;

    void delete(UUID id) throws ControllerException;

    void updateUser(UUID id, UserUpdateIncomingDto userUpdateIncomingDto) throws ControllerException;

    void updateStatus(UUID id, UserUpdateStatusIncomingDto userUpdateStatusIncomingDto);

    /**
     * Returns user by it's UUID
     *
     * @param id user uuif
     * @return requested {@link User}
     */
     //TODO: Implement finding user by its uuid

}

Create a custom exception type: Change service method signature for own exception class


package moe.akagi.chibaproject.card;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;

import it.gmariotti.cardslib.library.internal.Card;
import moe.akagi.chibaproject.R;
import moe.akagi.chibaproject.activity.PlaceDisplay;
import moe.akagi.chibaproject.datatype.Event;

/**
 * Created by a15 on 12/11/15.
 */
public class EventDetailInfo extends EventInfo {

    public EventDetailInfo(Context context, Event event) {
        super(context, R.layout.event_detail_info_content, event);
        this.addCardHeader(null);
        this.imageViewId = R.id.event_detail_info_image;
        this.timeViewId = R.id.event_detail_info_time;
        this.placeViewId = R.id.event_detail_info_place;
    }

    @Override
    public void setupInnerViewElements(ViewGroup parent, View view) {
        super.setupInnerViewElements(parent, view);
        showMapText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PlaceDisplay.actionStart(v.getContext(),location);
            }
        });
    }
}

package moe.akagi.chibaproject.card;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;

import moe.akagi.chibaproject.R;
import moe.akagi.chibaproject.activity.PlaceMapCreate;
import moe.akagi.chibaproject.activity.PlaceMapDisplay;
import moe.akagi.chibaproject.datatype.Event;
import moe.akagi.chibaproject.datatype.Location;

/**
 * Created by a15 on 12/11/15.
 */
public class EventDetailInfo extends EventInfo {

    public EventDetailInfo(Context context, Event event) {
        super(context, R.layout.event_detail_info_content, event);
        this.addCardHeader(null);
        this.imageViewId = R.id.event_detail_info_image;
        this.timeViewId = R.id.event_detail_info_time;
        this.placeViewId = R.id.event_detail_info_place;
    }

    @Override
    public void setupInnerViewElements(ViewGroup parent, View view) {
        super.setupInnerViewElements(parent, view);
        showMapText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                PlaceMapDisplay.actionStart(v.getContext(),new Location("Test Location",40,30,30.27,120.132));
                PlaceMapCreate.actionStart(v.getContext());
            }
        });
    }
}

Add click for map activity test

Add click for map activity test


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

package de.vorb.platon.web.rest;

import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.server.spring.scope.RequestContextFilter;
import org.junit.Test;

import java.util.Set;

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

public class RestResourceConfigTest {

    @Test
    public void testConstructor() throws Exception {

        final RestResourceConfig restResourceConfig = new RestResourceConfig();

        final Set<Class<?>> registeredClasses = restResourceConfig.getClasses();

        // assert that the correct resources and filters are registered
        assertThat(registeredClasses).containsExactly(
                RequestContextFilter.class,
                PoweredByResponseFilter.class,
                CommentResource.class,
                CommentCountResource.class,
                LoggingFilter.class,
                ObjectMapperContextResolver.class);

    }
}

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

package de.vorb.platon.web.rest;

import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.server.spring.scope.RequestContextFilter;
import org.junit.Test;

import java.util.Set;

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

public class RestResourceConfigTest {

    @Test
    public void testConstructor() throws Exception {

        final RestResourceConfig restResourceConfig = new RestResourceConfig();

        final Set<Class<?>> registeredClasses = restResourceConfig.getClasses();

        assertThat(registeredClasses).containsExactlyInAnyOrder(
                RequestContextFilter.class,
                PoweredByResponseFilter.class,
                CommentResource.class,
                CommentCountResource.class,
                LoggingFilter.class,
                ObjectMapperContextResolver.class);
    }
}

Allow registered classes to be in any order


package edu.washington.escience.myria.operator;

import edu.washington.escience.myria.Schema;
import edu.washington.escience.myria.TupleBatch;

/**
 * Implementation of set difference. Duplicates are not preserved.
 *
 * @author whitaker
 */
public class Difference extends BinaryOperator {

  /**
   * Instantiate a set difference operator.
   *
   * @param left the operator being subtracted from.
   * @param right the operator to be subtracted.
   */
  public Difference(final Operator left, final Operator right) {
    super(left, right);
  }

  /** Required for Java serialization. */
  private static final long serialVersionUID = 1L;

  @Override
  protected TupleBatch fetchNextReady() throws Exception {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  protected Schema generateSchema() {
    return getLeft().getSchema();
  }
}

package edu.washington.escience.myria.operator;

import com.google.common.collect.ImmutableMap;

import edu.washington.escience.myria.DbException;
import edu.washington.escience.myria.Schema;
import edu.washington.escience.myria.TupleBatch;

/**
 * Implementation of set difference. Duplicates are not preserved.
 *
 * @author whitaker
 */
public class Difference extends BinaryOperator {

  /**
   * Instantiate a set difference operator.
   *
   * @param left the operator being subtracted from.
   * @param right the operator to be subtracted.
   */
  public Difference(final Operator left, final Operator right) {
    super(left, right);
  }

  /** Required for Java serialization. */
  private static final long serialVersionUID = 1L;

  private TupleBatch processLeftChildTB(TupleBatch leftTB) {
    // TODO Auto-generated method stub
    return null;
  }

  private void processRightChildTB(TupleBatch rightTB) {

  }

  @Override
  protected TupleBatch fetchNextReady() throws Exception {
    final Operator right = getRight();

    /* Drain the right child. */
    while (!right.eos()) {
      TupleBatch rightTB = right.nextReady();
      if (rightTB == null) {
        if (right.eos()) {
          break;
        }
        return null;
      }
      processRightChildTB(rightTB);
    }

    final Operator left = getLeft();
    while (!left.eos()) {
      TupleBatch leftTB = left.nextReady();
      if (leftTB == null) {
        return null;
      }
      return processLeftChildTB(leftTB);
    }

    return null;
  }

  @Override
  protected Schema generateSchema() {
    return getLeft().getSchema();
  }

  @Override
  public void init(final ImmutableMap<String, Object> execEnvVars) throws DbException {
  }

  @Override
  protected void cleanup() throws DbException {
  }
}

Add some basic scaffolding for scanning input relations


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

package io.spine.query;

import com.google.errorprone.annotations.Immutable;

import java.util.function.UnaryOperator;

/**
 * A lambda serving to fill the current predicate {@linkplain QueryBuilder query builders}
 * with the parameters joined in {@linkplain LogicalOperator#OR disjunction}.
 */
@FunctionalInterface
@Immutable
public interface Either<B extends QueryBuilder<?, ?, ?, ?, ?>> extends UnaryOperator<B> {

}

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

package io.spine.query;

import com.google.errorprone.annotations.Immutable;

import java.util.function.UnaryOperator;

/**
 * A lambda serving to fill the current predicate {@linkplain QueryBuilder query builders}
 * with the parameters joined in {@linkplain LogicalOperator#OR disjunction}.
 */
@Immutable
@FunctionalInterface
public interface Either<B extends QueryBuilder<?, ?, ?, ?, ?>> extends UnaryOperator<B> {

}

Swap places the annotations to allow them to read together.


package com.thaiopensource.xml.util;

public final class Name {
  final private String namespaceUri;
  final private String localName;
  final private int hc;

  public Name(String namespaceUri, String localName) {
    this.namespaceUri = namespaceUri;
    this.localName = localName;
    this.hc = namespaceUri.hashCode() ^ localName.hashCode();
  }

  public String getNamespaceUri() {
    return namespaceUri;
  }

  public String getLocalName() {
    return localName;
  }

  public boolean equals(Object obj) {
    if (!(obj instanceof Name))
      return false;
    Name other = (Name)obj;
    return (this.hc == other.hc
	    && this.namespaceUri.equals(other.namespaceUri)
	    && this.localName.equals(other.localName));
  }

  public int hashCode() {
    return hc;
  }
}

package com.thaiopensource.xml.util;

public final class Name {
  final private String namespaceUri;
  final private String localName;
  final private int hc;

  public Name(String namespaceUri, String localName) {
    this.namespaceUri = namespaceUri;
    this.localName = localName;
    this.hc = namespaceUri.hashCode() ^ localName.hashCode();
  }

  public String getNamespaceUri() {
    return namespaceUri;
  }

  public String getLocalName() {
    return localName;
  }

  public boolean equals(Object obj) {
    if (!(obj instanceof Name))
      return false;
    Name other = (Name)obj;
    return (this.hc == other.hc
	    && this.namespaceUri.equals(other.namespaceUri)
	    && this.localName.equals(other.localName));
  }

  public int hashCode() {
    return hc;
  }

  // We include this, but don't derive from Comparator<Name> to avoid a dependency on Java 5.
  static public int compare(Name n1, Name n2) {
    int ret = n1.namespaceUri.compareTo(n2.namespaceUri);
    if (ret != 0)
      return ret;
    return n1.localName.compareTo(n2.localName);
  }
}

Add compare method from com.thaiopensource.relaxng.output.common.

git-svn-id: ca8e9bb6f3f9b50a093b443c23951d3c25ca0913@1968 369101cc-9a96-11dd-8e58-870c635edf7a


package com.holmsted.gerrit;

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

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

import com.holmsted.json.JsonUtils;

public class GerritStatParser {

    public List<Commit> parseCommits(String jsonCommitData) {
        List<Commit> commits = new ArrayList<>();
        String[] lines = jsonCommitData.split("\n");
        for (String line : lines) {
            try {
                JSONObject lineJson = JsonUtils.readJsonString(line);
                if (Commit.isCommit(lineJson)) {
                    commits.add(Commit.fromJson(lineJson));
                } else {
                    // TODO ignore for now
                    System.err.println("Ignored line " + line);
                }
            } catch (JSONException ex) {
                System.err.println(String.format("Not JsonObject: '%s'", line));
            }
        }

        return commits;
    }
}

package com.holmsted.gerrit;

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

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

import com.holmsted.json.JsonUtils;

public class GerritStatParser {

    public List<Commit> parseCommits(String jsonCommitData) {
        List<Commit> commits = new ArrayList<>();
        String[] lines = jsonCommitData.split("\n");
        for (String line : lines) {
            try {
                JSONObject lineJson = JsonUtils.readJsonString(line);
                if (Commit.isCommit(lineJson)) {
                    commits.add(Commit.fromJson(lineJson));
                // ignore the stats, log the rest in case the format changes
                } else if (!lineJson.get("type").equals("stats")) {
                    System.err.println("Ignored line " + line);
                }
            } catch (JSONException ex) {
                System.err.println(String.format("Not JsonObject: '%s'", line));
            }
        }

        return commits;
    }
}

Remove the noisy "Ignored line" messages for stats that are not used


package com.csforge.sstable;

import com.google.common.base.Strings;

import java.io.File;
import java.util.Arrays;

public class Driver {
    public static void main(String ... args) {
        if (args.length == 0) {
            printCommands();
            System.exit(-1);
        }
        switch(args[0].toLowerCase()) {
            case "tojson":
                SSTable2Json.main(Arrays.copyOfRange(args, 1, args.length));
                break;

            case "cqlsh":
                Cqlsh.main(Arrays.copyOfRange(args, 1, args.length));
                break;

            case "describe":
                String path = new File(args[1]).getAbsolutePath();
                try {
                    System.out.println("\u001B[1;34m" + path);
                    System.out.println(TableTransformer.ANSI_CYAN + Strings.repeat("=", path.length()));
                    System.out.print(TableTransformer.ANSI_RESET);
                    CassandraUtils.printStats(path, System.out);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;

            default:
                System.err.println("Unknown command: " + args[0]);
                printCommands();
                System.exit(-2);
                break;
        }
    }

    private static void printCommands() {
        System.err.println("Available commands: cqlsh, toJson, select, describe");
    }
}

package com.csforge.sstable;

import com.google.common.base.Strings;

import java.io.File;
import java.util.Arrays;

public class Driver {
    public static void main(String ... args) {
        if (args.length == 0) {
            printCommands();
            System.exit(-1);
        }
        switch(args[0].toLowerCase()) {
            case "tojson":
                SSTable2Json.main(Arrays.copyOfRange(args, 1, args.length));
                break;

            case "cqlsh":
                Cqlsh.main(Arrays.copyOfRange(args, 1, args.length));
                break;

            case "describe":
                String path = new File(args[1]).getAbsolutePath();
                try {
                    System.out.println("\u001B[1;34m" + path);
                    System.out.println(TableTransformer.ANSI_CYAN + Strings.repeat("=", path.length()));
                    System.out.print(TableTransformer.ANSI_RESET);
                    CassandraUtils.printStats(path, System.out);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;

            default:
                System.err.println("Unknown command: " + args[0]);
                printCommands();
                System.exit(-2);
                break;
        }
    }

    private static void printCommands() {
        System.err.println("Available commands: cqlsh, toJson, describe");
    }
}

Remove select from command list.

Remove select from command list.