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

/**
 * Created by nate on 4/10/16.
 */
public abstract class Model {
    private Connection c;

    public Model() {
        try {
            c = DriverManager.getConnection("jdbc:sqlite:data.db");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public Model(Connection c) {
        this.c = c;
    }
}

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

/**
 * Created by nate on 4/10/16.
 */
public abstract class Model {
    protected Connection c;

    public Model() {
        try {
            c = DriverManager.getConnection("jdbc:sqlite:data.db");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public Model(Connection c) {
        this.c = c;
    }
}

Update visibility of connection in model


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

import com.yahoo.slime.Slime;

/**
 * A 200 ok response with a message in JSON.
 *
 * @author bratseth
 */
public class MessageResponse extends SlimeJsonResponse {

    public MessageResponse(String message) {
        super(slime(message));
    }

    private static Slime slime(String message) {
        var slime = new Slime();
        slime.setObject().setString("message", message);
        return slime;
    }

}

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

import com.yahoo.slime.Slime;

/**
 * A 200 ok response with a message in JSON.
 *
 * @author bratseth
 */
public class MessageResponse extends SlimeJsonResponse {

    public MessageResponse(String message) {
        super(slime(message));
    }

    public MessageResponse(int statusCode, String message) {
        super(statusCode, slime(message));
    }

    private static Slime slime(String message) {
        var slime = new Slime();
        slime.setObject().setString("message", message);
        return slime;
    }

}

Add constructor also taking status code

Add constructor also taking status code


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

/**
 * @author Andrew Shvayka
 */
public enum EntityType {
    TENANT, TENANT_PROFILE, CUSTOMER, USER, DASHBOARD, ASSET, DEVICE, DEVICE_PROFILE, ALARM, RULE_CHAIN, RULE_NODE, ENTITY_VIEW, WIDGETS_BUNDLE, WIDGET_TYPE
}

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

/**
 * @author Andrew Shvayka
 */
public enum EntityType {
    TENANT, CUSTOMER, USER, DASHBOARD, ASSET, DEVICE, ALARM, RULE_CHAIN, RULE_NODE, ENTITY_VIEW, WIDGETS_BUNDLE, WIDGET_TYPE, TENANT_PROFILE, DEVICE_PROFILE
}

Move device/tenant profile entitiy type enums to the end of list.


package com.blocksolid.okrello.display;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Dan Buckland on 02/12/2015.
 */
public class Scores {
    public String extractScoreFromString(String string) {
        Pattern pattern = Pattern.compile("\\[(\\d{1}\\.\\d{1})\\]");
        Matcher m = pattern.matcher(string);
        if (m.find()) {
            String score = m.group(1);
            double value = Double.parseDouble(score);
            if (value > 1) {
                return "1.0";
            } else {
                return score;
            }
        } else {
            return "!";
        }
    }

    public String removeScoreFromString(String string) {
        return "";
    }
}

package com.blocksolid.okrello.display;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Dan Buckland on 02/12/2015.
 */
public class Scores {
    public String extractScoreFromString(String string) {
        Pattern pattern = Pattern.compile("\\[(\\d{1}\\.\\d{1})\\]");
        Matcher m = pattern.matcher(string);
        if (m.find()) {
            String score = m.group(1);
            double value = Double.parseDouble(score);
            if (value > 1) {
                return "1.0";
            } else {
                return score;
            }
        } else {
            return "!";
        }
    }

    public String removeScoreFromString(String string) {
        string = string.replaceAll("\\[\\d{1}\\.\\d{1}\\]", "").trim();
        return string;
    }
}

Complete removeScoreFromString method to pass unit tests


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.lomatek.jslint;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import org.openide.loaders.DataObject;

import org.openide.awt.ActionRegistration;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionID;
import org.openide.util.NbBundle.Messages;

import org.openide.util.RequestProcessor;

@ActionID(category = "Build",
id = "org.lomatek.jslint.JSLintSample")
@ActionRegistration(displayName = "#CTL_JSLintSample")
@ActionReferences({
    @ActionReference(path = "Editors/text/javascript/Popup", position = 300)
})
@Messages("CTL_JSLintSample=JSLintSample")
public final class JSLintSample implements ActionListener {

    static RequestProcessor processor = null;

    private final DataObject context;

    public JSLintSample(DataObject context) {
	this.context = context;
    }

    public void actionPerformed(ActionEvent ev) {
	// TODO use context
	if (processor == null) {
            processor = new RequestProcessor("TidyErrorCheck", 1, true);
        }
        processor.post(new JSLintRunnable(context, "-e"));
    }
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.lomatek.jslint;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import org.openide.loaders.DataObject;

import org.openide.awt.ActionRegistration;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionID;
import org.openide.util.NbBundle.Messages;

import org.openide.util.RequestProcessor;

@ActionID(category = "Build",
id = "org.lomatek.jslint.JSLintSample")
@ActionRegistration(displayName = "#CTL_JSLintSample")
@ActionReferences({
    @ActionReference(path = "Editors/text/javascript/Popup", position = 300)
})
@Messages("CTL_JSLintSample=JSLintSample")
public final class JSLintSample implements ActionListener {

    static RequestProcessor processor = null;

    private final DataObject context;

    public JSLintSample(DataObject context) {
	this.context = context;
    }

    public void actionPerformed(ActionEvent ev) {
	// TODO use context
	if (processor == null) {
            processor = new RequestProcessor("TidyErrorCheck", 1, true);
        }
        processor.post(new JSLintRunnableB(context, "-e"));
    }
}

Change Runable function to RunableB

Change Runable function to RunableB


package com.royalrangers.controller;

import com.royalrangers.dto.ResponseResult;
import com.royalrangers.dto.user.EmailDto;
import com.royalrangers.service.SubscribeService;
import com.royalrangers.utils.ResponseBuilder;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/subscribe")
public class SubscribeController {

    @Autowired
    private SubscribeService subscribeService;

    @PostMapping
    @ApiOperation(value = "Create subscriber")
    public ResponseResult subscribe(@RequestBody EmailDto request) {

        String email = request.getMail();
        log.info("Add subscriber: " + email);
        try {
            subscribeService.add(email);
            return ResponseBuilder.success(String.format("Email %s added to subscribers list", email));
        } catch (Exception e) {
            return ResponseBuilder.fail(e.getMessage());
        }
    }

    @DeleteMapping
    @ApiOperation(value = "Delete subscriber")
    public ResponseResult unsubscribe(@RequestBody EmailDto request) {

        String email = request.getMail();
        log.info("Remove subscriber: " + email);
        try {
            subscribeService.remove(email);
            return ResponseBuilder.success(String.format("Email %s removed from subscribers list", email));
        } catch (Exception e) {
            return ResponseBuilder.fail(e.getMessage());
        }
    }
}

package com.royalrangers.controller;

import com.royalrangers.dto.ResponseResult;
import com.royalrangers.dto.user.EmailDto;
import com.royalrangers.service.SubscribeService;
import com.royalrangers.utils.ResponseBuilder;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/subscribe")
public class SubscribeController {

    @Autowired
    private SubscribeService subscribeService;

    @PostMapping
    @ApiOperation(value = "Add email to subscribers list")
    public ResponseResult subscribe(@RequestBody EmailDto request) {

        String email = request.getMail();
        log.info("Add subscriber: " + email);
        try {
            subscribeService.add(email);
            return ResponseBuilder.success(String.format("Email %s added to subscribers list", email));
        } catch (Exception e) {
            return ResponseBuilder.fail(e.getMessage());
        }
    }

    @DeleteMapping
    @ApiOperation(value = "Remove email from subscribers list")
    public ResponseResult unsubscribe(@RequestBody EmailDto request) {

        String email = request.getMail();
        log.info("Remove subscriber: " + email);
        try {
            subscribeService.remove(email);
            return ResponseBuilder.success(String.format("Email %s removed from subscribers list", email));
        } catch (Exception e) {
            return ResponseBuilder.fail(e.getMessage());
        }
    }
}

Fix API description for Subscribe Controller


package org.jetbrains.plugins.groovy.util;

import com.intellij.util.containers.ConcurrentHashMap;
import org.jetbrains.annotations.NotNull;

/**
 * @author Sergey Evdokimov
 */
public class ClassInstanceCache {

  private static final ConcurrentHashMap<String, Object> CACHE = new ConcurrentHashMap<String, Object>();

  private ClassInstanceCache() {
  }

  @SuppressWarnings("unchecked")
  public static <T> T getInstance(@NotNull String className, ClassLoader classLoader) {
    Object res = CACHE.get(className);
    if (res == null) {
      try {
        res = classLoader.loadClass(className).newInstance();
      }
      catch (Exception e) {
        throw new RuntimeException(e);
      }

      Object oldValue = CACHE.putIfAbsent(className, res);
      if (oldValue != null) {
        res = oldValue;
      }
    }

    return (T)res;
  }
}

package org.jetbrains.plugins.groovy.util;

import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.util.containers.ConcurrentHashMap;
import org.jetbrains.annotations.NotNull;

/**
 * @author Sergey Evdokimov
 */
public class ClassInstanceCache {

  private static final ConcurrentHashMap<String, Object> CACHE = new ConcurrentHashMap<String, Object>();

  private ClassInstanceCache() {
  }

  private static Object createInstance(@NotNull String className) {
    try {
      try {
        return Class.forName(className).newInstance();
      }
      catch (ClassNotFoundException e) {
        for (IdeaPluginDescriptor descriptor : PluginManager.getPlugins()) {
          try {
            return descriptor.getPluginClassLoader().loadClass(className).newInstance();
          }
          catch (ClassNotFoundException ignored) {

          }
        }

        throw new RuntimeException("Class not found: " + className);
      }
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  @SuppressWarnings("unchecked")
  public static <T> T getInstance(@NotNull String className, ClassLoader classLoader) {
    Object res = CACHE.get(className);
    if (res == null) {
      res = createInstance(className);

      Object oldValue = CACHE.putIfAbsent(className, res);
      if (oldValue != null) {
        res = oldValue;
      }
    }

    return (T)res;
  }

}

Revert: Improve class loading in GroovyMethodInfo. (cf9bf0e)


package com.github.aureliano.edocs.service.bean;

public class UserServiceBean implements IServiceBean {

}

package com.github.aureliano.edocs.service.bean;

import com.github.aureliano.edocs.common.exception.ServiceException;
import com.github.aureliano.edocs.domain.entity.User;

public class UserServiceBean implements IServiceBean {

	public UserServiceBean() {}

	public User createDatabaseUser(String name, String password) {
		throw new ServiceException("Not implemented yet.");
	}

	public User saveUser(User user) {
		throw new ServiceException("Not implemented yet.");
	}

	public boolean isValidCredential(String name, String passwor) {
		throw new ServiceException("Not implemented yet.");
	}

	public void deleteUser(User user) {
		throw new ServiceException("Not implemented yet.");
	}

	public User findUserById(Integer id) {
		throw new ServiceException("Not implemented yet.");
	}
}

Add user service methods signatures.

Add user service methods signatures.


package uk.ac.ebi.biosamples.repos;

import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import uk.ac.ebi.biosamples.models.NeoSample;

@RepositoryRestResource(path="samplesrelations",collectionResourceRel="samplesrelations",itemResourceRel="samplerelations")
public interface ReadOnlyNeoSampleRepository extends ReadOnlyGraphRepository<NeoSample> {

}

package uk.ac.ebi.biosamples.repos;

import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;

import uk.ac.ebi.biosamples.models.NeoSample;

@RepositoryRestResource(path="samplesrelations",collectionResourceRel="samplesrelations",itemResourceRel="samplerelations", exported=true)
//docs say one or the toher should be sufficient, but seems that you do need both
@RestResource(path="samplesrelations",exported=true)
public interface ReadOnlyNeoSampleRepository extends ReadOnlyGraphRepository<NeoSample> {

}

Fix for exporting via REST

Fix for exporting via REST


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

package com.lynn9388.rmichatroom.rmi;

import java.io.Serializable;

public class User implements Serializable {
    private static final long serialVersionUID = 148606460530002054L;

    private String username;
    private String ip;
    private String port;
    private String remoteName;

    public User(String username, String ip, String port, String remoteName) {
        this.username = username;
        this.ip = ip;
        this.port = port;
        this.remoteName = remoteName;
    }

    public String getUsername() {
        return username;
    }

    public String getIp() {
        return ip;
    }

    public String getPort() {
        return port;
    }

    public String getRemoteName() {
        return remoteName;
    }
}

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

package com.lynn9388.rmichatroom.rmi;

import java.io.Serializable;

public class User implements Serializable {
    private static final long serialVersionUID = 8116975872176331171L;
    private String username;
    private String ip;
    private int port;
    private String remoteName;

    public User(String username, String ip, int port, String remoteName) {
        this.username = username;
        this.ip = ip;
        this.port = port;
        this.remoteName = remoteName;
    }

    public String getUsername() {
        return username;
    }

    public String getIp() {
        return ip;
    }

    public int getPort() {
        return port;
    }

    public String getRemoteName() {
        return remoteName;
    }
}

Change user's port value style

Change user's port value style


package net.emteeware.emteeseason;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import static net.emteeware.emteeseason.R.id.SeriesList;

public class MainActivity extends AppCompatActivity {

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

        ListView listview = (ListView) findViewById(R.id.SeriesList);

        String[] items = new String[] {"Blue Bloods", "Marvel's Daredevil", "Suits"};
        ArrayAdapter<String> adapter =
                new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);

        listview.setAdapter(adapter);
    }
}

package net.emteeware.emteeseason;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

import static net.emteeware.emteeseason.R.id.SeriesList;

public class MainActivity extends AppCompatActivity {

    ArrayList<String> items = new ArrayList<>();
    ArrayAdapter<String> adapter;

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

        items.add( "Suits");
        ListView listview = (ListView) findViewById(R.id.SeriesList);

        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);

        listview.setAdapter(adapter);
    }

    public void addItems(View view) {
        items.add("Blue Bloods");
        items.add("Sherlock");
        adapter.notifyDataSetChanged();
    }
}

Add new items when button is pressed

Add new items when button is pressed


package net.squanchy.search.engines;

import java.text.Normalizer;
import java.util.Locale;
import java.util.regex.Pattern;

final class StringNormalizer {

    private static final String EMPTY_STRING = "";
    private static final String ACCENTS_PATTERN_STRING = "\\p{M}";
    private static final Pattern ACCENTS_PATTERN = Pattern.compile(ACCENTS_PATTERN_STRING);

    static String normalize(String text) {
        String lowercasedText = lowercase(text);
        return removeDiacritics(lowercasedText);
    }

    private static String lowercase(String text) {
        return text.toLowerCase(Locale.getDefault());
    }

    private static String removeDiacritics(String text) {
        String normalised = Normalizer.normalize(text, Normalizer.Form.NFD);
        return ACCENTS_PATTERN.matcher(normalised).replaceAll(EMPTY_STRING);
    }
}

package net.squanchy.search.engines;

import java.text.Normalizer;
import java.util.Locale;
import java.util.regex.Pattern;

final class StringNormalizer {

    private static final String ACCENTS_PATTERN_STRING = "\\p{M}";
    private static final Pattern ACCENTS_PATTERN = Pattern.compile(ACCENTS_PATTERN_STRING);
    private static final String EMPTY_STRING = "";

    static String normalize(String text) {
        String lowercasedText = lowercase(text);
        return removeDiacritics(lowercasedText);
    }

    private static String lowercase(String text) {
        return text.toLowerCase(Locale.ROOT);
    }

    private static String removeDiacritics(String text) {
        String normalised = Normalizer.normalize(text, Normalizer.Form.NFD);
        return ACCENTS_PATTERN.matcher(normalised).replaceAll(EMPTY_STRING);
    }
}

Use root locale when normalising

Use root locale when normalising


/*
 * Copyright 2000-2016 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * See LICENSE in the project root for license information.
 */

package jetbrains.buildServer.dnx.test;

import jetbrains.buildServer.agent.ToolProvider;
import jetbrains.buildServer.agent.impl.ToolProvidersRegistryImpl;
import jetbrains.buildServer.dnx.DnxToolProvider;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * @author Dmitry.Tretyakov
 *         Date: 1/15/2016
 *         Time: 12:50 AM
 */
public class DnxToolProviderTest {

    @Test
    public void testGetPath() throws Exception {
        final ToolProvider toolProvider = new DnxToolProvider(new ToolProvidersRegistryImpl());
        final String dnuPath = toolProvider.getPath("dnu");

        System.out.print(dnuPath);

        Assert.assertNotNull(dnuPath);
    }

    @Test
    public void testSupport() throws Exception {
        final ToolProvider toolProvider = new DnxToolProvider(new ToolProvidersRegistryImpl());
        Assert.assertTrue(toolProvider.supports("dnu"));
    }
}

/*
 * Copyright 2000-2016 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * See LICENSE in the project root for license information.
 */

package jetbrains.buildServer.dnx.test;

import jetbrains.buildServer.agent.ToolCannotBeFoundException;
import jetbrains.buildServer.agent.ToolProvider;
import jetbrains.buildServer.agent.impl.ToolProvidersRegistryImpl;
import jetbrains.buildServer.dnx.DnxToolProvider;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.File;

/**
 * @author Dmitry.Tretyakov
 *         Date: 1/15/2016
 *         Time: 12:50 AM
 */
public class DnxToolProviderTest {

    @Test
    public void testGetPath() {
        final ToolProvider toolProvider = new DnxToolProvider(new ToolProvidersRegistryImpl());
        String dnuPath = null;
        ToolCannotBeFoundException exception = null;

        try {
            dnuPath = toolProvider.getPath("dnu");
        } catch (ToolCannotBeFoundException e) {
            exception = e;
        }

        final String userHome = System.getProperty("user.home");
        final File dnxDirectory = new File(userHome, ".dnx");

        if (dnxDirectory.exists()){
            Assert.assertNotNull(dnuPath, "DNU path should not be null");
            Assert.assertTrue(new File(dnuPath).exists(), "DNU should exists");
        } else {
            Assert.assertNotNull(exception, "Should be thrown dnu not found exception");
        }
    }

    @Test
    public void testSupport() throws Exception {
        final ToolProvider toolProvider = new DnxToolProvider(new ToolProvidersRegistryImpl());
        Assert.assertTrue(toolProvider.supports("dnu"));
    }
}

Fix assertion in dnu discovery test

Fix assertion in dnu discovery test


package me.jesensky.dan.playertracker.net;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

public final class NetUtils {
    private NetUtils(){
    }

    public static byte[] byteListToArray(List<Byte> bytes){
        byte[] b = new byte[bytes.size()];
        for(int i = 0; i < b.length; i++)
            b[i] = bytes.get(i);
        return b;
    }

    public static byte[] getMD5Hash(byte[] b){
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(b);
            return md5.digest();
        }catch(NoSuchAlgorithmException e){
            //ignore, md5 is always there
        }
        return null;
    }

    public static byte[] stringToBytes(String s){
        try {
            return s.getBytes("UTF-8");
        }catch(UnsupportedEncodingException e){
            //if your computer does not have UTF-8, there's something severely wrong with it, or you're running windows 95.
        }
        return null;
    }
}

package me.jesensky.dan.playertracker.net;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

public final class NetUtils {
    private NetUtils(){
    }

    public static byte[] byteListToArray(List<Byte> bytes){
        byte[] b = new byte[bytes.size()];
        for(int i = 0; i < b.length; i++)
            b[i] = bytes.get(i);
        return b;
    }

    public static byte[] getMD5Hash(byte[] b){
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(b);
            return md5.digest();
        }catch(NoSuchAlgorithmException e){
            //ignore, md5 is always there
        }
        return null;
    }

    public static byte[] stringToBytes(String s){
        try {
            return s.getBytes("UTF-8");
        }catch(UnsupportedEncodingException e){
            //if your computer does not have UTF-8, there's something severely wrong with it, or you're running windows 95.
        }
        return null;
    }

    public static String byteToString(byte[] b){
        try{
            return new String(b, "UTF-8");
        }catch(UnsupportedEncodingException e){
            //stop running windows 95
        }
        return null;
    }
}

Add utility of bytes to string in netutils


package co.paralleluniverse.firebase;

//~--- non-JDK imports --------------------------------------------------------

import co.paralleluniverse.fibers.SuspendExecution;

import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.Query;

/**
 * This class exposes Firebase functionality that builds on top of the fiber
 * model.
 */
public enum FirebaseUtil {
  INSTANCE;

