package tours.compiler;

import tours.grammar.ToursParser;

public class Type {
    public static final Type BOOLEAN = new Type(ToursParser.BOOLEAN);
    public static final Type CHARACTER = new Type(ToursParser.CHARACTER);
    public static final Type INTEGER = new Type(ToursParser.INTEGER);
    public static final Type STRING = new Type(ToursParser.STRING);
    private final int type;

    public Type(int type) {
        this.type = type;
    }
    public Type(String type) {
        switch (type) {
            case "boolean" :
                this.type = BOOLEAN.getType();
                break;
            case "character" :
                this.type = CHARACTER.getType();
                break;
            case "integer" :
                this.type = INTEGER.getType();
                break;
            case "string" :
                this.type = STRING.getType();
                break;
            default :
                throw new UnsupportedOperationException("Type: " + type + " was undefined");
        }
    }

    public int getType() {
        return type;
    }

    @Override
    public boolean equals(Object object) {
        if (object instanceof Type) {
            return this.getType() == ((Type) object).getType();
        }
        return false;
    }
}

package tours.compiler;

import tours.grammar.ToursParser;

public class Type {
    public static final Type BOOLEAN = new Type(ToursParser.BOOLEAN);
    public static final Type CHARACTER = new Type(ToursParser.CHARACTER);
    public static final Type INTEGER = new Type(ToursParser.INTEGER);
    public static final Type STRING = new Type(ToursParser.STRING);
    private final int type;

    public Type(int type) {
        this.type = type;
    }
    public Type(String type) {
        type = type.toLowerCase();
        switch (type) {
            case "boolean" :
                this.type = BOOLEAN.getType();
                break;
            case "character" :
                this.type = CHARACTER.getType();
                break;
            case "integer" :
                this.type = INTEGER.getType();
                break;
            case "string" :
                this.type = STRING.getType();
                break;
            default :
                throw new UnsupportedOperationException("Type: " + type + " was undefined");
        }
    }

    public int getType() {
        return type;
    }

    @Override
    public boolean equals(Object object) {
        if (object instanceof Type) {
            return this.getType() == ((Type) object).getType();
        }
        return false;
    }
}

Normalize type before switching on it

Normalize type before switching on it


/*
 * Copyright 2015 Ivan Pribela
 *
 * 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.svetovid.demo;

import org.svetovid.Svetovid;

public class HelloWorld {

    public static void main(String[] args) {

        // Ask for a name
        String name = Svetovid.in.readString("Please enter your name:");

        // Greet the user
        Svetovid.out.println("Hello " + name + "!");

    }
}

/*
 * Copyright 2015 Ivan Pribela
 *
 * 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.svetovid.demo;

import org.svetovid.Svetovid;

public class HelloWorld {

    public static void main(String[] args) {

        // Ask for a name
        String name = Svetovid.in.readLine("Please enter your name:");

        // Greet the user
        Svetovid.out.println("Hello " + name + "!");

    }
}

Fix demos to use readTokenXxx()

Fix demos to use readTokenXxx()


package protocolsupport;

import java.util.logging.Level;

import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.plugin.Plugin;
import protocolsupport.injector.BungeeNettyChannelInjector;
import protocolsupport.injector.pe.PEProxyServer;
import protocolsupport.utils.Utils;

public class ProtocolSupport extends Plugin {

	private PEProxyServer peserver;

	@Override
	public void onLoad() {
		try {
			getProxy().getPluginManager().registerCommand(this, new CommandHandler());
			BungeeNettyChannelInjector.inject();
		} catch (Throwable t) {
			t.printStackTrace();
			ProxyServer.getInstance().stop();
		}
	}

	@Override
	public void onEnable() {
		if (Utils.getJavaPropertyValue("enablepe", false, Boolean::parseBoolean)) {
			getLogger().log(Level.INFO, "Enabling MCPE support");
			(peserver = new PEProxyServer()).start();
		}
	}

	@Override
	public void onDisable() {
		peserver.stop();
	}

}

package protocolsupport;

import java.util.logging.Level;

import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.plugin.Plugin;
import protocolsupport.injector.BungeeNettyChannelInjector;
import protocolsupport.injector.pe.PEProxyServer;
import protocolsupport.utils.Utils;

public class ProtocolSupport extends Plugin {

	private PEProxyServer peserver;

	@Override
	public void onLoad() {
		try {
			getProxy().getPluginManager().registerCommand(this, new CommandHandler());
			BungeeNettyChannelInjector.inject();
		} catch (Throwable t) {
			t.printStackTrace();
			ProxyServer.getInstance().stop();
		}
	}

	@Override
	public void onEnable() {
		if (Utils.getJavaPropertyValue("enablepe", false, Boolean::parseBoolean)) {
			getLogger().log(Level.INFO, "Enabling MCPE support");
			(peserver = new PEProxyServer()).start();
		}
	}

	@Override
	public void onDisable() {
		if (peserver != null) {
			peserver.stop();
		}
	}

}

Stop PE server only if it was running

Stop PE server only if it was running


package com.pedro.fizzbuzz;

/**
 *
 * Matcher implementation created to return the "Fizz" value if the value passed as argument in the evaluate method
 * is 5 or multiple of 5.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
class BuzzMatcher implements Matcher {

    @Override
    public String evaluate(int value) {
        return "";
    }
}

package com.pedro.fizzbuzz;

/**
 *
 * Matcher implementation created to return the "Fizz" value if the value passed as argument in the evaluate method
 * is 5 or multiple of 5.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
class BuzzMatcher implements Matcher {

    /*
     * Constants
     */
    private final static String BUZZ = "BUZZ";

    /*
     * Implemented methods
     */

    @Override
    public String evaluate(int value) {
        return value % 5 == 0 ? BUZZ : "";
    }
}

Implement BUZZ matcher and all tests in green :)


package com.vite;

import com.vite.service.ViteClient;
import org.apache.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@EnableWebMvc
@ComponentScan({"com.vite.service"})
@SpringBootApplication
public class Application {
    static final Logger LOGGER = Logger.getLogger(Application.class);

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        new ViteClient();
        LOGGER.info("Starting server...");
    }
}

package com.vite;

import org.apache.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@EnableWebMvc
@ComponentScan({"com.vite.service"})
@SpringBootApplication
public class Application {
    static final Logger LOGGER = Logger.getLogger(Application.class);

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        LOGGER.info("Starting server...");
    }
}

Remove code from start up

Remove code from start up


package ch.hood;

import static ch.hood.jooq.schema1.Tables.A;
import static ch.hood.jooq.schema2.Tables.B;
import static org.jooq.impl.DSL.select;

public class App {
	public static void main(String[] args) {
		System.out.println(
			select(A.ID, A.FLAG)
				.from(A)
				.join(B).on(B.NAME.eq(A.NAME))
				.toString());
	}

}

package ch.hood;

import static ch.hood.jooq.schema1.Schema1.SCHEMA1;
import static ch.hood.jooq.schema1.Tables.A;
import static ch.hood.jooq.schema2.Schema2.SCHEMA2;
import static ch.hood.jooq.schema2.Tables.B;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import static org.jooq.impl.DSL.select;

import ch.hood.jooq.schema1.Schema1;
import ch.hood.jooq.schema2.Schema2;
import org.jooq.Configuration;
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.conf.MappedSchema;
import org.jooq.conf.RenderMapping;
import org.jooq.conf.RenderNameStyle;
import org.jooq.conf.Settings;
import org.jooq.impl.DSL;
import org.jooq.impl.DefaultConfiguration;

/**
 * The main methods expects either no arguments or 2 arguments. When run without arguments, we assume a HQSLDB;
 * when run with 2 arguments, we expect the names of the schema1 and the schema2 for a Postgresql (or Oracle) instance.
 */
public class App {
	public static void main(String[] args) {
		SQLDialect sqlDialect = args.length == 0 ? SQLDialect.HSQLDB : SQLDialect.POSTGRES; // SQLDialect.ORACLE

		Settings settings = new Settings()
			.withRenderFormatted(true)
			.withRenderSchema(TRUE)
			.withRenderNameStyle(RenderNameStyle.UPPER);
		if (sqlDialect == SQLDialect.POSTGRES) {
			String schema1Name = args[0];
			String schema2Name = args[1];
			settings.withRenderMapping(new RenderMapping()
				.withSchemata(
					new MappedSchema().withInput(SCHEMA1.getName()).withOutput(schema1Name),
					new MappedSchema().withInput(SCHEMA2.getName()).withOutput(schema2Name)));
		}

		Configuration config = new DefaultConfiguration()
			.set(sqlDialect)
			.set(settings);

		Configuration configuration = config;
		DSLContext dsl = DSL.using(configuration);

		System.out.println(
			dsl.select(A.ID, A.FLAG)
				.from(A)
				.join(B).on(B.NAME.eq(A.NAME))
				.toString());
	}

}

Add Code Example with Schema Mapping.

Add Code Example with Schema Mapping.


package com.rhomobile.rhodes.webview;

import android.content.Context;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class RhoWebSettingsNew implements RhoWebSettings {

	public WebSettings setWebSettings(WebView w) {
		RhoWebSettingsOld ws = new RhoWebSettingsOld();
		WebSettings webSettings = ws.setWebSettings(w);

		webSettings.setAppCacheEnabled(true);

		webSettings.setDatabaseEnabled(true);
		webSettings.setJavaScriptEnabled(true);

		Context context = w.getContext();
		String databasePath = context.getDir("database", Context.MODE_PRIVATE).getPath();
		webSettings.setDatabasePath(databasePath);

		return webSettings;
	}

}

package com.rhomobile.rhodes.webview;

import android.content.Context;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class RhoWebSettingsNew implements RhoWebSettings {

	public WebSettings setWebSettings(WebView w) {
		RhoWebSettingsOld ws = new RhoWebSettingsOld();
		WebSettings webSettings = ws.setWebSettings(w);

		webSettings.setAppCacheEnabled(true);

		webSettings.setDatabaseEnabled(true);
		webSettings.setJavaScriptEnabled(true);
		webSettings.setDomStorageEnabled(true);

		Context context = w.getContext();
		String databasePath = context.getDir("database", Context.MODE_PRIVATE).getPath();
		webSettings.setDatabasePath(databasePath);

		return webSettings;
	}

}

Fix localStorage access from js.

Android: Fix localStorage access from js.


package com.iluwatar.doublechecked.locking;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * In {@link Inventory} we store the items with a given size. However, we do not store
 * more items than the inventory size. To address concurrent access problems we
 * use double checked locking to add item to inventory. In this method, the
 * thread which gets the lock first adds the item.
 *
 */
public class App {

	/**
	 * Program entry point
	 * @param args command line args
	 */
	public static void main(String[] args) {
		final Inventory inventory = new Inventory(1000);
		ExecutorService executorService = Executors.newFixedThreadPool(3);
		for (int i = 0; i < 3; i++) {
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					while (inventory.addItem(new Item()))
						;
				}
			});
		}
	}
}

package com.iluwatar.doublechecked.locking;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * Double Checked Locking is a concurrency design pattern used to reduce the overhead
 * of acquiring a lock by first testing the locking criterion (the "lock hint") without
 * actually acquiring the lock. Only if the locking criterion check indicates that
 * locking is required does the actual locking logic proceed.
 * <p>
 * In {@link Inventory} we store the items with a given size. However, we do not store
 * more items than the inventory size. To address concurrent access problems we
 * use double checked locking to add item to inventory. In this method, the
 * thread which gets the lock first adds the item.
 *
 */
public class App {

	/**
	 * Program entry point
	 * @param args command line args
	 */
	public static void main(String[] args) {
		final Inventory inventory = new Inventory(1000);
		ExecutorService executorService = Executors.newFixedThreadPool(3);
		for (int i = 0; i < 3; i++) {
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					while (inventory.addItem(new Item()))
						;
				}
			});
		}
	}
}

Improve Double Checked Locking Javadoc

Improve Double Checked Locking Javadoc


/*******************************************************************************
 * Copyright (c) 2010 itemis AG (http://www.itemis.eu) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package org.eclipse.xtext.mwe;

/**
 * @author svenefftinge - Initial contribution and API
 */
public class EquinoxClasspathEntriesProvider implements IClasspathEntriesProvider {

	@Override
	public Iterable<String> getAllPathes(ClassLoader classloader) {

		return null;
	}

}

/*******************************************************************************
 * Copyright (c) 2010 itemis AG (http://www.itemis.eu) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package org.eclipse.xtext.mwe;

import java.util.Collections;

/**
 * @author svenefftinge - Initial contribution and API
 */
public class EquinoxClasspathEntriesProvider implements IClasspathEntriesProvider {
	@Override
	public Iterable<String> getAllPathes(ClassLoader classloader) {
		return Collections.emptyList();
	}

}

Return empty list instead of null

Return empty list instead of null

Signed-off-by: Karsten Thoms <dec0ef9b050f1aa68d12b8ac7c21dd1e6ea132c8@itemis.de>


package com.unidev.polydata;

import com.unidev.polydata.domain.BasicPoly;
import com.unidev.polydata.domain.Poly;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;

import java.util.Optional;

/**
 * SQLite storage tests
 */
public class SQLiteStorageTest {

    @Test
    public void testStorageSaveLoad() throws SQLiteStorageException {

        SQLiteStorage sqLiteStorage = new SQLiteStorage("/tmp/testdb.db");

        BasicPoly basicPoly = BasicPoly.newPoly("potato");
        basicPoly.put("value", "tomato");

        sqLiteStorage.save("poly", basicPoly);

        Optional<Poly> polyOptional = sqLiteStorage.fetch("poly", "potato");
        assertThat(polyOptional.isPresent(), is(true));

        Poly poly = polyOptional.get();
        assertThat(poly._id(), is("potato"));
        assertThat(poly.get("value"), is("tomato"));

        Optional<Poly> polyOptional2 = sqLiteStorage.fetch("poly", "tomato");
        assertThat(polyOptional2.isPresent(), is(false));
    }
}

package com.unidev.polydata;

import com.unidev.polydata.domain.BasicPoly;
import com.unidev.polydata.domain.Poly;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Optional;

/**
 * SQLite storage tests
 */
public class SQLiteStorageTest {

    @Test
    public void testStorageSaveLoad() throws SQLiteStorageException {

        SQLiteStorage sqLiteStorage = new SQLiteStorage("/tmp/testdb.db");
        sqLiteStorage.setPolyMigrators(Arrays.asList(new SQLitePolyMigrator() {
            @Override
            public boolean canHandle(String poly) {
                return "poly".equalsIgnoreCase(poly);
            }

            @Override
            public void handle(String poly, Connection connection) throws SQLiteStorageException {
                try {
                    Statement statement = connection.createStatement();
                    statement.executeUpdate("CREATE TABLE IF NOT EXISTS "+poly+" (_id TEXT PRIMARY KEY, value TEXT)");
                } catch (SQLException e) {
                    throw new SQLiteStorageException(e);
                }
            }
        }));

        BasicPoly basicPoly = BasicPoly.newPoly("potato");
        basicPoly.put("value", "tomato");

        sqLiteStorage.save("poly", basicPoly);

        Optional<Poly> polyOptional = sqLiteStorage.fetch("poly", "potato");
        assertThat(polyOptional.isPresent(), is(true));

        Poly poly = polyOptional.get();
        assertThat(poly._id(), is("potato"));
        assertThat(poly.get("value"), is("tomato"));

        Optional<Poly> polyOptional2 = sqLiteStorage.fetch("poly", "tomato");
        assertThat(polyOptional2.isPresent(), is(false));
    }
}

Test coverage for poly tables conversion


package io.georocket.index.generic;

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

import io.georocket.index.xml.MetaIndexer;
import io.georocket.storage.ChunkMeta;
import io.georocket.storage.IndexMeta;

/**
 * Default implementation of {@link MetaIndexer} that extracts generic
 * attributes from chunk metadata and adds it to the index.
 * @author Michel Kraemer
 */
public class DefaultMetaIndexer implements MetaIndexer {
  private final Map<String, Object> result = new HashMap<>();

  @Override
  public Map<String, Object> getResult() {
    return result;
  }

  @Override
  public void onIndexChunk(String path, ChunkMeta chunkMeta,
      IndexMeta indexMeta) {
    result.put("path", path);
    result.put("correlationId", indexMeta.getCorrelationId());
    result.put("filename", indexMeta.getFilename());
    result.put("timestamp", indexMeta.getTimestamp());
    result.put("chunkMeta", chunkMeta.toJsonObject());
    if (indexMeta.getTags() != null) {
      result.put("tags", indexMeta.getTags());
    }
  }
}

package io.georocket.index.generic;

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

import io.georocket.index.xml.MetaIndexer;
import io.georocket.storage.ChunkMeta;
import io.georocket.storage.IndexMeta;

/**
 * Default implementation of {@link MetaIndexer} that extracts generic
 * attributes from chunk metadata and adds it to the index.
 * @author Michel Kraemer
 */
public class DefaultMetaIndexer implements MetaIndexer {
  private final Map<String, Object> result = new HashMap<>();

  @Override
  public Map<String, Object> getResult() {
    return result;
  }

  @Override
  public void onIndexChunk(String path, ChunkMeta chunkMeta,
      IndexMeta indexMeta) {
    result.put("path", path);
    result.put("chunkMeta", chunkMeta.toJsonObject());
    if (indexMeta.getTags() != null) {
      result.put("tags", indexMeta.getTags());
    }
  }
}

Remove unnecessary properties from index


package org.apache.lucene.index;

/**
 * Copyright 2004 The Apache Software Foundation
 *
 * 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.
 */

import java.io.IOException;

import org.apache.lucene.store.GCJDirectory;

class GCJSegmentReader extends SegmentReader {

  /** Try to use an optimized native implementation of TermDocs.  The optimized
   * implementation can only be used when the segment's directory is a
   * GCJDirectory and it is not in compound format.  */
  public final TermDocs termDocs() throws IOException {
    if (directory() instanceof GCJDirectory       // it's a GCJ directory
        && this.cfsReader == null) {              // & not in compound format
      return new GCJTermDocs(this);               // so can use GCJTermDocs
    } else {
      return super.termDocs();
    }
  }
}

package org.apache.lucene.index;

/**
 * Copyright 2004 The Apache Software Foundation
 *
 * 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.
 */

import java.io.IOException;

import org.apache.lucene.store.GCJIndexInput;

class GCJSegmentReader extends SegmentReader {

  /** Try to use an optimized native implementation of TermDocs.  The optimized
   * implementation can only be used when the segment's directory is a
   * GCJDirectory and it is not in compound format.  */
  public final TermDocs termDocs() throws IOException {
    if (freqStream instanceof GCJIndexInput) {    // it's a GCJIndexInput
      return new GCJTermDocs(this);               // so can use GCJTermDocs
    } else {
      return super.termDocs();
    }
  }
}

Check the type of the IndexInput rather than the Directory to detect
native implementation.  This is a simpler and more correct test.  It
also permits the Directory to return a mixture of native and
non-native IndexInput implementations.