  /**
   * Retrieves the Firebase server time based off of the local server time
   * offset.
   *
   * @param  ref an authenticated Firebase reference.
   *
   * @return the Firebase server time.
   */
  public long serverTime(Firebase ref) throws SuspendExecution {
    return System.currentTimeMillis() + serverTimeOffset(ref);
  }

  public long serverTimeOffset(Firebase ref) throws SuspendExecution {
    DataSnapshot snap = QuasarUtil.INSTANCE.run(new ValueEventListenerAsync() {
      @Override
      protected void requestAsync() {
        Query query = ref.getRoot().child(".info/serverTimeOffset");

        query.addListenerForSingleValueEvent(this);
      }
    });

    return (Long) snap.getValue();
  }
}

package co.paralleluniverse.firebase;

//~--- non-JDK imports --------------------------------------------------------

import co.paralleluniverse.fibers.SuspendExecution;

import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.Query;

/**
 * This class exposes Firebase functionality that builds on top of the fiber
 * model.
 */
public enum FirebaseUtil {
  INSTANCE;

  /**
   * Retrieves the Firebase server time based off of the local server time
   * offset.
   *
   * @param  ref an authenticated Firebase reference.
   *
   * @return the Firebase server time.
   *
   * @throws SuspendExecution
   */
  public long serverTime(Firebase ref) throws SuspendExecution {
    return System.currentTimeMillis() + serverTimeOffset(ref);
  }

  /**
   * Retrieves the local server time offset.
   *
   * @param  ref an authenticated Firebase reference.
   *
   * @return the local server time offset.
   *
   * @throws SuspendExecution
   */
  public long serverTimeOffset(Firebase ref) throws SuspendExecution {
    DataSnapshot snap = QuasarUtil.INSTANCE.run(new ValueEventListenerAsync() {
      @Override
      protected void requestAsync() {
        Query query = ref.getRoot().child(".info/serverTimeOffset");

        query.addListenerForSingleValueEvent(this);
      }
    });

    return (Long) snap.getValue();
  }
}

Add throws to the javadoc

Add throws to the javadoc


package org.spoofax.jsglr2.actions;

import org.spoofax.jsglr2.characters.ICharacters;
import org.spoofax.jsglr2.parsetable.IProduction;
import org.spoofax.jsglr2.parsetable.ProductionType;

public class Reduce extends Action implements IReduce {

    private final IProduction production;
    private final ProductionType productionType;
    private final int arity;

    public Reduce(ICharacters characters, IProduction production, ProductionType productionType, int arity) {
        super(characters);

        this.production = production;
        this.productionType = productionType;
        this.arity = arity;

        /*
         * NOTE: according to Eduardo, the type of the action and of the production should match for types REJECT /
         * PREFER / AVOID at least. There seems to be a bug in the parse table generator.
         */
        assert !(productionType == ProductionType.REJECT || productionType == ProductionType.PREFER
            || productionType == ProductionType.AVOID) || productionType == production.productionType();

        assert !(production.productionType() == ProductionType.REJECT
            || production.productionType() == ProductionType.PREFER
            || production.productionType() == ProductionType.AVOID) || production.productionType() == productionType;
    }

    public IProduction production() {
        return production;
    }

    public ProductionType productionType() {
        return productionType;
    }

    public int arity() {
        return arity;
    }

}

package org.spoofax.jsglr2.actions;

import org.spoofax.jsglr2.characters.ICharacters;
import org.spoofax.jsglr2.parsetable.IProduction;
import org.spoofax.jsglr2.parsetable.ProductionType;

public class Reduce extends Action implements IReduce {

    private final IProduction production;
    private final ProductionType productionType;
    private final int arity;

    public Reduce(ICharacters characters, IProduction production, ProductionType productionType, int arity) {
        super(characters);

        this.production = production;
        this.productionType = productionType;
        this.arity = arity;

        /*
         * NOTE: according to Eduardo, the type of the action and of the production should match for types REJECT /
         * PREFER / AVOID at least. There seems to be a bug in the parse table generator. If this bug is fixed the
         * asserts below should succeed (they are failing now).
         *
         * assert !(productionType == ProductionType.REJECT || productionType == ProductionType.PREFER || productionType
         * == ProductionType.AVOID) || productionType == production.productionType();
         *
         * assert !(production.productionType() == ProductionType.REJECT || production.productionType() ==
         * ProductionType.PREFER || production.productionType() == ProductionType.AVOID) || production.productionType()
         * == productionType;
         */
    }

    public IProduction production() {
        return production;
    }

    public ProductionType productionType() {
        return productionType;
    }

    public int arity() {
        return arity;
    }

}

Disable failing asserts due to parser generator bug


package org.verapdf.model.tools;

import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSObject;

/**
 * Created by Evgeniy Muravitskiy on 4/27/15.
 *

 * This class specified for creating ID`s for every object from model.
 */
public final class IDGenerator {

    private IDGenerator(){}

    /**
     * Generate ID for pdf box object. Current method generate a string of the form 'N M' for
     * {@link org.apache.pdfbox.cos.COSObject}, where 'N' and 'M' are numbers, and null
     * for other pdf box objects
     * @param pdfBoxObject object of pdf box library
     * @return string representation of ID
     */
    public static String generateID(COSBase pdfBoxObject) {
        if (pdfBoxObject instanceof COSObject) {
            return ((COSObject) pdfBoxObject).getObjectNumber() + " " + ((COSObject) pdfBoxObject).getGenerationNumber();
        }
        return null;
    }
}

package org.verapdf.model.tools;

import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSObject;

/**
 * Created by Evgeniy Muravitskiy on 4/27/15.
 *

 * This class specified for creating ID`s for every object from model.
 */
public final class IDGenerator {

    private IDGenerator(){}

    /**
     * Generate ID for pdf box object. Current method generate a string of the form 'N M' for
     * {@link org.apache.pdfbox.cos.COSObject}, where 'N' and 'M' are numbers, and null
     * for other pdf box objects
     * @param pdfBoxObject object of pdf box library
     * @return string representation of ID
     */
    public static String generateID(COSBase pdfBoxObject) {
        if (pdfBoxObject instanceof COSObject) {
            return ((COSObject) pdfBoxObject).getObjectNumber() + " " + ((COSObject) pdfBoxObject).getGenerationNumber();
        } else {
            return null;
        }
    }
}

Change working principle of id generating


/*
 * Copyright 2013 MovingBlocks
 *
 * 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.terasology.utilities.gson;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import org.terasology.input.Input;
import org.terasology.input.InputType;

import java.lang.reflect.Type;

/**
 * @author Immortius
 */
public class InputHandler implements JsonSerializer<Input>, JsonDeserializer<Input> {