git-svn-id: 4c5078813df38efa56971a28e09a55254294f104@150604 13f79535-47bb-0310-9956-ffa450edef68


package given.a.spec.with.constructor.parameters;

class Fixture {

  public static Class<?> getSpecThatRequiresAConstructorParameter() {
    class Spec {
      @SuppressWarnings("unused")
      public Spec(final String something) {}
    }

    return Spec.class;
  }

  public static class SomeException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    public SomeException(final String message) {
      super(message);
    }
  }

}

package given.a.spec.with.constructor.parameters;

class Fixture {

  public static Class<?> getSpecThatRequiresAConstructorParameter() {
    class Spec {
      @SuppressWarnings("unused")
      public Spec(final String something) {}
    }

    return Spec.class;
  }

}

Remove some dead code from test suite

Remove some dead code from test suite


package com.granveaud.mysql2h2converter.converter;

import com.granveaud.mysql2h2converter.parser.ParseException;
import com.granveaud.mysql2h2converter.parser.SQLParserManager;
import com.granveaud.mysql2h2converter.sql.Statement;

import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Iterator;

public class Main {
    final static private Charset INPUT_CHARSET = Charset.forName("UTF-8");

    public static void main(String[] args) throws IOException, ParseException {
        if (args.length < 1) {
            System.err.println("Usage: input_file1 input_file2...");
            System.exit(1);
        }

        for (String str : args) {
            Iterator<Statement> sourceIterator = SQLParserManager.parseScript(new InputStreamReader(new FileInputStream(str), INPUT_CHARSET));

            // conversion and execution
            Iterator<Statement> it = H2Converter.convertScript(sourceIterator);
            while (it.hasNext()) {
                Statement st = it.next();

                // output to stdout
                System.out.println(st.toString() + ";");
            }
        }
    }
}

package com.granveaud.mysql2h2converter.converter;

import com.granveaud.mysql2h2converter.parser.ParseException;
import com.granveaud.mysql2h2converter.parser.SQLParserManager;
import com.granveaud.mysql2h2converter.sql.Statement;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.zip.GZIPInputStream;

public class Main {
    final static private Charset INPUT_CHARSET = Charset.forName("UTF-8");

    public static void main(String[] args) throws IOException, ParseException {
        if (args.length < 1) {
            System.err.println("Usage: input_file1 input_file2...");
            System.exit(1);
        }

        for (String str : args) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(readFile(str), INPUT_CHARSET));
            Iterator<Statement> sourceIterator = SQLParserManager.parseScript(reader);

            // conversion and execution
            Iterator<Statement> it = H2Converter.convertScript(sourceIterator);
            while (it.hasNext()) {
                Statement st = it.next();

                // output to stdout
                System.out.println(st.toString() + ";");
            }
        }

    }

    public static InputStream readFile(String name) throws IOException {
        InputStream input = new BufferedInputStream(new FileInputStream(name));
        PushbackInputStream pb = new PushbackInputStream( input, 2 );
        byte [] magicbytes = new byte[2];
        pb.read(magicbytes);
        pb.unread(magicbytes);
        ByteBuffer bb = ByteBuffer.wrap(magicbytes);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        short magic = bb.getShort();
        if( magic == (short)GZIPInputStream.GZIP_MAGIC )
            return new GZIPInputStream( pb );
        else
            return pb;
    }
}

Support reading input scripts that are gzipped


package ohtuhatut.domain;

import org.springframework.data.jpa.domain.AbstractPersistable;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.List;

/**
 * The class for a list of references
 * Created by iilumme.
 */

@Entity
@Table(name = "ReferenceList")
public class ReferenceList extends AbstractPersistable<Long> {

    @OneToMany(fetch = FetchType.LAZY)
    private List<Reference> references;

    public List<Reference> getReferences() {
        return this.references;
    }

    public void setReferences(List<Reference> references) {
        this.references = references;
    }
}

package ohtuhatut.domain;

import org.springframework.data.jpa.domain.AbstractPersistable;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.List;

/**
 * The class for a list of references
 * Created by iilumme.
 */

@Entity
@Table(name = "ReferenceList")
public class ReferenceList extends AbstractPersistable<Long> {

    @OneToMany(fetch = FetchType.LAZY)
    private List<Reference> references;

    private String name;

    public ReferenceList(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

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

    public List<Reference> getReferences() {
        return this.references;
    }

    public void setReferences(List<Reference> references) {
        this.references = references;
    }
}

Add name field for reference list

Add name field for reference list


package com.geeks;

public class BinarySearchTree {
	public static void main(String[] args) {

	}

	private static class TreeNode<T> {
		TreeNode<T> left;
		TreeNode<T> right;

		T elem;
	}
}

package com.geeks;

import java.util.Arrays;

public class BinarySearchTree {
	public static void main(String[] args) {
		Character[] inOrder = { 'D', 'B', 'E', 'A', 'F', 'C' };
		Character[] preOrder = { 'A', 'B', 'D', 'E', 'C', 'F' };

		TreeNode<Character> tree = constructTreeNode(0, preOrder, inOrder);

		postOrderTraverse(tree, new TraverseCallback() {

			public <T> void callback(T t) {
				TreeNode<Character> treeNode = (TreeNode<Character>) t;
				System.out.println(treeNode.elem);
			}
		});
	}

	/**
	 *
	 * @param inOrder
	 * @param preOrder
	 * @return
	 */
	private static <T> TreeNode<T> constructTreeNode(int rootPos, T[] preOrder,
			T[] inOrder) {
		if (rootPos == preOrder.length) {
			return null;
		}

		if (inOrder == null || inOrder.length == 0)
			return null;

		T childRoot = preOrder[rootPos];

		int i = 0;
		for (; i < inOrder.length; i++) {
			if (childRoot.equals(inOrder[i]))
				break;
		}

		T[] leftChildInOrder = Arrays.copyOfRange(inOrder, 0, i);

		T[] rightChildInOrder = null;
		if (i < inOrder.length - 1) {
			rightChildInOrder = Arrays.copyOfRange(inOrder, i + 1,
					inOrder.length);
		}

		TreeNode<T> leftChild = constructTreeNode(rootPos + 1, preOrder,
				leftChildInOrder);
		TreeNode<T> rightChild = constructTreeNode(rootPos + i + 1, preOrder,
				rightChildInOrder);

		TreeNode<T> node = new TreeNode<T>();
		node.left = leftChild;
		node.right = rightChild;
		node.elem = childRoot;

		return node;
	}

	private static <T> void postOrderTraverse(TreeNode<T> tree,
			TraverseCallback callback) {
		if (tree.right != null)
			postOrderTraverse(tree.right, callback);

		if (tree.left != null)
			postOrderTraverse(tree.left, callback);

		callback.callback(tree);
		// System.out.println(tree.elem);
	}

	private static interface TraverseCallback {
		public <T> void callback(T t);
	}

	private static class TreeNode<T> {
		TreeNode<T> left;
		TreeNode<T> right;

		T elem;
	}
}

Add construct binary tree from inOrder and preOrder


/*
 * Copyright 2015 Timothy Brooks
 *
 * 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.uncontended.precipice.timeout;

public class NewTimerService {

    public void schedule(Object task, long timeMillis) {

    }
}

/*
 * Copyright 2015 Timothy Brooks
 *
 * 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.uncontended.precipice.timeout;

import java.util.concurrent.TimeUnit;

public class NewTimerService {

    private final long resolution;
    private final long startTime;

    public NewTimerService(long resolution, TimeUnit unit) {
        this.resolution = unit.toMillis(resolution);
        startTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
    }

    public void schedule(Object task, long delay, TimeUnit unit) {

    }
}

Work on laying out timeout service resolution


package org.synyx.urlaubsverwaltung.application.domain;

/**
 * Enum describing which states an {@link Application} may have.
 */
public enum ApplicationStatus {

    /**
     * After applying for the leave, the saved application for leave gets this status.
     */
    WAITING,

    /**
     * After the HeadOf has allowed the application in a two stage approval process.
     *
     * @since 2.15.0
     */
    TEMPORARY_ALLOWED,

    /**
     * Status after a boss has allowed the application for leave or after HeadOf has allowed the application in a one
     * stage approval process or after a SECOND_STAGE_AUTHORITY (Role) has released a TEMPORARY_ALLOWED application.
     */
    ALLOWED,

    /**
     * Status after the application for leave was allowed but the applicant wants to cancel the own application.
     * The application for leave is at this point not cancelled and can only be approved by OFFICE Role.
     */
    ALLOWED_CANCELLATION_REQUESTED,

    /**
     * Status after a boss has rejected application for leave.
     */
    REJECTED,

    /**
     * If an application for leave has been allowed and is cancelled afterwards, it gets this status.
     */
    CANCELLED,

    /**
     * If an application for leave has **not** been allowed yet and is cancelled, it gets this status.
     *
     * @since 2.5.2
     */
    REVOKED
}

package org.synyx.urlaubsverwaltung.application.domain;

/**
 * Enum describing which states an {@link Application} may have.
 */
public enum ApplicationStatus {

    /**
     * After applying for the leave, the saved application for leave gets this status.
     */
    WAITING,

    /**
     * After the department head has allowed the application in a two stage approval process and before the
     * second stage authority has rejected or allowed the application.
     * This status is a special case of WAITING and needs to be handled as a waiting, not yet allowed, application for leave.
     *
     * @since 2.15.0
     */
    TEMPORARY_ALLOWED,

    /**
     * Status after a boss has allowed the application for leave or after HeadOf has allowed the application in a one
     * stage approval process or after a SECOND_STAGE_AUTHORITY (Role) has released a TEMPORARY_ALLOWED application.
     */
    ALLOWED,

    /**
     * Status after the application for leave was allowed but the applicant wants to cancel the own application.
     * The application for leave is at this point not cancelled and can only be approved by OFFICE Role.
     */
    ALLOWED_CANCELLATION_REQUESTED,

    /**
     * Status after a boss has rejected application for leave.
     */
    REJECTED,

    /**
     * If an application for leave has been allowed and is cancelled afterwards, it gets this status.
     */
    CANCELLED,

    /**
     * If an application for leave has **not** been allowed yet and is cancelled, it gets this status.
     *
     * @since 2.5.2
     */
    REVOKED
}

Improve javadoc of temporary allowed application status


/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * 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.facebook.buck.jvm.java.testutil.compiler;

import org.junit.runners.Parameterized;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.TestClass;

/**
 * Parameterized test runner that enables tests to work with the Compiler Tree API implementation
 * corresponding to the compiler returned by {@link
 * javax.tools.ToolProvider#getSystemJavaCompiler()}. These are public APIs that are not provided in
 * rt.jar and thus are not usually on the classpath.
 */
public class CompilerTreeApiParameterized extends Parameterized {
  public CompilerTreeApiParameterized(Class<?> klass) throws Throwable {
    super(klass);
  }

  @Override
  protected TestClass createTestClass(Class<?> testClass) {
    try {
      return new TestClass(CompilerTreeApiTestRunner.reloadFromCompilerClassLoader(testClass));
    } catch (InitializationError initializationError) {
      throw new AssertionError(initializationError);
    }
  }
}

/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * 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.facebook.buck.jvm.java.testutil.compiler;

import org.junit.runners.Parameterized;

/**
 * Parameterized test runner that enables tests to work with the Compiler Tree API implementation
 * corresponding to the compiler returned by {@link
 * javax.tools.ToolProvider#getSystemJavaCompiler()}. These are public APIs that are not provided in
 * rt.jar and thus are not usually on the classpath.
 */
public class CompilerTreeApiParameterized extends Parameterized {
  public CompilerTreeApiParameterized(Class<?> klass) throws Throwable {
    super(CompilerTreeApiTestRunner.reloadFromCompilerClassLoader(klass));
  }
}

Replace deprecate code in JUnit call

Replace deprecate code in JUnit call

Summary:
To make code compatible with JUnit 4.13 (following diff).

`createTestClass` function is deprecated, javadoc suggest replacing a call with a constructor, which is what I did.

Note this is a buck-self-test-only change.

Reviewed By: mykola-semko

shipit-source-id: 64158afd8a45fdefdd44c69df4f3103705b25748


/* Generated By:JJTree: Do not edit this line. OMultExpression.java Version 4.3 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=O,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package com.orientechnologies.orient.core.sql.parser;

import java.util.Set;

public
class OMultExpression extends OMathExpression {

  public OMultExpression(int id) {
    super(id);
  }

  public OMultExpression(OrientSql p, int id) {
    super(p, id);
  }

  /** Accept the visitor. **/
  public Object jjtAccept(OrientSqlVisitor visitor, Object data) {
    return visitor.visit(this, data);
  }

  public boolean needsAliases(Set<String> aliases) {
    throw new UnsupportedOperationException();
  }
}
/* JavaCC - OriginalChecksum=f75b8be48dca1e0cafae0cacadc608c8 (do not edit this line) */

/* Generated By:JJTree: Do not edit this line. OMultExpression.java Version 4.3 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=O,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package com.orientechnologies.orient.core.sql.parser;

import java.util.Set;

public
class OMultExpression extends OMathExpression {

  public OMultExpression(int id) {
    super(id);
  }

  public OMultExpression(OrientSql p, int id) {
    super(p, id);
  }

  /** Accept the visitor. **/
  public Object jjtAccept(OrientSqlVisitor visitor, Object data) {
    return visitor.visit(this, data);
  }

  public boolean needsAliases(Set<String> aliases) {
    return super.needsAliases(aliases);
  }
}
/* JavaCC - OriginalChecksum=f75b8be48dca1e0cafae0cacadc608c8 (do not edit this line) */

Fix Multiplication operation in new SQL executor


package net.interfax.rest.client.exception;

public class UnsuccessfulStatusCodeException extends Exception {

    public UnsuccessfulStatusCodeException(String message) {
        super(message);
    }

    public UnsuccessfulStatusCodeException(final String message, final Throwable cause) {
        super(message, cause);
    }

    public UnsuccessfulStatusCodeException(final Throwable cause) {
        super(cause);
    }

    public UnsuccessfulStatusCodeException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }

}

package net.interfax.rest.client.exception;

public class UnsuccessfulStatusCodeException extends Exception {

    private int statusCode;
    private String responseBody;

    public UnsuccessfulStatusCodeException(int statusCode) {
        this.statusCode = statusCode;
    }

    public UnsuccessfulStatusCodeException(int statusCode, String responseBody) {
        this.statusCode = statusCode;
        this.responseBody = responseBody;
    }

    public UnsuccessfulStatusCodeException(String message) {
        super(message);
    }

    public UnsuccessfulStatusCodeException(String message, int statusCode, String responseBody) {
        super(message);
        this.statusCode = statusCode;
        this.responseBody = responseBody;
    }

    public UnsuccessfulStatusCodeException(String message, int statusCode) {
        super(message);
        this.statusCode = statusCode;
    }

    public UnsuccessfulStatusCodeException(final String message, final Throwable cause) {
        super(message, cause);
    }

    public UnsuccessfulStatusCodeException(final Throwable cause) {
        super(cause);
    }

    public UnsuccessfulStatusCodeException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(final int statusCode) {
        this.statusCode = statusCode;
    }

    public String getResponseBody() {
        return responseBody;
    }

    public void setResponseBody(final String responseBody) {
        this.responseBody = responseBody;
    }

}

Add attributes to capture status code and response body in custom exception


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

package org.gradle.internal.filewatch;

import org.gradle.api.Action;
import org.gradle.api.internal.file.FileSystemSubset;

public interface FileWatcherFactory {
    FileWatcher watch(FileSystemSubset systemSubset, Action<? super Throwable> onError, FileWatcherListener listener);
}

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

package org.gradle.internal.filewatch;

import org.gradle.api.Action;
import org.gradle.api.internal.file.FileSystemSubset;

public interface FileWatcherFactory {

    /**
     * Starts watching for changes to the given subset of the file system.
     *

     * Listeners should not rely on the events being an entirely accurate journal of file system events.
     * Implementations may emit duplicate events and chronological ordering is not guaranteed.
     *

     * It can be assumed that all changes to the file system subset that occur after the return of this method will produce events.
     *

     * No events will be emitted after that watcher has been stopped.
     *
     * @param systemSubset the parts of the file system to watch
     * @param onError what to do if an error occurs while watching
     * @param listener the receiver of events
     * @return a, stoppable, handle to the watcher
     */
    FileWatcher watch(FileSystemSubset systemSubset, Action<? super Throwable> onError, FileWatcherListener listener);
}

Add some docs on the filewatcher contract.

+review REVIEW-5498


package com.gmail.jiangyang5157.cardboard.scene.projection;

import android.util.ArrayMap;
import android.util.Log;

/**
 * @author Yang
 * @since 4/12/2016.
 */
public class IcosphereBuilder {

    private volatile static IcosphereBuilder uniqueInstance = null;

    private ArrayMap<Integer, IcosphereVertex> icosphereVertices = new ArrayMap<>();

    public static IcosphereBuilder getInstance() {
        if (uniqueInstance == null) {
            synchronized (IcosphereBuilder.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new IcosphereBuilder();
                }
            }
        }
        return uniqueInstance;
    }

    private IcosphereBuilder() {
    }

    protected IcosphereVertex build(int recursionLevel) {
        final int MAX_RECURSION_LEVEL = IcosphereVertex.VERTEX_COUNTS.length - 1;
        if (recursionLevel > MAX_RECURSION_LEVEL) {
            throw new RuntimeException("Unable to build a Icosphere with recursion level greater than " + MAX_RECURSION_LEVEL);
        }

        Integer vertexCount = IcosphereVertex.VERTEX_COUNTS[recursionLevel];
        IcosphereVertex ret = icosphereVertices.get(vertexCount);
        if (ret == null) {
            ret = new IcosphereVertex(recursionLevel);
            icosphereVertices.put(vertexCount, ret);
            Log.d("####", "IcosphereBuilder: created IcosephereVertex object with vertexCount=" + vertexCount);
        }
        return ret;
    }
}

package com.gmail.jiangyang5157.cardboard.scene.projection;

import android.util.ArrayMap;
import android.util.Log;

/**
 * @author Yang
 * @since 4/12/2016.
 */
public class IcosphereBuilder {

    private volatile static IcosphereBuilder uniqueInstance;

    private ArrayMap<Integer, IcosphereVertex> icosphereVertices;

    public static IcosphereBuilder getInstance() {
        if (uniqueInstance == null) {
            synchronized (IcosphereBuilder.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new IcosphereBuilder();
                }
            }
        }
        return uniqueInstance;
    }

    private IcosphereBuilder() {
        icosphereVertices = new ArrayMap<>();
    }

    protected IcosphereVertex build(int recursionLevel) {
        final int MAX_RECURSION_LEVEL = IcosphereVertex.VERTEX_COUNTS.length - 1;
        if (recursionLevel > MAX_RECURSION_LEVEL) {
            throw new RuntimeException("Unable to build a Icosphere with recursion level greater than " + MAX_RECURSION_LEVEL);
        }

        Integer vertexCount = IcosphereVertex.VERTEX_COUNTS[recursionLevel];
        IcosphereVertex ret = icosphereVertices.get(vertexCount);
        if (ret == null) {
            ret = new IcosphereVertex(recursionLevel);
            icosphereVertices.put(vertexCount, ret);
            Log.d("####", "IcosphereBuilder: created IcosephereVertex object with vertexCount=" + vertexCount);
        }
        return ret;
    }
}