    @Override
    public Input deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return InputType.parse(json.getAsString());
    }

    @Override
    public JsonElement serialize(Input src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src.toString());
    }
}

/*
 * Copyright 2013 MovingBlocks
 *
 * 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.terasology.utilities.gson;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import org.terasology.input.Input;
import org.terasology.input.InputType;

import java.lang.reflect.Type;

/**
 * @author Immortius
 */
public class InputHandler implements JsonSerializer<Input>, JsonDeserializer<Input> {

    @Override
    public Input deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return InputType.parse(json.getAsString().replace(" ", "_"));
    }

    @Override
    public JsonElement serialize(Input src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src.toString());
    }
}

Fix to input handler to support space -> underscore conversion.


/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software License
 * version 1.1, a copy of which has been included with this distribution in
 * the LICENSE file.
 */
package org.apache.james.services;

import java.util.Iterator;

import org.apache.avalon.phoenix.Service;

/**
 * Interface for Phoenix blocks to access a store of Users. A UserStore
 * contains one or more UserRepositories. Multiple UserRepositories may or may
 * not have overlapping membership.
 *
 * @version 1.0.0, 24/04/1999
 * @author  Federico Barbieri <scoobie@pop.systemy.it>
 * @author Charles Benett
 */
public interface UsersStore
    extends Service {

    String ROLE = "org.apache.james.services.UsersStore";

    UsersRepository getRepository( String name );

    Iterator getRepositoryNames();
}

/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software License
 * version 1.1, a copy of which has been included with this distribution in
 * the LICENSE file.
 */
package org.apache.james.services;

import java.util.Iterator;

/**
 * Interface for Phoenix blocks to access a store of Users. A UserStore
 * contains one or more UserRepositories. Multiple UserRepositories may or may
 * not have overlapping membership.
 *
 * @version 1.0.0, 24/04/1999
 * @author  Federico Barbieri <scoobie@pop.systemy.it>
 * @author Charles Benett
 */
public interface UsersStore {

    String ROLE = UsersStore.class.getName();

    UsersRepository getRepository( String name );

    Iterator getRepositoryNames();
}

Remove reference to long deprecated Service interface.

git-svn-id: de9d04cf23151003780adc3e4ddb7078e3680318@107893 13f79535-47bb-0310-9956-ffa450edef68


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

import io.netty.util.internal.PlatformDependent;
import org.junit.Test;

import java.lang.reflect.Method;

public class ShadingIT {

    @Test
    public void testShadingNativeTransport() throws Exception {
        testShading0(PlatformDependent.isOsx() ? "io.netty.channel.kqueue.KQueue" : "io.netty.channel.epoll.Epoll");
    }

    @Test
    public void testShadingTcnative() throws Exception {
        testShading0("io.netty.handler.ssl.OpenSsl");
    }

    private static void testShading0(String classname) throws Exception {
        String shadingPrefix = System.getProperty("shadingPrefix");
        final Class<?> clazz = Class.forName(shadingPrefix + '.' + classname);
        Method method = clazz.getMethod("ensureAvailability");
        method.invoke(null);
    }
}

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

import io.netty.util.internal.PlatformDependent;
import org.junit.Ignore;
import org.junit.Test;

import java.lang.reflect.Method;

public class ShadingIT {

    @Test
    public void testShadingNativeTransport() throws Exception {
        testShading0(PlatformDependent.isOsx() ? "io.netty.channel.kqueue.KQueue" : "io.netty.channel.epoll.Epoll");
    }

    @Ignore("Figure out why this sometimes fail on the CI")
    @Test
    public void testShadingTcnative() throws Exception {
        testShading0("io.netty.handler.ssl.OpenSsl");
    }

    private static void testShading0(String classname) throws Exception {
        String shadingPrefix = System.getProperty("shadingPrefix");
        final Class<?> clazz = Class.forName(shadingPrefix + '.' + classname);
        Method method = clazz.getMethod("ensureAvailability");
        method.invoke(null);
    }
}

Disable test as it sometimes fails on the CI

Motivation:

Temporary disable test that wwas introduced as part of f60d08fd32b7287f65077f99a88bac645834098f as it sometimes fail on the CI. We need to figure out why it fails there (can not reproduce so far even on the CI after ssh into it).

Modifications:

Ignore test.

Result:

More stable builds until we figure out the flackyness.


package com.paritytrading.parity.client.command;

import com.paritytrading.parity.client.TerminalClient;
import java.util.Scanner;

class HelpCommand implements Command {

    @Override
    public void execute(TerminalClient client, Scanner arguments) throws CommandException {
        if (arguments.hasNext()) {
            Command command = Commands.find(arguments.next());

            if (arguments.hasNext())
                throw new CommandException();

            if (command != null)
                displayCommandHelp(client, command);
            else
                displayGeneralHelp(client);
        } else {
            displayGeneralHelp(client);
        }
    }

    private void displayGeneralHelp(TerminalClient client) {
        client.printf("Commands:\n");

        int maxCommandNameLength = calculateMaxCommandNameLength();

        for (Command command : Commands.all())
            client.printf("  %-" + maxCommandNameLength + "s  %s\n", command.getName(), command.getDescription());

        client.printf("\nType 'help <command>' for command specific help.\n");
    }

    private void displayCommandHelp(TerminalClient client, Command command) {
        client.printf("Usage: %s\n\n  %s\n\n", command.getUsage(), command.getDescription());
    }

    private int calculateMaxCommandNameLength() {
        return Commands.all().collectInt(c -> c.getName().length()).max();
    }

    @Override
    public String getName() {
        return "help";
    }

    @Override
    public String getDescription() {
        return "Display the help";
    }

    @Override
    public String getUsage() {
        return "help [command]";
    }

}

package com.paritytrading.parity.client.command;

import com.paritytrading.parity.client.TerminalClient;
import java.util.Scanner;

class HelpCommand implements Command {

    @Override
    public void execute(TerminalClient client, Scanner arguments) throws CommandException {
        if (arguments.hasNext()) {
            Command command = Commands.find(arguments.next());

            if (arguments.hasNext())
                throw new CommandException();

            if (command != null)
                displayCommandHelp(client, command);
            else
                displayGeneralHelp(client);
        } else {
            displayGeneralHelp(client);
        }
    }

    private void displayGeneralHelp(TerminalClient client) {
        client.printf("Commands:\n");

        int maxCommandNameLength = calculateMaxCommandNameLength();

        for (Command command : Commands.all())
            client.printf("  %-" + maxCommandNameLength + "s  %s\n", command.getName(), command.getDescription());

        client.printf("\nType 'help <command>' for command specific help.\n");
    }

    private void displayCommandHelp(TerminalClient client, Command command) {
        client.printf("Usage: %s\n\n  %s\n\n", command.getUsage(), command.getDescription());
    }

    private int calculateMaxCommandNameLength() {
        return Commands.names().collectInt(String::length).max();
    }

    @Override
    public String getName() {
        return "help";
    }

    @Override
    public String getDescription() {
        return "Display the help";
    }

    @Override
    public String getUsage() {
        return "help [command]";
    }

}

parity-client: Simplify command name length calculation


// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security;

import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;

/**
 * @author bjorncs
 */
public enum KeyStoreType {
    JKS {
        KeyStore createKeystore() throws KeyStoreException {
            return KeyStore.getInstance("JKS");
        }
    },
    PKCS12 {
        KeyStore createKeystore() throws KeyStoreException {
            return KeyStore.getInstance("PKCS12", BouncyCastleProviderHolder.getInstance());
        }
    };
    abstract KeyStore createKeystore() throws GeneralSecurityException;
}

// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security;

import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;

/**
 * @author bjorncs
 */
public enum KeyStoreType {
    JKS {
        KeyStore createKeystore() throws KeyStoreException {
            return KeyStore.getInstance("BKS", BouncyCastleProviderHolder.getInstance());
        }
    },
    PKCS12 {
        KeyStore createKeystore() throws KeyStoreException {
            return KeyStore.getInstance("PKCS12", BouncyCastleProviderHolder.getInstance());
        }
    };
    abstract KeyStore createKeystore() throws GeneralSecurityException;
}

Use BouncyCastle as provider for JKS keystore

Fixes an issue where KeyStoreBuilder fails to handle elliptic-curve crypto on older versions of OpenJDK