Add Camera and Light class. Refact.

Add Camera and Light class. Refact.


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

package com.google.gerrit.client.ui;

import com.google.gerrit.client.Gerrit;
import com.google.gwtexpui.safehtml.client.HighlightSuggestOracle;

/**
 * Suggest oracle that only provides suggestions if the user has typed at least
 * as many characters as configured by 'suggest.from'. If 'suggest.from' is set
 * to 0, suggestions will always be provided.
 */
public abstract class SuggestAfterTypingNCharsOracle extends HighlightSuggestOracle {

  @Override
  protected void onRequestSuggestions(final Request request, final Callback done) {
    final int suggestFrom = Gerrit.getConfig().getSuggestFrom();
    if (suggestFrom == 0 || request.getQuery().length() >= suggestFrom) {
      _onRequestSuggestions(request, done);
    }
  }

  protected abstract void _onRequestSuggestions(Request request, Callback done);
}

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

package com.google.gerrit.client.ui;

import com.google.gerrit.client.Gerrit;
import com.google.gwtexpui.safehtml.client.HighlightSuggestOracle;

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

/**
 * Suggest oracle that only provides suggestions if the user has typed at least
 * as many characters as configured by 'suggest.from'. If 'suggest.from' is set
 * to 0, suggestions will always be provided.
 */
public abstract class SuggestAfterTypingNCharsOracle extends HighlightSuggestOracle {

  @Override
  protected void onRequestSuggestions(Request req, Callback cb) {
    if (req.getQuery().length() >= Gerrit.getConfig().getSuggestFrom()) {
      _onRequestSuggestions(req, cb);
    } else {
      List<Suggestion> none = Collections.emptyList();
      cb.onSuggestionsReady(req, new Response(none));
    }
  }

  protected abstract void _onRequestSuggestions(Request request, Callback done);
}

Fix reviewer suggestions when suggestFrom > 0

RemoteSuggestOracle runs exactly one call to the
SuggestAfterTypingNCharsOracle then waits until
that completes. If SuggestAfterTypingNCharsOracle
doesn't want to send this query, it must finish
with no results to allow RemoteSuggestOracle to
unblock and consider the next query.

Change-Id: I2eb5dfe7a1aaa5c1f65002f918d4a115ab886224


package edu.northwestern.bioinformatics.studycalendar.xml.writers;

import edu.northwestern.bioinformatics.studycalendar.dao.EpochDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Epoch;
import edu.northwestern.bioinformatics.studycalendar.xml.AbstractStudyCalendarXmlSerializer;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;

public class EpochXmlSerializer extends AbstractStudyCalendarXmlSerializer<Epoch> {

    // Elements
    public static final String EPOCH = "epoch";
    public static final String PLANNDED_CALENDAR = "planned-calendar";

    private EpochDao epochDao;

    public Element createElement(Epoch epoch) {
        // Using QName is the only way to attach the namespace to the element
        QName qEpoch = DocumentHelper.createQName(EPOCH, DEFAULT_NAMESPACE);
        Element eEpoch = DocumentHelper.createElement(qEpoch)
                .addAttribute(ID, epoch.getGridId())
                .addAttribute(NAME, epoch.getName());

        return eEpoch;
    }

    public Epoch readElement(Element element) {
        String key = element.attributeValue(ID);
        Epoch epoch = epochDao.getByGridId(key);
        if (epoch == null) {
            epoch = new Epoch();
            epoch.setGridId(key);
            epoch.setName(element.attributeValue(NAME));
        }
        return epoch;
    }

    public void setEpochDao(EpochDao epochDao) {
        this.epochDao = epochDao;
    }
}

package edu.northwestern.bioinformatics.studycalendar.xml.writers;

import edu.northwestern.bioinformatics.studycalendar.dao.EpochDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Epoch;
import edu.northwestern.bioinformatics.studycalendar.xml.AbstractStudyCalendarXmlSerializer;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;

public class EpochXmlSerializer extends AbstractStudyCalendarXmlSerializer<Epoch> {

    // Elements
    public static final String EPOCH = "epoch";

    private EpochDao epochDao;

    public Element createElement(Epoch epoch) {
        // Using QName is the only way to attach the namespace to the element
        QName qEpoch = DocumentHelper.createQName(EPOCH, DEFAULT_NAMESPACE);
        Element eEpoch = DocumentHelper.createElement(qEpoch)
                .addAttribute(ID, epoch.getGridId())
                .addAttribute(NAME, epoch.getName());

        return eEpoch;
    }

    public Epoch readElement(Element element) {
        String key = element.attributeValue(ID);
        Epoch epoch = epochDao.getByGridId(key);
        if (epoch == null) {
            epoch = new Epoch();
            epoch.setGridId(key);
            epoch.setName(element.attributeValue(NAME));
        }
        return epoch;
    }

    public void setEpochDao(EpochDao epochDao) {
        this.epochDao = epochDao;
    }
}

Remove un-needed field in epoch serializer.

git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@2115 0d517254-b314-0410-acde-c619094fa49f


package net.safedata.springboot.training.d03.s01.handler;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

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

@Component
public class PostLogoutHandler implements LogoutHandler {

    @Override
    public void logout(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse,
                       final Authentication authentication) {
        // perform any post-logout operations
    }
}

Split the parameter on the next line

[improve] Split the parameter on the next line


/*******************************************************************************
 * Copyright (c) 2012 Symplectic Ltd. All rights reserved.
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 ******************************************************************************/
package uk.co.symplectic.elements.api;

import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;

class ElementsAPIConnectionManager {
    private static HttpConnectionManager connectionManager;
    private static HttpConnectionManagerParams params = null;

    static {
        params = new HttpConnectionManagerParams();
        params.setConnectionTimeout(30000);
    }

    private ElementsAPIConnectionManager() {}

    static HttpConnectionManager getInstance() {
        if (connectionManager == null) {
            ElementsAPIConnectionManager.initialize();
        }

        return connectionManager;
    }

    private static synchronized void initialize() {
        if (connectionManager == null) {
            connectionManager = new MultiThreadedHttpConnectionManager();
            if (params != null) {
                connectionManager.setParams(params);
            }
        }
    }
}

/*******************************************************************************
 * Copyright (c) 2012 Symplectic Ltd. All rights reserved.
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 ******************************************************************************/
package uk.co.symplectic.elements.api;

import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;

class ElementsAPIConnectionManager {
    private static HttpConnectionManager connectionManager;
    private static HttpConnectionManagerParams params = null;

    static {
        params = new HttpConnectionManagerParams();
        params.setConnectionTimeout(30000);
        params.setSoTimeout(60000);
    }

    private ElementsAPIConnectionManager() {}

    static HttpConnectionManager getInstance() {
        if (connectionManager == null) {
            ElementsAPIConnectionManager.initialize();
        }

        return connectionManager;
    }

    private static synchronized void initialize() {
        if (connectionManager == null) {
            connectionManager = new MultiThreadedHttpConnectionManager();
            if (params != null) {
                connectionManager.setParams(params);
            }
        }
    }
}

Fix timeouts on non-responsive API

Fix timeouts on non-responsive API


/**
 *
 */
package com.gengo.client;

/**
 * @author hiroyu-n@inter-plug.co.jp
 *
 */
public final class GengoConstants {
	protected static String BASE_URL_STANDARD = "http://api.gengo.com/v2/";
	protected static String BASE_URL_SANDBOX = "http://api.sandbox.gengo.com/v2/";
	protected static String BASE_URL_STAGING = "http://api.staging.gengo.com/v2/";
}

/**
 *
 */
package com.gengo.client;

/**
 * @author hiroyu-n@inter-plug.co.jp
 *
 */
public final class GengoConstants {
	protected static String BASE_URL_STANDARD = "http://api.gengo.com/v2/";
	protected static String BASE_URL_SANDBOX = "http://api.sandbox.gengo.com/v2/";
}

Remove code for staging environment.

Remove code for staging environment.


package org.crygier.graphql;

import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;

import graphql.language.IntValue;
import graphql.language.StringValue;
import graphql.schema.Coercing;
import graphql.schema.GraphQLScalarType;

public class JavaScalars {
    public static GraphQLScalarType GraphQLDate = new GraphQLScalarType("Date", "Date type", new Coercing() {
        @Override
        public Object serialize(Object input) {
            if (input instanceof String) {
                try {
                    return DateFormat.getInstance().parse((String)input);
                } catch (ParseException e) {
                    throw new IllegalArgumentException(e.getMessage());
                }
            } else if (input instanceof Date) {
                return input;
            } else if (input instanceof Long) {
                return new Date(((Long) input));
            } else if (input instanceof Integer) {
                return new Date(((Integer) input).longValue());
            } else {
                return null;
            }
        }

        @Override
        public Object parseValue(Object input) {
            return serialize(input);
        }

        @Override
        public Object parseLiteral(Object input) {
            if (input instanceof StringValue) {
                try {
                    return DateFormat.getInstance().parse(((StringValue) input).getValue());
                } catch (ParseException e) {
                    throw new IllegalArgumentException(e.getMessage());
                }
            } else if (input instanceof IntValue) {
                BigInteger value = ((IntValue) input).getValue();
                return new Date(value.longValue());
            }
            return null;
        }
    });
}

package org.crygier.graphql;

import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;

import graphql.language.IntValue;
import graphql.language.StringValue;
import graphql.schema.Coercing;
import graphql.schema.GraphQLScalarType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JavaScalars {
    static final Logger log = LoggerFactory.getLogger(JavaScalars.class);

    public static GraphQLScalarType GraphQLDate = new GraphQLScalarType("Date", "Date type", new Coercing() {
        @Override
        public Object serialize(Object input) {
            if (input instanceof String) {
                return parseStringToDate((String) input);
            } else if (input instanceof Date) {
                return input;
            } else if (input instanceof Long) {
                return new Date(((Long) input).longValue());
            } else if (input instanceof Integer) {
                return new Date(((Integer) input).longValue());
            }
            return null;
        }

        @Override
        public Object parseValue(Object input) {
            return serialize(input);
        }

        @Override
        public Object parseLiteral(Object input) {
            if (input instanceof StringValue) {
                return parseStringToDate(((StringValue) input).getValue());
            } else if (input instanceof IntValue) {
                BigInteger value = ((IntValue) input).getValue();
                return new Date(value.longValue());
            }
            return null;
        }

        private Date parseStringToDate(String input) {
            try {
                return DateFormat.getInstance().parse(input);
            } catch (ParseException e) {
                log.warn("Failed to parse Date from input: " + input, e);
                return null;
            }
        }
    });
}

Return null on parse errors as per specification; Do not throw Exception


/* This file is part of SableCC ( http://sablecc.org ).
 *
 * See the NOTICE file distributed with this work for copyright information.
 *
 * 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.sablecc.sablecc.launcher;

import org.sablecc.sablecc.exception.InternalException;

public class TextArgument {

    private String text;

    public TextArgument(
            String text) {

        if (text == null) {
            throw new InternalException("text may not be null");
        }

        this.text = text;
    }

    public String getText() {

        return this.text;
    }
}

/* This file is part of SableCC ( http://sablecc.org ).
 *
 * See the NOTICE file distributed with this work for copyright information.
 *
 * 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.sablecc.sablecc.launcher;

import org.sablecc.sablecc.exception.InternalException;

/**
 * A text argument puts in appendix a String at the end of another.
 */
public class TextArgument {

    /** the text to append. */
    private String text;

    /**
     * Constructs a new textArgument.
     *
     * @param text
     *            the provided text to append.
     *
     * @throws InternalException
     *             if the text is null.
     */
    public TextArgument(
            String text) {

        if (text == null) {
            throw new InternalException("text may not be null");
        }

        this.text = text;
    }

    /**
     * Returns the text of this textArgument.
     *
     * @return the text.
     */
    public String getText() {

        return this.text;
    }
}

Add javadoc comments. See ticket:56.

Add javadoc comments. See ticket:56.

Signed-off-by: Raymond Audet <281aa2b19aab01efe2941a7da076ec0616a9b992@gmail.com>
Signed-off-by: Etienne M. Gagnon <bf06ec0eb40152cd863534753d026b021022c851@j-meg.com>


package wang.cloudfinger.printing.utils;

public class Constants {

	public static final String IMAGE_CACHE_PATH = "imageLoader/cache";

	public final static int NEWS_TYPE_REGISTER = 0;
	public final static int NEWS_TYPE_ADVERTISING = 1;
	public final static int NEWS_TYPE_PRINTING = 2;
	public final static int NEWS_TYPE_BID = 3;
	public final static int NEWS_TYPE_HOBBY = 4;

}

package wang.cloudfinger.printing.utils;

public final class Constants {

	public static final String IMAGE_CACHE_PATH = "imageLoader/cache";

	public final static int NEWS_TYPE_REGISTER = 0;
	public final static int NEWS_TYPE_ADVERTISING = 1;
	public final static int NEWS_TYPE_PRINTING = 2;
	public final static int NEWS_TYPE_BID = 3;
	public final static int NEWS_TYPE_HOBBY = 4;

}

Change the Class to final Class

Change the Class to final Class


package org.lapanen.stealth.si.process;

import java.util.concurrent.ExecutorService;

import org.springframework.integration.context.IntegrationObjectSupport;
import org.springframework.integration.core.MessageSource;
import org.springframework.integration.endpoint.MessageProducerSupport;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;

public class ProcessInboundChannelAdapter implements MessageSource<ProcessRunResult> {

    private final ProcessExecutor processExecutor;

    private final ExecutorService executorService;

    private final ExitValueResultHandler exitValueResultHandler;

    public ProcessInboundChannelAdapter(final ProcessExecutor processExecutor, final ExecutorService executorService,
            final ExitValueResultHandler exitValueResultHandler) {
        this.processExecutor = processExecutor;
        this.executorService = executorService;
        this.exitValueResultHandler = exitValueResultHandler;
    }
    public ProcessInboundChannelAdapter(final ProcessExecutor processExecutor, final ExecutorService executorService) {
        this(processExecutor, executorService, new OnNokExitValueExceptionThrowingExitValueHandler());
    }

    @Override
    public Message<ProcessRunResult> receive() {
        return MessageBuilder.withPayload(processExecutor.execute(executorService)).build();
    }
}

package org.lapanen.stealth.si.process;

import java.util.concurrent.ExecutorService;

import org.springframework.integration.context.IntegrationObjectSupport;
import org.springframework.integration.core.MessageSource;
import org.springframework.integration.endpoint.MessageProducerSupport;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;

public class ProcessInboundChannelAdapter implements MessageSource<ProcessRunResult> {

    private final ProcessExecutor processExecutor;

    private final ExecutorService executorService;

    private final ExitValueResultHandler exitValueResultHandler;

    public ProcessInboundChannelAdapter(final ProcessExecutor processExecutor, final ExecutorService executorService,
            final ExitValueResultHandler exitValueResultHandler) {
        this.processExecutor = processExecutor;
        this.executorService = executorService;
        this.exitValueResultHandler = exitValueResultHandler;
    }
    public ProcessInboundChannelAdapter(final ProcessExecutor processExecutor, final ExecutorService executorService) {
        this(processExecutor, executorService, new OnNokExitValueExceptionThrowingExitValueHandler());
    }

    @Override
    public Message<ProcessRunResult> receive() {
        final ProcessRunResult result = exitValueResultHandler.handleResult(processExecutor.execute(executorService));
        return MessageBuilder.withPayload(result).build();
    }
}

Add result handling to the adapter -- now for real, actually.


package com.netflix.governator.visitors;

import com.google.inject.Binding;
import com.google.inject.spi.DefaultBindingTargetVisitor;
import com.google.inject.spi.DefaultElementVisitor;
import com.google.inject.spi.InstanceBinding;
import com.google.inject.spi.ProviderInstanceBinding;

public class WarnOfToInstanceInjectionVisitor extends DefaultElementVisitor<String> {
    public <T> String visit(Binding<T> binding) {
        return binding.acceptTargetVisitor(new DefaultBindingTargetVisitor<T, String>() {
            public String visit(InstanceBinding<? extends T> instanceBinding) {
                return String.format("toInstance() at %s can force undesireable static initialization.  " +
                        "Consider replacing with an @Provides method instead.",
                        instanceBinding.getSource());
            }

            public String visit(ProviderInstanceBinding<? extends T> providerInstanceBinding) {
                return String.format("toInstance() at %s can force undesireable static initialization.  " +
                        "Consider replacing with an @Provides method instead.",
                        providerInstanceBinding.getSource());
            }
        });
    }
}

package com.netflix.governator.visitors;

import com.google.inject.Binding;
import com.google.inject.spi.DefaultBindingTargetVisitor;
import com.google.inject.spi.DefaultElementVisitor;
import com.google.inject.spi.InstanceBinding;

public class WarnOfToInstanceInjectionVisitor extends DefaultElementVisitor<String> {
    public <T> String visit(Binding<T> binding) {
        return binding.acceptTargetVisitor(new DefaultBindingTargetVisitor<T, String>() {
            public String visit(InstanceBinding<? extends T> instanceBinding) {
                return String.format("toInstance() at %s can force undesireable static initialization.  " +
                        "Consider replacing with an @Provides method instead.",
                        instanceBinding.getSource());
            }
        });
    }
}

Remove ProviderInstanceBinding as it also captures @Provides methods


/*-
 * Copyright 2016 Diamond Light Source Ltd.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */

package org.eclipse.dawnsci.analysis.api.processing;

import java.util.List;

/**
 * Interface to set up an operation processing run
 */
public interface IOperationBean {

	public void setDataKey(String dataKey);

	public void setFilePath(String filePath);

	public String getFilePath();

	public void setOutputFilePath(String outputFilePath);

	public String getOutputFilePath();

	public void setDatasetPath(String datasetPath);

	public void setSlicing(String slicing);

	public void setProcessingPath(String processingPath);

	public void setAxesNames(List<String>[] axesNames);

	public void setDeleteProcessingFile(boolean deleteProcessingFile);

	public void setXmx(String xmx);

	public void setDataDimensions(int[] dataDimensions);

	public void setScanRank(int scanRank);

	public void setReadable(boolean readable);

	public void setName(String name);

	public void setRunDirectory(String runDirectory);

	public void setNumberOfCores(int numberOfCores);

}

/*-
 * Copyright 2016 Diamond Light Source Ltd.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */

package org.eclipse.dawnsci.analysis.api.processing;

import java.util.List;

/**
 * Interface to set up an operation processing run
 */
public interface IOperationBean {

	public void setDataKey(String dataKey);

	public void setFilePath(String filePath);

	public String getFilePath();

	public void setOutputFilePath(String outputFilePath);

	public String getOutputFilePath();