package com.codemagic.powerhour;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class Dashboard extends Activity {

    Preferences myPrefs;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);
        myPrefs = new Preferences(this);
    }

    // method to start playing random songs -- maybe add timer info here
    public void startPlaying(View v) {
        Toast.makeText(v.getContext(), "Clicked!", Toast.LENGTH_SHORT).show();

    }

    public void saveOpts(View v) {

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.dashboard, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

package com.codemagic.powerhour;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class Dashboard extends Activity {

    Preferences myPrefs;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);
        myPrefs = new Preferences(this);
    }

    // method to start playing random songs -- maybe add timer info here
    public void startPlaying(View v) {
        Toast.makeText(v.getContext(), "Clicked!", Toast.LENGTH_SHORT).show();

    }

    // will save to the preferences or send directly to timer class
    public void saveOpts(View v) {

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.dashboard, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Comment for info of save btn

Comment for info of save btn


package edu.northwestern.bioinformatics.studycalendar.dao;

import edu.northwestern.bioinformatics.studycalendar.domain.Source;

import java.util.List;

public class SourceDao extends StudyCalendarMutableDomainObjectDao<Source> {
    public Class<Source> domainClass() {
        return Source.class;
    }

    public List<Source> getAll()  {
        return getHibernateTemplate().find("from Source order by name");
    }

    public Source getByName(String name) {
        List<Source> sources = getHibernateTemplate().find("from Source where name = ?", name);
        if (!sources.isEmpty()) {
            return sources.get(0);
        }
        return null;
    }
}

package edu.northwestern.bioinformatics.studycalendar.dao;

import edu.northwestern.bioinformatics.studycalendar.domain.Source;

import java.util.List;

public class SourceDao extends StudyCalendarMutableDomainObjectDao<Source> {
    public Class<Source> domainClass() {
        return Source.class;
    }

    /**
     * Finds all the activity sources available
     *
     * @return      a list of all the available activity sources
     */
    public List<Source> getAll()  {
        return getHibernateTemplate().find("from Source order by name");
    }

    /**
     * Finds all the actiivty sources for the given activity source name
     *
     * @param  name the name of the activity source to search for
     * @return      the source that was found for the given activity source name
     */
    public Source getByName(String name) {
        List<Source> sources = getHibernateTemplate().find("from Source where name = ?", name);
        if (!sources.isEmpty()) {
            return sources.get(0);
        }
        return null;
    }
}

Add javadoc to source dao.

Add javadoc to source dao.


package com.redhat.chrometwo.api.services;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;

import com.redhat.chrometwo.api.persistence.dao.AccountDao;
import com.redhat.chrometwo.api.security.SecurityInterceptor;

@Path("/accounts")
@Stateless
@LocalBean
public class AccountWS {

    @EJB
    private AccountDao accountDao;

    @GET
    @Path("/{accountId}")
    public String getAccount(@PathParam("accountId") String accountId,
    						  @Context HttpServletRequest request) throws Exception {
    	// Lookey test code remove me:
    	System.out.println(accountDao.doSomeBackendFunction());
    	System.out.println(request.getAttribute(SecurityInterceptor.ACCOUNT_ID));
    	System.out.println(request.getAttribute(SecurityInterceptor.USER_ID));
    	System.out.println(request.getAttribute(SecurityInterceptor.IS_INTERNAL));

        return "woot88: account: " + request.getAttribute(SecurityInterceptor.ACCOUNT_ID)
            + " id: " + request.getAttribute(SecurityInterceptor.USER_ID)
            + " internal: " + request.getAttribute(SecurityInterceptor.IS_INTERNAL);
    }
}

package com.redhat.chrometwo.api.services;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;

import com.redhat.chrometwo.api.persistence.dao.AccountDao;
import com.redhat.chrometwo.api.security.SecurityInterceptor;

@Path("/accounts")
@Stateless
@LocalBean
public class AccountWS {

    @EJB
    private AccountDao accountDao;

    @GET
    @Path("/{accountId}")
    public String getAccount(@PathParam("accountId") String accountId,
    						  @Context HttpServletRequest request) throws Exception {
    	// Lookey test code remove me:
    	System.out.println(accountDao.doSomeBackendFunction());
    	System.out.println(request.getAttribute(SecurityInterceptor.ACCOUNT_ID));
    	System.out.println(request.getAttribute(SecurityInterceptor.USER_ID));
    	System.out.println(request.getAttribute(SecurityInterceptor.IS_INTERNAL));

        return "woot 88";
    }
}

Revert "work around EJB's not working"

Revert "work around EJB's not working"

This reverts commit 5436a3e18ae816f62f80db7e5fa8a4b3ec18f6ae.


package org.asg.report;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class CleanJob implements Job {

	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		App.statuses.clear();
	}

}

package org.asg.report;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class CleanJob implements Job {

	private final static Logger LOGGER = Logger.getLogger(CleanJob.class);

	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		App.statuses.clear();
		LOGGER.info("Status Queue was just cleared");
	}

}

Add logging to status queue clearing

Add logging to status queue clearing


package kr.ac.kaist.se.tardis.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;

public class ExceptionHandlingController implements ErrorController {

	@ResponseStatus(code=HttpStatus.NOT_FOUND)
	public String notFound(){
		return "errorpage";
	}

	@ResponseStatus(code=HttpStatus.FORBIDDEN)
	@RequestMapping("error")
	public String forbidden(){
		return "errorpage";
	}

	@Override
	public String getErrorPath() {
		return "/error";
	}
}

package kr.ac.kaist.se.tardis.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;

@Controller
public class ExceptionHandlingController implements ErrorController {

	@ResponseStatus(code=HttpStatus.NOT_FOUND)
	public String notFound(){
		return "errorpage";
	}

	@ResponseStatus(code=HttpStatus.FORBIDDEN)
	@RequestMapping("error")
	public String forbidden(){
		return "errorpage";
	}

	@Override
	public String getErrorPath() {
		return "/error";
	}
}

Fix controller annotation on Error

Fix controller annotation on Error


package cgeo.geocaching.test;

import cgeo.geocaching.geopoint.GeopointParser;
import junit.framework.Assert;
import android.test.AndroidTestCase;

public class GeoPointParserTest extends AndroidTestCase {

    public void testParseLatitude() throws Throwable {

    	Assert.assertEquals(49.0 + 56.031 / 60.0, GeopointParser.parseLatitude("N 49° 56.031"));
    }

    public void testParseLongitude() throws Throwable {

    	Assert.assertEquals(8.0 + 38.564 / 60.0, GeopointParser.parseLongitude("E 8° 38.564"));
    }
}

package cgeo.geocaching.test;

import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.geopoint.GeopointParser;
import junit.framework.Assert;
import android.test.AndroidTestCase;

public class GeoPointParserTest extends AndroidTestCase {

	private static final double refLongitude = 8.0 + 38.564 / 60.0;
	private static final double refLatitude = 49.0 + 56.031 / 60.0;

	public void testParseLatitude() throws Throwable {

		Assert.assertEquals(refLatitude, GeopointParser.parseLatitude("N 49° 56.031"), 1e-8);
	}

	public void testParseLongitude() throws Throwable {

		Assert.assertEquals(refLongitude, GeopointParser.parseLongitude("E 8° 38.564"), 1e-8);
	}

	public void testFullCoordinates() throws Throwable {
		final Geopoint goal = new Geopoint(refLatitude, refLongitude);
		Assert.assertTrue(goal.isEqualTo(GeopointParser.parse("N 49° 56.031 | E 8° 38.564"), 1e-6));
	}

	public void testSouth() throws Throwable {
		Assert.assertEquals(-refLatitude, GeopointParser.parseLatitude("S 49° 56.031"), 1e-8);
	}

	public void testWest() throws Throwable {
		Assert.assertEquals(-refLongitude, GeopointParser.parseLongitude("W 8° 38.564"), 1e-8);
	}

	public void testLowerCase() throws Throwable {
		Assert.assertEquals(refLongitude, GeopointParser.parseLongitude("e 8° 38.564"), 1e-8);
	}
}

Add more tests for GeopointParser

Add more tests for GeopointParser


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

import org.jetbrains.annotations.NotNull;

public class RollDetails {
    private final long cycle;
    private final long epoch;

    public RollDetails(long cycle, long epoch) {
        this.cycle = cycle;
        this.epoch = epoch;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof RollDetails)) return false;
        @NotNull RollDetails rollDetails = (RollDetails) o;
        return cycle == rollDetails.cycle && epoch == rollDetails.epoch;
    }

    @Override
    public int hashCode() {
        int result = (int) (cycle ^ (cycle >>> 32));
        result = 31 * result + (int) (epoch ^ (epoch >>> 32));
        return result;
    }
}

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

import net.openhft.chronicle.wire.AbstractMarshallable;

public class RollDetails extends AbstractMarshallable {
    final long cycle;
    final long epoch;

    public RollDetails(long cycle, long epoch) {
        this.cycle = cycle;
        this.epoch = epoch;
    }
}

Use extends AbstractMarshallable in more places.


package eu.netide.lib.netip;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.projectfloodlight.openflow.protocol.OFMessage;

/**
 * Class representing a message of type OPENFLOW.
 * Note that this only serves as a convenience class - if the MessageType is manipulated, the class will not recognize that.
 */
public class OpenFlowMessage extends Message {
    private OFMessage ofMessage;

    /**
     * Instantiates a new Open flow message.
     */
    public OpenFlowMessage() {
        super(new MessageHeader(), new byte[0]);
        header.setMessageType(MessageType.OPENFLOW);
    }

    /**
     * Gets of message.
     *
     * @return the of message
     */
    public OFMessage getOfMessage() {
        return ofMessage;
    }