	public void setDatasetPath(String datasetPath);

	public void setSlicing(String slicing);

	public void setProcessingPath(String processingPath);

	public void setAxesNames(List<String>[] axesNames);

	public void setDeleteProcessingFile(boolean deleteProcessingFile);

	public void setXmx(String xmx);

	public void setDataDimensions(int[] dataDimensions);

	public void setScanRank(Integer scanRank);

	public void setReadable(boolean readable);

	public void setName(String name);

	public void setRunDirectory(String runDirectory);

	public void setNumberOfCores(int numberOfCores);

}

Change to use boxed type

Change to use boxed type


package org.metaborg.spoofax.eclipse.logging;

import java.io.InputStream;

import org.slf4j.ILoggerFactory;
import org.slf4j.impl.StaticLoggerBinder;

import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.ContextBase;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;

public class LoggingConfiguration {
    public static void configure(Class<?> clazz, String location) {
        final ILoggerFactory loggerFactory = StaticLoggerBinder.getSingleton().getLoggerFactory();
        final ContextBase context = (ContextBase) loggerFactory;
        try {
            final JoranConfigurator configurator = new JoranConfigurator();
            configurator.setContext(context);
            context.reset();
            final InputStream configStream = clazz.getResourceAsStream(location);
            configurator.doConfigure(configStream);
        } catch(JoranException je) {
            // Ignore exception, StatusPrinter will handle it.
        }
        StatusPrinter.printInCaseOfErrorsOrWarnings(context);
    }
}

package org.metaborg.spoofax.eclipse.logging;

import java.io.InputStream;

import org.slf4j.ILoggerFactory;
import org.slf4j.impl.StaticLoggerBinder;

import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.ContextBase;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;

public class LoggingConfiguration {
    public static void configure(Class<?> clazz, String location) {
        System.err.println("Configuring logging framework for Spoofax");
        final ILoggerFactory loggerFactory = StaticLoggerBinder.getSingleton().getLoggerFactory();
        final ContextBase context = (ContextBase) loggerFactory;
        try {
            System.err.println("Reading logging configuration from resource " + location + " in " + clazz);
            final JoranConfigurator configurator = new JoranConfigurator();
            configurator.setContext(context);
            context.reset();
            final InputStream configStream = clazz.getResourceAsStream(location);
            configurator.doConfigure(configStream);
        } catch(JoranException je) {
            // Ignore exception, StatusPrinter will handle it.
        }
        StatusPrinter.printInCaseOfErrorsOrWarnings(context);
    }
}

Print some diagnostic information when setting up the logging configuration.


package codesample.java_se_api.concurency.collections;

import java.io.IOException;
import java.util.concurrent.SynchronousQueue;

/**
 * SynchronousQueue provides a powerful concurrency mechanism to synchronize work in different threads.
 * In order to take() element from queue a call to put() should be active from another thread. At the same time
 * in order to put() something in a queue, a call to take() should be pending from other thread.
 */
class SynchronousQueueExample {
    public static void main(String args[]) throws InterruptedException {

        SynchronousQueue<String> str = new SynchronousQueue<>();

        Thread tr = new Thread(new MyRunnable(str));
        tr.start();
        str.put("kek");

        System.out.println("Finished");
    }

    private static class MyRunnable implements Runnable {

        final SynchronousQueue<String> queue;