    /**
     * Sets of message.
     *
     * @param ofMessage the of message
     */
    public void setOfMessage(OFMessage ofMessage) {
        this.ofMessage = ofMessage;
    }

    @Override
    public byte[] getPayload() {
        ChannelBuffer dcb = ChannelBuffers.dynamicBuffer();
        ofMessage.writeTo(dcb);
        this.payload = dcb.array();
        return this.payload;
    }

    @Override
    public String toString() {
        return "OpenFlowMessage [Header=" + header.toString() + ",Type=" + ofMessage.getType().toString() + ",OFMessage=" + ofMessage.toString() + "]";
    }
}

package eu.netide.lib.netip;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.projectfloodlight.openflow.protocol.OFMessage;

/**
 * Class representing a message of type OPENFLOW.
 * Note that this only serves as a convenience class - if the MessageType is manipulated, the class will not recognize that.
 */
public class OpenFlowMessage extends Message {
    private OFMessage ofMessage;

    /**
     * Instantiates a new Open flow message.
     */
    public OpenFlowMessage() {
        super(new MessageHeader(), new byte[0]);
        header.setMessageType(MessageType.OPENFLOW);
    }

    /**
     * Gets of message.
     *
     * @return the of message
     */
    public OFMessage getOfMessage() {
        return ofMessage;
    }

    /**
     * Sets of message.
     *
     * @param ofMessage the of message
     */
    public void setOfMessage(OFMessage ofMessage) {
        this.ofMessage = ofMessage;
    }

    @Override
    public byte[] getPayload() {
        ChannelBuffer dcb = ChannelBuffers.dynamicBuffer();
        ofMessage.writeTo(dcb);
        this.payload = new byte[dcb.readableBytes()];
        dcb.readBytes(this.payload, 0, this.payload.length);
        return this.payload;
    }

    @Override
    public String toString() {
        return "OpenFlowMessage [Header=" + header.toString() + ",Type=" + ofMessage.getType().toString() + ",OFMessage=" + ofMessage.toString() + "]";
    }
}

Fix OpenFlow packets getting stuffed with \0 bytes.


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

package io.reactivex.internal.util;

import static org.junit.Assert.*;
import org.junit.Test;

public class OpenHashSetTest {

    static class Value {

        @Override
        public int hashCode() {
            return 1;
        }

    }

    @Test
    public void addRemoveCollision() {
        Value v1 = new Value();
        Value v2 = new Value();

        OpenHashSet<Value> set = new OpenHashSet<Value>();

        assertTrue(set.add(v1));

        assertFalse(set.add(v1));

        assertFalse(set.remove(v2));

        assertTrue(set.add(v2));

        assertFalse(set.add(v2));

        assertTrue(set.remove(v2));

        assertFalse(set.remove(v2));
    }
}

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

package io.reactivex.internal.util;

import static org.junit.Assert.*;
import org.junit.Test;

public class OpenHashSetTest {

    static class Value {

        @Override
        public int hashCode() {
            return 1;
        }

        @Override
        public boolean equals(Object o) {
            return this == o;
        }
    }

    @Test
    public void addRemoveCollision() {
        Value v1 = new Value();
        Value v2 = new Value();

        OpenHashSet<Value> set = new OpenHashSet<Value>();

        assertTrue(set.add(v1));

        assertFalse(set.add(v1));

        assertFalse(set.remove(v2));

        assertTrue(set.add(v2));

        assertFalse(set.add(v2));

        assertTrue(set.remove(v2));

        assertFalse(set.remove(v2));
    }
}

Add equals() to the unit test to satisfy checkstyle


package com.adaptc.mws.plugins;

/**
 * Represents the current state of a plugin.
 * @author bsaville
 */
public enum PluginState {
	/**
	 * The plugin is created and ready for use, but is not
	 * currently receiving any events
	 */
	STOPPED("Stopped"),
	/**
	 * The plugin is currently receiving events and is working
	 * correctly.
	 */
	STARTED("Started"),
	/**
	 * The plugin is currently not receiving any events but is
	 * also not stopped.
	 *

	 * This should be used when polling or other events should
	 * stop only temporarily without firing the stop events.
	 */
	PAUSED("Paused"),
	/**
	 * MWS has detected an error with the plugin and has automatically
	 * stopped it.  Errors could be due to the following reasons:

	 *

	 *
An invalid configuration was detected when running the
	 * {@link AbstractPlugin#configure} method.
	 *
An unexpected exception was thrown during an event, such
	 * as during polling.
	 *

	 */
	ERRORED("Errored");

	private String str;
	private PluginState(String str) {
		this.str = str;
	}

	/**
	 * Returns a human-readable string of the state, such as "Paused" for {@link #PAUSED}.
	 * @return A human-readable string
	 */
	@Override
	public String toString() {
		return str;
	}
}

Fix documentation for plugin state

Fix documentation for plugin state


package fi.nls.oskari.control.users;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;

/**
 * Handles user's password reseting
 */
@Controller
public class UserController {

    private final static Logger log = LogFactory.getLogger(UserController.class);

    public UserController() {

    }

    @RequestMapping("/resetPassword/{uuid}")
    public String getMap(Model model, @ModelAttribute String uuid) {
         System.out.println("Test2");
         return null;
    }

}

package fi.nls.oskari.control.users;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;

/**
 * Handles user's password reseting
 */
@Controller
public class UserController {

    private final static Logger log = LogFactory.getLogger(UserController.class);

    public UserController() {

    }

    /**
     * "passwordReset" jsp view should ALWAYS be used by user to reset password
     * @param model
     * @param uuid
     * @return
     */
    @RequestMapping("/resetPassword/{uuid}")
    public String resetPassword(
    		Model model,
    		@ModelAttribute String uuid) {

         return "passwordReset";
    }

}

Return view is set to 'resetPassword'.

Return view is set to 'resetPassword'.


package io.github.vcuswimlab.stackintheflow.controller;

import io.github.vcuswimlab.stackintheflow.model.JerseyGet;
import io.github.vcuswimlab.stackintheflow.model.JerseyResponse;
import io.github.vcuswimlab.stackintheflow.model.Query;

/**
 * Created by Chase on 1/5/2017.
 */
public class QueryExecutor {

    private final static String filter = "!-MOiNm40F1U019gR)UUjNV-IQScciBJZ0";

    public static JerseyResponse executeQuery(String q) {
        return executeQuery(new Query("stackoverflow")
                .set(Query.Component.Q, q)
                .set(Query.Component.FILTER, filter)
                .set(Query.Component.SORT, JerseyGet.SortType.RELEVANCE.toString()));
    }

    public static JerseyResponse executeQuery(String q, JerseyGet.SortType sortType) {
        return executeQuery(new Query("stackoverflow")
                .set(Query.Component.Q, q)
                .set(Query.Component.FILTER, filter)
                .set(Query.Component.SORT, sortType.toString()));
    }

    public static JerseyResponse executeQuery(Query q) {
        return executeQuery(q, JerseyGet.SearchType.ADVANCED);
    }

    public static JerseyResponse executeQuery(Query q, JerseyGet.SearchType searchType) {
        return JerseyGet.getInstance().executeQuery(q, searchType);
    }
}

package io.github.vcuswimlab.stackintheflow.controller;

import io.github.vcuswimlab.stackintheflow.model.JerseyGet;
import io.github.vcuswimlab.stackintheflow.model.JerseyResponse;
import io.github.vcuswimlab.stackintheflow.model.Query;

/**
 * Created by Chase on 1/5/2017.
 */
public class QueryExecutor {

    private final static String filter = "!-MOiNm40F1U019gR)UUjNV-IQScciBJZ0";

    public static JerseyResponse executeQuery(String q) {
        return executeQuery(q, JerseyGet.SortType.RELEVANCE);
    }

    public static JerseyResponse executeQuery(String q, JerseyGet.SortType sortType) {
        return executeQuery(new Query("stackoverflow")
                .set(Query.Component.Q, q)
                .set(Query.Component.FILTER, filter)
                .set(Query.Component.SORT, sortType.toString()));
    }

    public static JerseyResponse executeQuery(Query q) {
        return executeQuery(q, JerseyGet.SearchType.ADVANCED);
    }

    public static JerseyResponse executeQuery(Query q, JerseyGet.SearchType searchType) {
        return JerseyGet.getInstance().executeQuery(q, searchType);
    }
}

Clean up execute query methods.

Clean up execute query methods.


package absyn;

import env.Env;
import javaslang.collection.Tree;
import parse.Loc;
import semantic.SemanticHelper;
import types.Type;

public class DecVar extends Dec {

   public final String name;
   public final String typeName;
   public final Exp init;

   public DecVar(Loc loc, String name, String typeName, Exp init) {
      super(loc);
      this.name = name;
      this.typeName = typeName;
      this.init = init;
   }

   @Override
   public Tree.Node<String> toTree() {
      return Tree.of("DecVar",
                     Tree.of(name),
                     Tree.of(typeName),
                     init.toTree());
   }

   @Override
   public void semantic(Env env) {
      Type t_init = init.semantic(env);
      Type t_var = t_init;
      if (typeName != null) {
         Type t_typeName = env.tenv.get(typeName);
         if (t_typeName == null)
            throw SemanticHelper.undefined(loc, "type", typeName);
         if (!t_init.is(t_typeName))
            throw SemanticHelper.typeMismatch(init.loc, t_init, t_typeName);
         t_var = t_typeName;
      }
      env.venv.put(name, t_var);
   }
}

package absyn;

import env.Env;
import javaslang.collection.List;
import javaslang.collection.Tree;
import parse.Loc;
import semantic.SemanticHelper;
import types.Type;

public class DecVar extends Dec {

   public final String name;
   public final String typeName;
   public final Exp init;

   public DecVar(Loc loc, String name, String typeName, Exp init) {
      super(loc);
      this.name = name;
      this.typeName = typeName;
      this.init = init;
   }

   @Override
   public Tree.Node<String> toTree() {
      List<Tree.Node<String>> children = List.of(Tree.of(name));
      if (typeName != null)
         children = children.append(Tree.of(typeName));
      children = children.append(init.toTree());
      return Tree.of("DecVar", children);
   }

   @Override
   public void semantic(Env env) {
      Type t_init = init.semantic(env);
      Type t_var = t_init;
      if (typeName != null) {
         Type t_typeName = env.tenv.get(typeName);
         if (t_typeName == null)
            throw SemanticHelper.undefined(loc, "type", typeName);
         if (!t_init.is(t_typeName))
            throw SemanticHelper.typeMismatch(init.loc, t_init, t_typeName);
         t_var = t_typeName;
      }
      env.venv.put(name, t_var);
   }
}

Fix toTree method for variable declarations

The type name of the variable may be missing.


package org.wildfly.apigen.test.model;

import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
import org.wildfly.apigen.test.AbstractTestCase;
import org.wildfly.apigen.model.AddressTemplate;
import org.wildfly.apigen.model.DefaultStatementContext;
import org.wildfly.apigen.model.ResourceDescription;
import org.wildfly.apigen.operations.ReadDescription;

/**
 * Verifies the Model API helper classes and it usage
 *
 * @author Heiko Braun
 * @since 29/07/15
 */
public class ModelAPITestCase extends AbstractTestCase {

    @Test
    public void testResourceDescriptionParsing() throws Exception {
        AddressTemplate address = AddressTemplate.of("/subsystem=datasources/data-source=*");
        ReadDescription op = new ReadDescription(address);

        ModelNode response = client.execute(op.resolve(new DefaultStatementContext()));
        ResourceDescription description = ResourceDescription.from(response);

        Assert.assertNotNull(description.getText());
        Assert.assertEquals(57, description.getAttributes().size());
    }
}

package org.wildfly.apigen.test.model;

import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
import org.wildfly.apigen.test.AbstractTestCase;
import org.wildfly.apigen.model.AddressTemplate;
import org.wildfly.apigen.model.DefaultStatementContext;
import org.wildfly.apigen.model.ResourceDescription;
import org.wildfly.apigen.operations.ReadDescription;

/**
 * Verifies the Model API helper classes and it usage
 *
 * @author Heiko Braun
 * @since 29/07/15
 */
public class ModelAPITestCase extends AbstractTestCase {

    @Test
    public void testResourceDescriptionParsing() throws Exception {
        AddressTemplate address = AddressTemplate.of("/subsystem=datasources/data-source=*");
        ReadDescription op = new ReadDescription(address);

        ModelNode response = client.execute(op.resolve(new DefaultStatementContext()));
        ResourceDescription description = ResourceDescription.from(response);

        Assert.assertNotNull(description.getText());
        Assert.assertEquals(59, description.getAttributes().size());
    }
}

Update expected number of attributes in datasource test for WF10


package com.thaiopensource.resolver;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.io.IOException;

/**
 *
 */
public class BasicResolver implements Resolver {
  static private final BasicResolver theInstance = new BasicResolver();

  protected BasicResolver() {
  }

  public static BasicResolver getInstance() {
    return theInstance;
  }

  public void resolve(Identifier id, Input input) throws IOException, ResolverException {
    if (!input.isResolved())
      input.setUri(resolveUri(id));
  }

  public void open(Input input) throws IOException, ResolverException {
    if (!input.isUriDefinitive())
      return;
    URI uri;
    try {
      uri = new URI(input.getUri());
    }
    catch (URISyntaxException e) {
      throw new ResolverException(e);
    }
    if (!uri.isAbsolute())
      throw new ResolverException("cannot open relative URI: " + uri);
    URL url = new URL(uri.toASCIIString());
    // XXX should set the encoding properly
    input.setByteStream(url.openStream());
  }

  public static String resolveUri(Identifier id) throws ResolverException {
    try {
      URI uri = new URI(id.getUriReference());
      String base = id.getBase();
      if (base != null)
        uri = new URI(base).resolve(uri);
      return uri.toString();
    }
    catch (URISyntaxException e) {
      throw new ResolverException(e);
    }
  }
}

package com.thaiopensource.resolver;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.io.IOException;

/**
 *
 */
public class BasicResolver implements Resolver {
  static private final BasicResolver theInstance = new BasicResolver();

  protected BasicResolver() {
  }

  public static BasicResolver getInstance() {
    return theInstance;
  }

  public void resolve(Identifier id, Input input) throws IOException, ResolverException {
    if (!input.isResolved())
      input.setUri(resolveUri(id));
  }

  public void open(Input input) throws IOException, ResolverException {
    if (!input.isUriDefinitive())
      return;
    URI uri;
    try {
      uri = new URI(input.getUri());
    }
    catch (URISyntaxException e) {
      throw new ResolverException(e);
    }
    if (!uri.isAbsolute())
      throw new ResolverException("cannot open relative URI: " + uri);
    URL url = new URL(uri.toASCIIString());
    // XXX should set the encoding properly
    // XXX if this is HTTP and we've been redirected, should do input.setURI with the new URI
    input.setByteStream(url.openStream());
  }

  public static String resolveUri(Identifier id) throws ResolverException {
    try {
      URI uri = new URI(id.getUriReference());
      String base = id.getBase();
      if (base != null)
        uri = new URI(base).resolve(uri);
      return uri.toString();
    }
    catch (URISyntaxException e) {
      throw new ResolverException(e);
    }
  }
}

Add note that we need to handle HTTP redirection


package org.endeavourhealth.hl7receiver;

import org.endeavourhealth.core.data.config.ConfigManagerException;
import org.endeavourhealth.hl7receiver.hl7.HL7Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Main {

	private static final String PROGRAM_DISPLAY_NAME = "EDS HL7 receiver";
	private static final Logger LOG = LoggerFactory.getLogger(Main.class);

	public static void main(String[] args) {
		try {
            Configuration configuration = Configuration.getInstance();

		    LOG.info("--------------------------------------------------");
            LOG.info(PROGRAM_DISPLAY_NAME);
            LOG.info("--------------------------------------------------");

			HL7Service serviceManager = new HL7Service(configuration);
            serviceManager.start();

            LOG.info("Press any key to exit...");

            System.in.read();

            LOG.info("Shutting down...");
            serviceManager.stop();

            LOG.info("Shutdown");
            System.exit(0);

        } catch (ConfigManagerException cme) {
            System.err.println("Fatal exception occurred initializing ConfigManager [" + cme.getClass().getName() + "] " + cme.getMessage());
		    LOG.error("Fatal exception occurred initializing ConfigManager", cme);
            System.exit(-2);
        }
        catch (Exception e) {
			LOG.error("Fatal exception occurred", e);
			System.exit(-1);
		}
	}
}

package org.endeavourhealth.hl7receiver;

import org.endeavourhealth.core.data.config.ConfigManagerException;
import org.endeavourhealth.hl7receiver.hl7.HL7Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Main {

	private static final String PROGRAM_DISPLAY_NAME = "EDS HL7 receiver";
	private static final Logger LOG = LoggerFactory.getLogger(Main.class);

	private static HL7Service serviceManager;

	public static void main(String[] args) {
		try {
            Configuration configuration = Configuration.getInstance();

		    LOG.info("--------------------------------------------------");
            LOG.info(PROGRAM_DISPLAY_NAME);
            LOG.info("--------------------------------------------------");

			HL7Service serviceManager = new HL7Service(configuration);
            serviceManager.start();

            LOG.info("Started succesfully...");

            Runtime.getRuntime().addShutdownHook(new Thread(() -> shutdown()));

        } catch (ConfigManagerException cme) {
            printToErrorConsole("Fatal exception occurred initializing ConfigManager", cme);
		    LOG.error("Fatal exception occurred initializing ConfigManager", cme);
            System.exit(-2);
        }
        catch (Exception e) {
			LOG.error("Fatal exception occurred", e);
			System.exit(-1);
		}
	}

	private static void shutdown() {
	    try {
            LOG.info("Shutting down...");

            if (serviceManager != null)
                serviceManager.stop();

	    } catch (Exception e) {
            printToErrorConsole("Exception occurred during shutdown", e);
	        LOG.error("Exception occurred during shutdown", e);
        }
    }

    private static void printToErrorConsole(String message, Exception e) {
        System.err.println(message + " [" + e.getClass().getName() + "] " + e.getMessage());
    }
}