        MyRunnable(SynchronousQueue<String> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                System.out.println(queue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

package codesample.java_se_api.concurency.collections;

import java.util.concurrent.SynchronousQueue;

/**
 * SynchronousQueue provides a powerful concurrency mechanism to synchronize work in different threads.
 * In order to take() element from queue a call to put() should be active from another thread. At the same time
 * in order to put() something in a queue, a call to take() should be pending from other thread.
 */
class SynchronousQueueExample {
    public static void main(String args[]) throws InterruptedException {

        SynchronousQueue<String> queue = new SynchronousQueue<>();

        Thread taker = new Thread(new SynchronousQueueTaker(queue));
        taker.start();

        System.out.println("Nothing in output, because taker thread has nothing to take thus it's blocked");

        Thread putter = new Thread(new SynchronousQueuePutter(queue, "Value passed to putter!"));
        putter.start();

        /* Wait for both threads before outputting finish*/
        taker.join();
        putter.join();
        System.out.println("Finished");

    }

    private static class SynchronousQueueTaker implements Runnable {

        final SynchronousQueue<String> queue;

        SynchronousQueueTaker(SynchronousQueue<String> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                System.out.println(queue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    private static class SynchronousQueuePutter implements Runnable {

        final SynchronousQueue<String> queue;
        final String value;

        SynchronousQueuePutter(SynchronousQueue<String> queue, String value) {
            this.queue = queue;
            this.value = value;
        }

        @Override
        public void run() {
            try {
                queue.put(value);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Add better sync queue example

Add better sync queue example


package uk.ac.ebi.spot.goci.curation.service.batchloader;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import uk.ac.ebi.spot.goci.curation.model.BatchUploadError;
import uk.ac.ebi.spot.goci.curation.model.batchloader.BatchUploadRow;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.Study;

import java.io.IOException;
import java.util.Collection;

/**
 * Created by emma on 21/03/2016.
 *
 * @author emma
 *

 *         Upload, error check and create persistance obejects that can be saved in DB from a batch of SNPs from a .xlsx
 *         spreadsheet. Note that the spreadsheet must be of .xlsx format!
 *

 *         Created from code originally written by Dani. Adapted to fit with new curation system.
 */
public interface AssociationBatchLoaderService {

    Collection<BatchUploadError> processFile(String fileName, Study study) throws InvalidFormatException, IOException;

    Collection<Association> processFileRows(Collection<BatchUploadRow> batchUploadRows);

    Collection<BatchUploadError> checkUploadForErrors(Collection<BatchUploadRow> batchUploadRows);

    void saveAssociations(Collection<Association> associations, Study study);
}

package uk.ac.ebi.spot.goci.curation.service.batchloader;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import uk.ac.ebi.spot.goci.curation.model.batchloader.BatchUploadError;
import uk.ac.ebi.spot.goci.curation.model.batchloader.BatchUploadRow;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.Study;

import java.io.IOException;
import java.util.Collection;

/**
 * Created by emma on 21/03/2016.
 *
 * @author emma
 *

 *         Upload, error check and create persistance obejects that can be saved in DB from a batch of SNPs from a .xlsx
 *         spreadsheet. Note that the spreadsheet must be of .xlsx format!
 *

 *         Created from code originally written by Dani. Adapted to fit with new curation system.
 */
public interface AssociationBatchLoaderService {

    Collection<BatchUploadRow> processFile(String fileName, Study study) throws InvalidFormatException, IOException;

    Collection<Association> processFileRows(Collection<BatchUploadRow> batchUploadRows);

    Collection<BatchUploadError> checkUploadForErrors(Collection<BatchUploadRow> batchUploadRows);

    void saveAssociations(Collection<Association> associations, Study study);

    void deleteFile(String fileName);
}

Add new method to delete file

Add new method to delete file


package org.muml.psm.allocation.algorithm.ilp.lpsolve.tests;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({
	LPSolveM2TTest.class
})
public class AllTestsSuite {

}

package org.muml.psm.allocation.algorithm.ilp.lpsolve.tests;

import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import org.muml.psm.allocation.ilp.lpsolve.xtext.LPSolveStandaloneSetup;

@RunWith(Suite.class)
@SuiteClasses({
	LPSolveM2TTest.class
})
public class AllTestsSuite {
	@BeforeClass
	public static void setup() {
		LPSolveStandaloneSetup.doSetup();
	}
}

Make sure the *.lp file extension is registered (testsuite)


/*
 * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

package org.opendaylight.controller.md.sal.common.api.data;

import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;

/**
*
* Failure of asynchronous transaction commit caused by failure
* of optimistic locking.
*
* This exception is raised and returned when transaction commit
* failed, because other transaction finished successfully
* and modified same data as failed transaction.
*
*  Clients may recover from this error condition by
*  retrieving current state and submitting new updated
*  transaction.
*
*/
public class OptimisticLockFailedException extends TransactionCommitFailedException {

    private static final long serialVersionUID = 1L;

    public OptimisticLockFailedException(final String message, final Throwable cause) {
        super(message, cause, RpcResultBuilder.newError(ErrorType.APPLICATION, "resource-denied",
                                                        message, null, null, cause));
    }

    public OptimisticLockFailedException(final String message) {
        this(message, null);
    }

}

Fix license header violations in sal-common-api

Change-Id: I58fdef120495514ef94f2e9681790786ba4e0841
Signed-off-by: Thanh Ha <09ea4d3a79c8bee41a16519f6a431f6bc0fd8d6f@linuxfoundation.org>


package ciir.jfoley.chai;

import ciir.jfoley.chai.io.Streams;
import ciir.jfoley.chai.string.StrUtil;

import java.io.IOException;
import java.util.Arrays;

/**
 * Interface to Java's lackluster Process API.
 * @author jfoley.
 */
public class Spawn {
	public static void doProcess(String... args) throws IOException, InterruptedException {
		Process exec = Runtime.getRuntime().exec(args);
		int status = exec.waitFor();
		Streams.copy(exec.getErrorStream(), System.err);
		Streams.copy(exec.getInputStream(), System.err);
		System.err.println("# status: " + status + " for: " + StrUtil.join(Arrays.asList(args), " "));
		if(status != 0) throw new RuntimeException();
	}
}

package ciir.jfoley.chai;

import ciir.jfoley.chai.io.Streams;
import ciir.jfoley.chai.string.StrUtil;

import java.io.IOException;
import java.util.Arrays;

/**
 * Interface to Java's lackluster Process API.
 * @author jfoley.
 */
public class Spawn {
	public static void doProcess(int expectedStatus, String... args) throws IOException, InterruptedException {
		Process exec = Runtime.getRuntime().exec(args);
		int status = exec.waitFor();
		Streams.copy(exec.getErrorStream(), System.err);
		Streams.copy(exec.getInputStream(), System.err);
		System.err.println("# status: " + status + " for: " + StrUtil.join(Arrays.asList(args), " "));
		if(status != expectedStatus) throw new RuntimeException();
	}

  public static void doProcess(String... args) throws IOException, InterruptedException {
    doProcess(0, args);
  }
}

Allow expecting a different status code.


/*******************************************************************************
 * Copyright (c) 2004 Actuate Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *  Actuate Corporation  - initial API and implementation
 *******************************************************************************/

package org.eclipse.birt.report.item.crosstab.internal.ui.dialogs;

import org.eclipse.birt.report.designer.ui.dialogs.ExpressionProvider;
import org.eclipse.birt.report.designer.ui.expressions.ExpressionFilter;
import org.eclipse.birt.report.model.api.DesignElementHandle;

/**
 *
 */

public class CrosstabComputedMeasureExpressionProvider extends
		CrosstabExpressionProvider
{

	public CrosstabComputedMeasureExpressionProvider( DesignElementHandle handle )
	{
		super( handle, null );
	}

	protected void addFilterToProvider( )
	{
		this.addFilter( new ExpressionFilter( ) {

			public boolean select( Object parentElement, Object element )
			{
				if ( ExpressionFilter.CATEGORY.equals( parentElement )
						&& ExpressionProvider.CURRENT_CUBE.equals( element ) )
				{
					return false;
				}
				return true;
			}
		} );
	}

}

/*******************************************************************************
 * Copyright (c) 2004 Actuate Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *  Actuate Corporation  - initial API and implementation
 *******************************************************************************/

package org.eclipse.birt.report.item.crosstab.internal.ui.dialogs;

import org.eclipse.birt.report.designer.ui.dialogs.ExpressionProvider;
import org.eclipse.birt.report.designer.ui.expressions.ExpressionFilter;
import org.eclipse.birt.report.model.api.DesignElementHandle;

/**
 *
 */

public class CrosstabComputedMeasureExpressionProvider extends
		CrosstabExpressionProvider
{

	public CrosstabComputedMeasureExpressionProvider( DesignElementHandle handle )
	{
		super( handle, null );
	}

//	protected void addFilterToProvider( )
//	{
//		this.addFilter( new ExpressionFilter( ) {
//
//			public boolean select( Object parentElement, Object element )
//			{
//				if ( ExpressionFilter.CATEGORY.equals( parentElement )
//						&& ExpressionProvider.CURRENT_CUBE.equals( element ) )
//				{
//					return false;
//				}
//				return true;
//			}
//		} );
//	}

}

Remove the restriction on cube element on the expression builder when creating a derived measure.


package com.hida.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.Type;

/**
 *
 * @author lruffin
 */
@Entity
@Table(name = "USED_SETTING")
public class UsedSetting extends Setting{

    @NotNull
    @Column(name="AMOUNT")
    @Type(type="long")
    private long Amount;

    /**
     * Constructor; missing javadoc
     *
     * @param Prepend
     * @param Prefix
     * @param TokenType
     * @param CharMap
     * @param RootLength
     * @param SansVowels
     * @param Amount
     */
    public UsedSetting(String Prepend, String Prefix, TokenType TokenType, String CharMap,
            int RootLength, boolean SansVowels, long Amount) {
        super(Prefix, TokenType, CharMap, RootLength, SansVowels);
        this.Amount = Amount;

    }

    /**
     * Default constructor
     */
    public UsedSetting() {

    }

    public long getAmount() {
        return Amount;
    }

    public void setAmount(long Amount) {
        this.Amount = Amount;
    }

}

package com.hida.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.Type;

/**
 *
 * @author lruffin
 */
@Entity
@Table(name = "USED_SETTING")
public class UsedSetting extends Setting{

    @NotNull
    @Column(name="AMOUNT")
    @Type(type="long")
    private long Amount;

    /**
     * Constructor; missing javadoc
     *
     * @param Prefix
     * @param TokenType
     * @param CharMap
     * @param RootLength
     * @param SansVowels
     * @param Amount
     */
    public UsedSetting(String Prefix, TokenType TokenType, String CharMap,
            int RootLength, boolean SansVowels, long Amount) {
        super(Prefix, TokenType, CharMap, RootLength, SansVowels);
        this.Amount = Amount;

    }

    /**
     * Default constructor
     */
    public UsedSetting() {

    }

    public long getAmount() {
        return Amount;
    }

    public void setAmount(long Amount) {
        this.Amount = Amount;
    }

}

Remove all instances of Prepend

Remove all instances of Prepend

Prepend was removed because it does not strictly contribute to the
creation of Pids; instead it is added to turn Pids into a URL specific
to the organization that created them.


/*
 * Copyright 2017 - 2018 Anton Tananaev (anton@traccar.org)
 *
 * 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.traccar.protocol;

import org.traccar.BaseProtocol;
import org.traccar.CharacterDelimiterFrameDecoder;
import org.traccar.PipelineBuilder;
import org.traccar.TrackerServer;

import java.util.List;

public class TlvProtocol extends BaseProtocol {

    public TlvProtocol() {
        super("tlv");
    }

    @Override
    public void initTrackerServers(List<TrackerServer> serverList) {
        serverList.add(new TrackerServer(false, getName()) {
            @Override
            protected void addProtocolHandlers(PipelineBuilder pipeline) {
                pipeline.addLast("frameDecoder", new CharacterDelimiterFrameDecoder('\0'));
                pipeline.addLast("objectDecoder", new TlvProtocolDecoder(TlvProtocol.this));
            }
        });
    }

}

/*
 * Copyright 2017 - 2018 Anton Tananaev (anton@traccar.org)
 *
 * 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.traccar.protocol;

import org.traccar.BaseProtocol;
import org.traccar.CharacterDelimiterFrameDecoder;
import org.traccar.PipelineBuilder;
import org.traccar.TrackerServer;

import java.util.List;

public class TlvProtocol extends BaseProtocol {

    public TlvProtocol() {
        super("tlv");
    }

    @Override
    public void initTrackerServers(List<TrackerServer> serverList) {
        serverList.add(new TrackerServer(false, getName()) {
            @Override
            protected void addProtocolHandlers(PipelineBuilder pipeline) {
                pipeline.addLast("frameDecoder", new CharacterDelimiterFrameDecoder(1024, '\0'));
                pipeline.addLast("objectDecoder", new TlvProtocolDecoder(TlvProtocol.this));
            }
        });
    }

}

Fix issue with TLV frame decoder

Fix issue with TLV frame decoder


package controller;

import boundary.BuilderApplication;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import model.BuilderModel;

/**
 * The controller to handle altered number weights.
 *
 * @author Cem Unsal
 */
public class BuilderNumberWeightCtrl implements ChangeListener {
  BuilderApplication app;
  BuilderModel model;
  int number;

  /**
   * Create a BuilderMultiplierWeightCtrl, given a BuilderApplication and a
   * BuilderModel for context.
   *
   * @param app
   * @param model
   * @param multiplier The multiplier to which this controller applies.
   */
  public BuilderNumberWeightCtrl(BuilderApplication app, BuilderModel model,
      int number) {
    this.app = app;
    this.model = model;
    this.number = number;
  }

  /**
   * Handle the slider's value changing.
   *
   * @param event Details about the ChangeEvent, including the relevant JSlider.
   */
  @Override
  public void stateChanged(ChangeEvent event) {
    JSlider source = (JSlider) event.getSource();
    int val = source.getValue();
    model.level.rules.numberWeights[number] = val;
    model.takeSnapshot();
  }
}

package controller;

import boundary.BuilderApplication;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import model.BuilderModel;

/**
 * The controller to handle altered number weights.
 *
 * Example probability distributions:
 *
 * <pre>
 * 16.7%, 16.7%, 16.7%, 16.7%, 16.7%, 16.7%
 * 1,     1,     1,     1,     1,     1     => 6
 *
 * 10%,   18%,   18%,   18%,   18%,   18%
 * 5,     9,     9,     9,     9,     9     => 50
 *
 * 10%,   20%,   17.5%, 17.5%, 17.5%, 17.5%
 * 4,     8,     7,     7,     7,     7     => 40
 * </pre>
 *
 * @author Cem Unsal
 */
public class BuilderNumberWeightCtrl implements ChangeListener {
  BuilderApplication app;
  BuilderModel model;
  int number;

  /**
   * Create a BuilderMultiplierWeightCtrl, given a BuilderApplication and a
   * BuilderModel for context.
   *
   * @param app
   * @param model
   * @param multiplier The multiplier to which this controller applies.
   */
  public BuilderNumberWeightCtrl(BuilderApplication app, BuilderModel model,
      int number) {
    this.app = app;
    this.model = model;
    this.number = number;
  }

  /**
   * Handle the slider's value changing.
   *
   * @param event Details about the ChangeEvent, including the relevant JSlider.
   */
  @Override
  public void stateChanged(ChangeEvent event) {
    JSlider source = (JSlider) event.getSource();
    int val = source.getValue();
    model.level.rules.numberWeights[number] = val;
    model.takeSnapshot();
  }
}

Add comment about number weights

Add comment about number weights

Signed-off-by: Eli Skeggs <9586c285e7eef0e86d45536fe84e916128618137@wpi.edu>