Change main thread to support upstart

Change main thread to support upstart


package com.github.jmchilton.blend4j.galaxy.beans;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown=true)
public class HistoryDetails extends History {
  private String state;

  public String getState() {
    return state;
  }

  public void setState(String state) {
    this.state = state;
  }

}

package com.github.jmchilton.blend4j.galaxy.beans;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown=true)
public class HistoryDetails extends History {
  private String state;
  private Map<String, List<String>> stateIds = new HashMap<String, List<String>>();

  public String getState() {
    return state;
  }

  public void setState(String state) {
    this.state = state;
  }

  @JsonProperty("state_ids")
  public void setStateIds(final Map<String, List<String>> stateIds) {
    this.stateIds = stateIds;
  }

  public Map<String, List<String>> getStateIds() {
    return stateIds;
  }

}

Add property to get state map from histories, figure out which HDAs are in what state - ok, failed, etc....


package org.realityforge.replicant.example.server.service.tyrell.replicate;

import java.util.List;
import javax.annotation.Nonnull;
import org.realityforge.replicant.server.EntityMessage;
import org.realityforge.replicant.server.json.JsonEncoder;

public final class Packet
{
  private final int _sequence;
  @Nonnull
  private final List<EntityMessage> _changes;

  public Packet( final int sequence, @Nonnull final List<EntityMessage> changes )
  {
    _sequence = sequence;
    _changes = changes;
  }

  public int getSequence()
  {
    return _sequence;
  }

  @Nonnull
  public List<EntityMessage> getChanges()
  {
    return _changes;
  }

  public String toJson()
  {
    return JsonEncoder.encodeChangeSetFromEntityMessages( getSequence(), _changes );
  }
}

package org.realityforge.replicant.example.server.service.tyrell.replicate;

import java.util.List;
import javax.annotation.Nonnull;
import org.realityforge.replicant.server.EntityMessage;
import org.realityforge.replicant.server.json.JsonEncoder;

public final class Packet
{
  private final int _sequence;
  @Nonnull
  private final List<EntityMessage> _changes;

  public Packet( final int sequence, @Nonnull final List<EntityMessage> changes )
  {
    _sequence = sequence;
    _changes = changes;
  }

  public int getSequence()
  {
    return _sequence;
  }

  @Nonnull
  public List<EntityMessage> getChanges()
  {
    return _changes;
  }

  public String toJson()
  {
    return JsonEncoder.encodeChangeSetFromEntityMessages( getSequence(), getChanges() );
  }
}

Use accessor to do encoding

Use accessor to do encoding


package study.hard.javalib.nativelib;

public class GetClassTest {

	public static void main(String[] args) {
		GetClassTest tester = new GetClassTest();
		ExtendedClassA extendedA = tester.new ExtendedClassA();
		extendedA.printClass(); // class study.hard.javalib.nativelib.GetClassTest$ExtendedClassA

		Class<? extends ClassA> clazz = extendedA.getClass();
		System.out.println(clazz.getName());
	}

	public class ClassA {
		public void printThisClass() {
			System.out.println(getClass());
		}
	}

	public class ExtendedClassA extends ClassA {
		public void printClass() {
			printThisClass();
		}
	}

}

package study.hard.javalib.nativelib;

public class GetClassTest {

	public static void main(String[] args) {
		GetClassTest tester = new GetClassTest();
		ExtendedClassA extendedA = tester.new ExtendedClassA();
		extendedA.printClass(); // class study.hard.javalib.nativelib.GetClassTest$ExtendedClassA

		Class<? extends ClassA> clazz1 = extendedA.getClass();
		System.out.println(clazz1.getName());

		Class<? extends ClassA> clazz2 = ExtendedClassA.class;
		System.out.println(clazz2.getName());

		System.out.println(clazz1 == clazz2);
	}

	public class ClassA {
		public void printThisClass() {
			System.out.println(getClass());
		}
	}

	public class ExtendedClassA extends ClassA {
		public void printClass() {
			printThisClass();
		}
	}

}

Add a test case to check identity of result of getClass() and classname.class.


/**
 * Copyright 2010-2012 Ralph Schaer <ralphschaer@gmail.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 ch.ralscha.extdirectspring.demo;

import ch.rasc.embeddedtc.EmbeddedTomcat;

public class RunDemoOnTomcat {

	public static void main(String[] args) {
		EmbeddedTomcat.create().addDependencyAsResourceJar("resources", "sencha-touch-gpl").startAndWait();
	}
}

/**
 * Copyright 2010-2012 Ralph Schaer <ralphschaer@gmail.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 ch.ralscha.extdirectspring.demo;

import ch.rasc.embeddedtc.EmbeddedTomcat;

public class RunDemoOnTomcat {

	public static void main(String[] args) {
		EmbeddedTomcat.create().startAndWait();
	}
}

Remove resource jar handling. Works now out of the box with latest Tomcat


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

package com.linecorp.armeria.client.http;

import com.linecorp.armeria.common.util.Version;

import io.netty.util.AsciiString;

final class HttpHeaderUtil {

    private static final String CLIENT_ARTIFACT_ID = "armeria";

    static final AsciiString USER_AGENT = AsciiString.of(createUserAgentName());

    static String hostHeader(String host, int port, int defaultPort) {
        if (port == defaultPort) {
            return host;
        }

        return new StringBuilder(host.length() + 6).append(host).append(':').append(port).toString();
    }

    private static String createUserAgentName() {
        Version version = Version.identify().get(CLIENT_ARTIFACT_ID);
        return CLIENT_ARTIFACT_ID + '/' + (version != null ? version.artifactId() : "unknown");
    }

    private HttpHeaderUtil() {}
}

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

package com.linecorp.armeria.client.http;

import com.linecorp.armeria.common.util.Version;

import io.netty.util.AsciiString;

final class HttpHeaderUtil {

    private static final String CLIENT_ARTIFACT_ID = "armeria";

    static final AsciiString USER_AGENT = AsciiString.of(createUserAgentName());

    static String hostHeader(String host, int port, int defaultPort) {
        if (port == defaultPort) {
            return host;
        }

        return new StringBuilder(host.length() + 6).append(host).append(':').append(port).toString();
    }

    private static String createUserAgentName() {
        final Version version = Version.identify(HttpHeaderUtil.class.getClassLoader())
                                       .get(CLIENT_ARTIFACT_ID);

        return CLIENT_ARTIFACT_ID + '/' + (version != null ? version.artifactVersion() : "unknown");
    }

    private HttpHeaderUtil() {}
}

Fix missing version information in user-agent header

Motivation:

HttpClient sends the 'user-agent' header with incorrect version
information. It's sending artifactId instead of artifactVersion.

Modifications:

- Use artifactVersion instead of artifactId
- Use correct class loader

Result:

The 'user-agent' header value includes the version information.


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

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

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import java.io.IOException;

public class MMXOAuthCallbackHandler implements CallbackHandler {
  private static Logger LOGGER = LoggerFactory.getLogger(BFOAuthTokenValidatorImpl.class);

  @Override
  public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    LOGGER.trace("No op callback handler used");
  }
}

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

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

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

public class MMXOAuthCallbackHandler implements CallbackHandler {
  private static Logger LOGGER = LoggerFactory.getLogger(MMXOAuthCallbackHandler.class);

  @Override
  public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    LOGGER.trace("No op callback handler used");
  }
}

Correct a misleading class name for the logger.


package org.frawa.elmtest.run;

import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.IconLoader;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

public class ElmTestConfigurationFactory extends ConfigurationFactory {

    private static final String FACTORY_NAME = "Elm Test configuration factory";

    static final Icon RUN_ICON = IconLoader.getIcon("/icons/elm-colorful-original.svg");

    ElmTestConfigurationFactory(ConfigurationType type) {
        super(type);
    }

    @NotNull
    @Override
    public RunConfiguration createTemplateConfiguration(@NotNull Project project) {
        return new ElmTestRunConfiguration(project, this, "Elm Test");
    }

    @Override
    public String getName() {
        return FACTORY_NAME;
    }

    @Nullable
    @Override
    public Icon getIcon() {
        return RUN_ICON;
    }

}

package org.frawa.elmtest.run;

import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.openapi.project.Project;
import org.elm.ide.icons.ElmIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

public class ElmTestConfigurationFactory extends ConfigurationFactory {

    private static final String FACTORY_NAME = "Elm Test configuration factory";

    static final Icon RUN_ICON = ElmIcons.INSTANCE.getCOLORFUL();

    ElmTestConfigurationFactory(ConfigurationType type) {
        super(type);
    }

    @NotNull
    @Override
    public RunConfiguration createTemplateConfiguration(@NotNull Project project) {
        return new ElmTestRunConfiguration(project, this, "Elm Test");
    }

    @Override
    public String getName() {
        return FACTORY_NAME;
    }

    @Nullable
    @Override
    public Icon getIcon() {
        return RUN_ICON;
    }

}

Fix icon (SVG was being rendered HUGE in WebStorm)