repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
voostindie/sprox
src/test/java/nl/ulso/sprox/movies/FirstMovieFirstStarSelectorTest.java
// Path: src/main/java/nl/ulso/sprox/XmlProcessor.java // public interface XmlProcessor<T> { // // /** // * Process XML by pulling it from a reader. The reader is not closed. If buffering is needed, this must be // * provided by the caller. // * // * @param reader The reader to pull the XML from. // * @return The result of processing the XML; is {@code null} only if {@code T} is {@link java.lang.Void}. // * @throws XmlProcessorException If an error occurred while processing the XML // */ // T execute(Reader reader) throws XmlProcessorException; // // /** // * Process XML by pulling it from an input stream. The input stream is not closed. If buffering is needed, this // * must be provided by the caller. // * // * @param inputStream The stream to pull the XML from. // * @return The result of processing the XML; is {@code null} only if {@code T} is {@link java.lang.Void}. // * @throws XmlProcessorException If an error occurred while processing the XML // */ // T execute(InputStream inputStream) throws XmlProcessorException; // } // // Path: src/test/java/nl/ulso/sprox/SproxTests.java // public static <T> XmlProcessorBuilder<T> createXmlProcessorBuilder(Class<T> resultClass) { // return new StaxBasedXmlProcessorBuilderFactory().createXmlProcessorBuilder(requireNonNull(resultClass)); // }
import nl.ulso.sprox.Node; import nl.ulso.sprox.XmlProcessor; import org.junit.Test; import static nl.ulso.sprox.SproxTests.createXmlProcessorBuilder; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat;
package nl.ulso.sprox.movies; public class FirstMovieFirstStarSelectorTest { @Test public void testInjectionOfSingleObjects() throws Exception {
// Path: src/main/java/nl/ulso/sprox/XmlProcessor.java // public interface XmlProcessor<T> { // // /** // * Process XML by pulling it from a reader. The reader is not closed. If buffering is needed, this must be // * provided by the caller. // * // * @param reader The reader to pull the XML from. // * @return The result of processing the XML; is {@code null} only if {@code T} is {@link java.lang.Void}. // * @throws XmlProcessorException If an error occurred while processing the XML // */ // T execute(Reader reader) throws XmlProcessorException; // // /** // * Process XML by pulling it from an input stream. The input stream is not closed. If buffering is needed, this // * must be provided by the caller. // * // * @param inputStream The stream to pull the XML from. // * @return The result of processing the XML; is {@code null} only if {@code T} is {@link java.lang.Void}. // * @throws XmlProcessorException If an error occurred while processing the XML // */ // T execute(InputStream inputStream) throws XmlProcessorException; // } // // Path: src/test/java/nl/ulso/sprox/SproxTests.java // public static <T> XmlProcessorBuilder<T> createXmlProcessorBuilder(Class<T> resultClass) { // return new StaxBasedXmlProcessorBuilderFactory().createXmlProcessorBuilder(requireNonNull(resultClass)); // } // Path: src/test/java/nl/ulso/sprox/movies/FirstMovieFirstStarSelectorTest.java import nl.ulso.sprox.Node; import nl.ulso.sprox.XmlProcessor; import org.junit.Test; import static nl.ulso.sprox.SproxTests.createXmlProcessorBuilder; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; package nl.ulso.sprox.movies; public class FirstMovieFirstStarSelectorTest { @Test public void testInjectionOfSingleObjects() throws Exception {
final XmlProcessor<Movie> processor = createXmlProcessorBuilder(Movie.class)
voostindie/sprox
src/test/java/nl/ulso/sprox/movies/FirstMovieFirstStarSelectorTest.java
// Path: src/main/java/nl/ulso/sprox/XmlProcessor.java // public interface XmlProcessor<T> { // // /** // * Process XML by pulling it from a reader. The reader is not closed. If buffering is needed, this must be // * provided by the caller. // * // * @param reader The reader to pull the XML from. // * @return The result of processing the XML; is {@code null} only if {@code T} is {@link java.lang.Void}. // * @throws XmlProcessorException If an error occurred while processing the XML // */ // T execute(Reader reader) throws XmlProcessorException; // // /** // * Process XML by pulling it from an input stream. The input stream is not closed. If buffering is needed, this // * must be provided by the caller. // * // * @param inputStream The stream to pull the XML from. // * @return The result of processing the XML; is {@code null} only if {@code T} is {@link java.lang.Void}. // * @throws XmlProcessorException If an error occurred while processing the XML // */ // T execute(InputStream inputStream) throws XmlProcessorException; // } // // Path: src/test/java/nl/ulso/sprox/SproxTests.java // public static <T> XmlProcessorBuilder<T> createXmlProcessorBuilder(Class<T> resultClass) { // return new StaxBasedXmlProcessorBuilderFactory().createXmlProcessorBuilder(requireNonNull(resultClass)); // }
import nl.ulso.sprox.Node; import nl.ulso.sprox.XmlProcessor; import org.junit.Test; import static nl.ulso.sprox.SproxTests.createXmlProcessorBuilder; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat;
package nl.ulso.sprox.movies; public class FirstMovieFirstStarSelectorTest { @Test public void testInjectionOfSingleObjects() throws Exception {
// Path: src/main/java/nl/ulso/sprox/XmlProcessor.java // public interface XmlProcessor<T> { // // /** // * Process XML by pulling it from a reader. The reader is not closed. If buffering is needed, this must be // * provided by the caller. // * // * @param reader The reader to pull the XML from. // * @return The result of processing the XML; is {@code null} only if {@code T} is {@link java.lang.Void}. // * @throws XmlProcessorException If an error occurred while processing the XML // */ // T execute(Reader reader) throws XmlProcessorException; // // /** // * Process XML by pulling it from an input stream. The input stream is not closed. If buffering is needed, this // * must be provided by the caller. // * // * @param inputStream The stream to pull the XML from. // * @return The result of processing the XML; is {@code null} only if {@code T} is {@link java.lang.Void}. // * @throws XmlProcessorException If an error occurred while processing the XML // */ // T execute(InputStream inputStream) throws XmlProcessorException; // } // // Path: src/test/java/nl/ulso/sprox/SproxTests.java // public static <T> XmlProcessorBuilder<T> createXmlProcessorBuilder(Class<T> resultClass) { // return new StaxBasedXmlProcessorBuilderFactory().createXmlProcessorBuilder(requireNonNull(resultClass)); // } // Path: src/test/java/nl/ulso/sprox/movies/FirstMovieFirstStarSelectorTest.java import nl.ulso.sprox.Node; import nl.ulso.sprox.XmlProcessor; import org.junit.Test; import static nl.ulso.sprox.SproxTests.createXmlProcessorBuilder; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; package nl.ulso.sprox.movies; public class FirstMovieFirstStarSelectorTest { @Test public void testInjectionOfSingleObjects() throws Exception {
final XmlProcessor<Movie> processor = createXmlProcessorBuilder(Movie.class)
voostindie/sprox
src/main/java/nl/ulso/sprox/parsers/ShortParser.java
// Path: src/main/java/nl/ulso/sprox/ParseException.java // public final class ParseException extends XmlProcessorException { // public ParseException(Class resultClass, String value) { // super(createMessage(resultClass, value)); // } // // public ParseException(Class resultClass, String value, Throwable cause) { // super(createMessage(resultClass, value), cause); // } // // private static String createMessage(Class resultClass, String value) { // return "Could not parse string \"" + value + "\" into a value of type \"" + resultClass + "\""; // } // } // // Path: src/main/java/nl/ulso/sprox/Parser.java // public interface Parser<T> { // // /** // * Parses a string value into a specific type. // * // * @param value String value to parse. // * @return The result of parsing the value. // * @throws ParseException If the value could not be parsed. // */ // T fromString(String value) throws ParseException; // }
import nl.ulso.sprox.ParseException; import nl.ulso.sprox.Parser;
package nl.ulso.sprox.parsers; public class ShortParser implements Parser<Short> { @Override
// Path: src/main/java/nl/ulso/sprox/ParseException.java // public final class ParseException extends XmlProcessorException { // public ParseException(Class resultClass, String value) { // super(createMessage(resultClass, value)); // } // // public ParseException(Class resultClass, String value, Throwable cause) { // super(createMessage(resultClass, value), cause); // } // // private static String createMessage(Class resultClass, String value) { // return "Could not parse string \"" + value + "\" into a value of type \"" + resultClass + "\""; // } // } // // Path: src/main/java/nl/ulso/sprox/Parser.java // public interface Parser<T> { // // /** // * Parses a string value into a specific type. // * // * @param value String value to parse. // * @return The result of parsing the value. // * @throws ParseException If the value could not be parsed. // */ // T fromString(String value) throws ParseException; // } // Path: src/main/java/nl/ulso/sprox/parsers/ShortParser.java import nl.ulso.sprox.ParseException; import nl.ulso.sprox.Parser; package nl.ulso.sprox.parsers; public class ShortParser implements Parser<Short> { @Override
public Short fromString(String value) throws ParseException {
voostindie/sprox
src/test/java/nl/ulso/sprox/NodeAttributeTest.java
// Path: src/test/java/nl/ulso/sprox/NodeAttributeTest.java // public static final class PrimitiveInjectionProcessor { // @Node("root") // public Primitives mapPrimitives(@Attribute("i") int i, @Attribute("s") short s, @Attribute("l") long l, // @Attribute("f") float f, @Attribute("d") double d, @Attribute("b") byte b, // @Attribute("c") char c) { // return new Primitives(i, s, l, f, d, b, c); // } // } // // Path: src/test/java/nl/ulso/sprox/SproxTests.java // public static <T> void testControllers(T expected, String xml, Object... controllers) throws Exception { // @SuppressWarnings("unchecked") // final XmlProcessorBuilder<Object> builder = (XmlProcessorBuilder<Object>) createXmlProcessorBuilder(expected.getClass()); // for (Object controller : controllers) { // if (controller instanceof Class) { // builder.addControllerClass((Class) controller); // } else if (controller instanceof ControllerFactory) { // builder.addControllerFactory((ControllerFactory<?>) controller); // } else { // builder.addControllerObject(controller); // } // } // final XmlProcessor<Object> processor = builder.buildXmlProcessor(); // testProcessor(expected, xml, processor); // }
import org.junit.Test; import java.util.List; import static java.lang.Double.compare; import static java.lang.Double.doubleToLongBits; import static java.lang.Float.floatToIntBits; import static java.lang.Integer.parseInt; import static java.util.Collections.reverse; import static nl.ulso.sprox.NodeAttributeTest.Primitives.PrimitiveInjectionProcessor; import static nl.ulso.sprox.SproxTests.testControllers;
package nl.ulso.sprox; public class NodeAttributeTest { @Test public void testThatControllersAreProcessedInOrder() throws Exception {
// Path: src/test/java/nl/ulso/sprox/NodeAttributeTest.java // public static final class PrimitiveInjectionProcessor { // @Node("root") // public Primitives mapPrimitives(@Attribute("i") int i, @Attribute("s") short s, @Attribute("l") long l, // @Attribute("f") float f, @Attribute("d") double d, @Attribute("b") byte b, // @Attribute("c") char c) { // return new Primitives(i, s, l, f, d, b, c); // } // } // // Path: src/test/java/nl/ulso/sprox/SproxTests.java // public static <T> void testControllers(T expected, String xml, Object... controllers) throws Exception { // @SuppressWarnings("unchecked") // final XmlProcessorBuilder<Object> builder = (XmlProcessorBuilder<Object>) createXmlProcessorBuilder(expected.getClass()); // for (Object controller : controllers) { // if (controller instanceof Class) { // builder.addControllerClass((Class) controller); // } else if (controller instanceof ControllerFactory) { // builder.addControllerFactory((ControllerFactory<?>) controller); // } else { // builder.addControllerObject(controller); // } // } // final XmlProcessor<Object> processor = builder.buildXmlProcessor(); // testProcessor(expected, xml, processor); // } // Path: src/test/java/nl/ulso/sprox/NodeAttributeTest.java import org.junit.Test; import java.util.List; import static java.lang.Double.compare; import static java.lang.Double.doubleToLongBits; import static java.lang.Float.floatToIntBits; import static java.lang.Integer.parseInt; import static java.util.Collections.reverse; import static nl.ulso.sprox.NodeAttributeTest.Primitives.PrimitiveInjectionProcessor; import static nl.ulso.sprox.SproxTests.testControllers; package nl.ulso.sprox; public class NodeAttributeTest { @Test public void testThatControllersAreProcessedInOrder() throws Exception {
testControllers("[1, 2, 3, 4]",
voostindie/sprox
src/test/java/nl/ulso/sprox/NodeAttributeTest.java
// Path: src/test/java/nl/ulso/sprox/NodeAttributeTest.java // public static final class PrimitiveInjectionProcessor { // @Node("root") // public Primitives mapPrimitives(@Attribute("i") int i, @Attribute("s") short s, @Attribute("l") long l, // @Attribute("f") float f, @Attribute("d") double d, @Attribute("b") byte b, // @Attribute("c") char c) { // return new Primitives(i, s, l, f, d, b, c); // } // } // // Path: src/test/java/nl/ulso/sprox/SproxTests.java // public static <T> void testControllers(T expected, String xml, Object... controllers) throws Exception { // @SuppressWarnings("unchecked") // final XmlProcessorBuilder<Object> builder = (XmlProcessorBuilder<Object>) createXmlProcessorBuilder(expected.getClass()); // for (Object controller : controllers) { // if (controller instanceof Class) { // builder.addControllerClass((Class) controller); // } else if (controller instanceof ControllerFactory) { // builder.addControllerFactory((ControllerFactory<?>) controller); // } else { // builder.addControllerObject(controller); // } // } // final XmlProcessor<Object> processor = builder.buildXmlProcessor(); // testProcessor(expected, xml, processor); // }
import org.junit.Test; import java.util.List; import static java.lang.Double.compare; import static java.lang.Double.doubleToLongBits; import static java.lang.Float.floatToIntBits; import static java.lang.Integer.parseInt; import static java.util.Collections.reverse; import static nl.ulso.sprox.NodeAttributeTest.Primitives.PrimitiveInjectionProcessor; import static nl.ulso.sprox.SproxTests.testControllers;
package nl.ulso.sprox; public class NodeAttributeTest { @Test public void testThatControllersAreProcessedInOrder() throws Exception { testControllers("[1, 2, 3, 4]", "<root><node i=\"1\"><node i=\"2\"><node i=\"3\"><node i=\"4\"></node></node></node></node></root>", new NestedNodeAttributeProcessor(), new NodeLevel1AttributeProcessor(), new NodeLevel2AttributeProcessor(), new NodeLevel3AttributeProcessor(), new NodeLevel4AttributeProcessor() ); } @Test public void testMappingForPrimitivesInAttributes() throws Exception { final Primitives primitives = new Primitives(299792458, (short) 42, 42l, 2.72f, 3.14, (byte) 16, 'V'); testControllers(primitives, "<root i=\"299792458\" s=\"42\" l=\"42\" f=\"2.72\" d=\"3.14\" b=\"16\" c=\"V\"/>",
// Path: src/test/java/nl/ulso/sprox/NodeAttributeTest.java // public static final class PrimitiveInjectionProcessor { // @Node("root") // public Primitives mapPrimitives(@Attribute("i") int i, @Attribute("s") short s, @Attribute("l") long l, // @Attribute("f") float f, @Attribute("d") double d, @Attribute("b") byte b, // @Attribute("c") char c) { // return new Primitives(i, s, l, f, d, b, c); // } // } // // Path: src/test/java/nl/ulso/sprox/SproxTests.java // public static <T> void testControllers(T expected, String xml, Object... controllers) throws Exception { // @SuppressWarnings("unchecked") // final XmlProcessorBuilder<Object> builder = (XmlProcessorBuilder<Object>) createXmlProcessorBuilder(expected.getClass()); // for (Object controller : controllers) { // if (controller instanceof Class) { // builder.addControllerClass((Class) controller); // } else if (controller instanceof ControllerFactory) { // builder.addControllerFactory((ControllerFactory<?>) controller); // } else { // builder.addControllerObject(controller); // } // } // final XmlProcessor<Object> processor = builder.buildXmlProcessor(); // testProcessor(expected, xml, processor); // } // Path: src/test/java/nl/ulso/sprox/NodeAttributeTest.java import org.junit.Test; import java.util.List; import static java.lang.Double.compare; import static java.lang.Double.doubleToLongBits; import static java.lang.Float.floatToIntBits; import static java.lang.Integer.parseInt; import static java.util.Collections.reverse; import static nl.ulso.sprox.NodeAttributeTest.Primitives.PrimitiveInjectionProcessor; import static nl.ulso.sprox.SproxTests.testControllers; package nl.ulso.sprox; public class NodeAttributeTest { @Test public void testThatControllersAreProcessedInOrder() throws Exception { testControllers("[1, 2, 3, 4]", "<root><node i=\"1\"><node i=\"2\"><node i=\"3\"><node i=\"4\"></node></node></node></node></root>", new NestedNodeAttributeProcessor(), new NodeLevel1AttributeProcessor(), new NodeLevel2AttributeProcessor(), new NodeLevel3AttributeProcessor(), new NodeLevel4AttributeProcessor() ); } @Test public void testMappingForPrimitivesInAttributes() throws Exception { final Primitives primitives = new Primitives(299792458, (short) 42, 42l, 2.72f, 3.14, (byte) 16, 'V'); testControllers(primitives, "<root i=\"299792458\" s=\"42\" l=\"42\" f=\"2.72\" d=\"3.14\" b=\"16\" c=\"V\"/>",
new PrimitiveInjectionProcessor());
voostindie/sprox
src/test/java/nl/ulso/sprox/atom/DateTimeParser.java
// Path: src/main/java/nl/ulso/sprox/ParseException.java // public final class ParseException extends XmlProcessorException { // public ParseException(Class resultClass, String value) { // super(createMessage(resultClass, value)); // } // // public ParseException(Class resultClass, String value, Throwable cause) { // super(createMessage(resultClass, value), cause); // } // // private static String createMessage(Class resultClass, String value) { // return "Could not parse string \"" + value + "\" into a value of type \"" + resultClass + "\""; // } // } // // Path: src/main/java/nl/ulso/sprox/Parser.java // public interface Parser<T> { // // /** // * Parses a string value into a specific type. // * // * @param value String value to parse. // * @return The result of parsing the value. // * @throws ParseException If the value could not be parsed. // */ // T fromString(String value) throws ParseException; // }
import nl.ulso.sprox.ParseException; import nl.ulso.sprox.Parser; import org.joda.time.DateTime; import static org.joda.time.DateTime.parse;
package nl.ulso.sprox.atom; public class DateTimeParser implements Parser<DateTime> { @Override
// Path: src/main/java/nl/ulso/sprox/ParseException.java // public final class ParseException extends XmlProcessorException { // public ParseException(Class resultClass, String value) { // super(createMessage(resultClass, value)); // } // // public ParseException(Class resultClass, String value, Throwable cause) { // super(createMessage(resultClass, value), cause); // } // // private static String createMessage(Class resultClass, String value) { // return "Could not parse string \"" + value + "\" into a value of type \"" + resultClass + "\""; // } // } // // Path: src/main/java/nl/ulso/sprox/Parser.java // public interface Parser<T> { // // /** // * Parses a string value into a specific type. // * // * @param value String value to parse. // * @return The result of parsing the value. // * @throws ParseException If the value could not be parsed. // */ // T fromString(String value) throws ParseException; // } // Path: src/test/java/nl/ulso/sprox/atom/DateTimeParser.java import nl.ulso.sprox.ParseException; import nl.ulso.sprox.Parser; import org.joda.time.DateTime; import static org.joda.time.DateTime.parse; package nl.ulso.sprox.atom; public class DateTimeParser implements Parser<DateTime> { @Override
public DateTime fromString(String value) throws ParseException {
icecondor/android
src/com/icecondor/nest/api/Dispatch.java
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // }
import android.util.Log; import com.icecondor.nest.Constants;
package com.icecondor.nest.api; public class Dispatch { public void process(String msg) {
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // } // Path: src/com/icecondor/nest/api/Dispatch.java import android.util.Log; import com.icecondor.nest.Constants; package com.icecondor.nest.api; public class Dispatch { public void process(String msg) {
Log.d(Constants.APP_TAG, "ws: "+msg);
icecondor/android
src/com/icecondor/nest/ui/login/TokenValidateFragment.java
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // }
import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.icecondor.nest.Constants; import com.icecondor.nest.R;
package com.icecondor.nest.ui.login; public class TokenValidateFragment extends Fragment { private TextView status; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState);
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // } // Path: src/com/icecondor/nest/ui/login/TokenValidateFragment.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.icecondor.nest.Constants; import com.icecondor.nest.R; package com.icecondor.nest.ui.login; public class TokenValidateFragment extends Fragment { private TextView status; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState);
Log.d(Constants.APP_TAG, "TokenValidateFragment onActivityCreated");
icecondor/android
src/com/icecondor/nest/ui/login/LoginEmailFragment.java
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // }
import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import com.icecondor.nest.Constants; import com.icecondor.nest.R;
package com.icecondor.nest.ui.login; public class LoginEmailFragment extends Fragment { private EditText emailField; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState);
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // } // Path: src/com/icecondor/nest/ui/login/LoginEmailFragment.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import com.icecondor.nest.Constants; import com.icecondor.nest.R; package com.icecondor.nest.ui.login; public class LoginEmailFragment extends Fragment { private EditText emailField; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState);
Log.d(Constants.APP_TAG, "LoginFragmentEmail onActivityCreated");
icecondor/android
src/com/icecondor/nest/db/Activity.java
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // }
import java.security.InvalidParameterException; import java.util.UUID; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.json.JSONException; import org.json.JSONObject; import android.content.ContentValues; import android.database.Cursor; import android.util.Log; import com.icecondor.nest.Constants;
json.put("date", date); json.put("type", type); } catch (JSONException e) { e.printStackTrace(); } } public Activity(JSONObject ijson) throws JSONException { if(ijson.getString("class").equals(getClass().getName())) { id = ijson.getString("id"); date = DateTime.parse(ijson.getString("date")); json.put("id", id); json.put("class", ijson.getString("class")); json.put("date", date); json.put("type", ijson.getString("type")); } else { throw new RuntimeException("Incompatible JSON for "+getClass().getName()); } } public DateTime getDateTime() { return date; } @Override public String getTableName() { return Database.TABLE_ACTIVITIES; } static public Cursor getAll(Database db, int i) { if(db == null) {
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // } // Path: src/com/icecondor/nest/db/Activity.java import java.security.InvalidParameterException; import java.util.UUID; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.json.JSONException; import org.json.JSONObject; import android.content.ContentValues; import android.database.Cursor; import android.util.Log; import com.icecondor.nest.Constants; json.put("date", date); json.put("type", type); } catch (JSONException e) { e.printStackTrace(); } } public Activity(JSONObject ijson) throws JSONException { if(ijson.getString("class").equals(getClass().getName())) { id = ijson.getString("id"); date = DateTime.parse(ijson.getString("date")); json.put("id", id); json.put("class", ijson.getString("class")); json.put("date", date); json.put("type", ijson.getString("type")); } else { throw new RuntimeException("Incompatible JSON for "+getClass().getName()); } } public DateTime getDateTime() { return date; } @Override public String getTableName() { return Database.TABLE_ACTIVITIES; } static public Cursor getAll(Database db, int i) { if(db == null) {
Log.d(Constants.APP_TAG, "getAll called with null db!");
icecondor/android
src/com/icecondor/nest/ui/login/UserEditFragment.java
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // }
import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import com.icecondor.nest.Constants; import com.icecondor.nest.R;
package com.icecondor.nest.ui.login; public class UserEditFragment extends Fragment { private EditText usernameEdit; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState);
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // } // Path: src/com/icecondor/nest/ui/login/UserEditFragment.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import com.icecondor.nest.Constants; import com.icecondor.nest.R; package com.icecondor.nest.ui.login; public class UserEditFragment extends Fragment { private EditText usernameEdit; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState);
Log.d(Constants.APP_TAG, "UserEditFragment onActivityCreated");
icecondor/android
src/com/icecondor/nest/api/Client.java
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // }
import java.net.URI; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashSet; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import java.util.concurrent.ExecutionException; import org.json.JSONException; import org.json.JSONObject; import android.os.Handler; import android.util.Base64; import android.util.Log; import com.icecondor.nest.Constants; import com.koushikdutta.async.future.Future; import com.koushikdutta.async.http.AsyncHttpClient; import com.koushikdutta.async.http.AsyncHttpGet; import com.koushikdutta.async.http.AsyncHttpRequest; import com.koushikdutta.async.http.WebSocket;
package com.icecondor.nest.api; public class Client implements ConnectCallbacks { private final URI apiUrl; private final AsyncHttpClient client; private final ClientActions actions; private static final int RECONNECT_WAIT_BASE = 2; private int reconnects = 0; private final Handler handler; private Future<WebSocket> websocketFuture; private WebSocket websocket; private final Timer apiTimer; private final HashSet<String> apiQueue; public enum States { IDLE, WAITING, CONNECTING, CONNECTED }; private States state; private Runnable reconnectRunnable = new Runnable() { @Override public void run() {
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // } // Path: src/com/icecondor/nest/api/Client.java import java.net.URI; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashSet; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import java.util.concurrent.ExecutionException; import org.json.JSONException; import org.json.JSONObject; import android.os.Handler; import android.util.Base64; import android.util.Log; import com.icecondor.nest.Constants; import com.koushikdutta.async.future.Future; import com.koushikdutta.async.http.AsyncHttpClient; import com.koushikdutta.async.http.AsyncHttpGet; import com.koushikdutta.async.http.AsyncHttpRequest; import com.koushikdutta.async.http.WebSocket; package com.icecondor.nest.api; public class Client implements ConnectCallbacks { private final URI apiUrl; private final AsyncHttpClient client; private final ClientActions actions; private static final int RECONNECT_WAIT_BASE = 2; private int reconnects = 0; private final Handler handler; private Future<WebSocket> websocketFuture; private WebSocket websocket; private final Timer apiTimer; private final HashSet<String> apiQueue; public enum States { IDLE, WAITING, CONNECTING, CONNECTED }; private States state; private Runnable reconnectRunnable = new Runnable() { @Override public void run() {
Log.d(Constants.APP_TAG, "api.Client postDelayed firing.");
icecondor/android
src/com/icecondor/nest/service/BatteryReceiver.java
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // }
import java.util.Date; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.BatteryManager; import android.util.Log; import com.icecondor.nest.Constants;
package com.icecondor.nest.service; public class BatteryReceiver extends BroadcastReceiver { private int last_battery_level; private Date last_battery_date; private boolean ac_power; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_BATTERY_CHANGED)) { last_battery_level = intent.getIntExtra("level", 0); last_battery_date = new Date(); int ac_int = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); ac_power = ac_int != 0;
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // } // Path: src/com/icecondor/nest/service/BatteryReceiver.java import java.util.Date; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.BatteryManager; import android.util.Log; import com.icecondor.nest.Constants; package com.icecondor.nest.service; public class BatteryReceiver extends BroadcastReceiver { private int last_battery_level; private Date last_battery_date; private boolean ac_power; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_BATTERY_CHANGED)) { last_battery_level = intent.getIntExtra("level", 0); last_battery_date = new Date(); int ac_int = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); ac_power = ac_int != 0;
Log.d(Constants.APP_TAG, "battery changed "+last_battery_level+" charging "+ac_power+" "+ac_int);
icecondor/android
src/com/icecondor/nest/ui/login/LoginFragment.java
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // }
import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.icecondor.nest.Constants; import com.icecondor.nest.R;
package com.icecondor.nest.ui.login; public class LoginFragment extends Fragment { private TextView statusView; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState);
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // } // Path: src/com/icecondor/nest/ui/login/LoginFragment.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.icecondor.nest.Constants; import com.icecondor.nest.R; package com.icecondor.nest.ui.login; public class LoginFragment extends Fragment { private TextView statusView; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState);
Log.d(Constants.APP_TAG, "LoginFragment onActivityCreated");
icecondor/android
src/com/icecondor/nest/api/KoushiSocket.java
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // }
import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import org.apache.http.conn.ssl.SSLSocketFactory; import android.util.Log; import com.icecondor.nest.Constants; import com.koushikdutta.async.ByteBufferList; import com.koushikdutta.async.DataEmitter; import com.koushikdutta.async.callback.CompletedCallback; import com.koushikdutta.async.callback.DataCallback; import com.koushikdutta.async.http.AsyncHttpClient; import com.koushikdutta.async.http.WebSocket; import com.koushikdutta.async.http.WebSocket.StringCallback;
package com.icecondor.nest.api; public class KoushiSocket implements AsyncHttpClient.WebSocketConnectCallback { private final ConnectCallbacks connectCallbacks; public KoushiSocket(ConnectCallbacks connBack) { connectCallbacks = connBack; } @Override public void onCompleted(Exception ex, WebSocket webSocket) { if (ex != null) { if(ex.getClass().isAssignableFrom(java.util.concurrent.TimeoutException.class)) {
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // } // Path: src/com/icecondor/nest/api/KoushiSocket.java import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import org.apache.http.conn.ssl.SSLSocketFactory; import android.util.Log; import com.icecondor.nest.Constants; import com.koushikdutta.async.ByteBufferList; import com.koushikdutta.async.DataEmitter; import com.koushikdutta.async.callback.CompletedCallback; import com.koushikdutta.async.callback.DataCallback; import com.koushikdutta.async.http.AsyncHttpClient; import com.koushikdutta.async.http.WebSocket; import com.koushikdutta.async.http.WebSocket.StringCallback; package com.icecondor.nest.api; public class KoushiSocket implements AsyncHttpClient.WebSocketConnectCallback { private final ConnectCallbacks connectCallbacks; public KoushiSocket(ConnectCallbacks connBack) { connectCallbacks = connBack; } @Override public void onCompleted(Exception ex, WebSocket webSocket) { if (ex != null) { if(ex.getClass().isAssignableFrom(java.util.concurrent.TimeoutException.class)) {
Log.d(Constants.APP_TAG, "ws: timeout!");
icecondor/android
src/com/icecondor/nest/NotificationBar.java
// Path: src/com/icecondor/nest/ui/alist/Main.java // public class Main extends BaseActivity implements UiActions, // CompoundButton.OnCheckedChangeListener { // // private CompoundButton onOff; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // Log.d(Constants.APP_TAG, "alist.MainActivity onCreate"); // // actionBarExtraSetup(); // // if (savedInstanceState == null) { // switchFragment(actListFragment); // } // } // // public void actionBarExtraSetup() { // LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, // LayoutParams.WRAP_CONTENT, // Gravity.RIGHT | Gravity.CENTER_VERTICAL); // View customNav = LayoutInflater.from(this).inflate(R.layout.action_bar_extra, null); // onOff = (CompoundButton)customNav.findViewById(R.id.actionbar_onoff); // onOff.setOnCheckedChangeListener(this); // ActionBar bar = getSupportActionBar(); // bar.setCustomView(customNav, lp); // bar.setDisplayShowCustomEnabled(true); // } // // @Override // protected void onResume() { // super.onResume(); // Log.d(Constants.APP_TAG, "alist.MainActivity onResume"); // onOff.setChecked(prefs.isOnOff()); // enableServiceHandler(); // authCheck(); // } // // @Override // protected void onPause() { // super.onPause(); // disableServiceHandler(); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // } // return super.onOptionsItemSelected(item); // } // // @Override // public void onConnecting(URI uri) { // Log.d(Constants.APP_TAG, "alist.MainActivity callback onConnecting"); // } // // @Override // public void onConnected() { // Log.d(Constants.APP_TAG, "alist.MainActivity callback onConnected"); // } // // @Override // public void onDisconnected() { // Log.d(Constants.APP_TAG, "alist.MainActivity callback onDisconnected"); // } // // @Override // public void onConnectTimeout() { // Log.d(Constants.APP_TAG, "alist.MainActivity callback onTimeout"); // } // // @Override // public void onConnectException(Exception ex) { // Log.d(Constants.APP_TAG, "alist.MainActivity callback onConnectException "+ex); // } // // @Override // public void onNewActivity() { // Log.d(Constants.APP_TAG, "alist.MainActivity: callback onNewActivity"); // actListFragment.invalidateView(); // } // // @Override // public void onApiResult(String id, JSONObject result) { // Log.d(Constants.APP_TAG, "alist.Main onApiResult "+id+" "+result); // } // // @Override // public void onApiError(String id, JSONObject error) { // Log.d(Constants.APP_TAG, "alist.Main onApierror "+id+" "+error); // } // // @Override // public void onCheckedChanged(CompoundButton btn, boolean isChecked) { // if(btn.getId() == R.id.actionbar_onoff){ // if(condor != null) { // condor.setRecording(isChecked); // } // } // } // // public void doLogout() { // called from SettingsFragment // prefs.clearAuthenticatedUser(); // if(condor != null) { // condor.disconnect(); // } // Intent intent = new Intent(this, com.icecondor.nest.ui.login.Main.class); // startActivity(intent); // finish(); // } // // public void resetApiUrl(URI url) { // condor.resetApiUrl(url); // } // // public void configChangeRecord(String key, String desc) { // condor.configChange(key, desc); // } // // public void resetTimersAndConnection() { // // frequency changed. stop/start all the things // if(condor != null) { // condor.stopRecording(); // condor.startRecording(); // } // } // }
import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import com.icecondor.nest.ui.alist.Main;
package com.icecondor.nest; public class NotificationBar { private NotificationManager notificationManager; private Notification ongoingNotification; private PendingIntent contentIntent; private Context ctx; public NotificationBar(Context ctx) { this.ctx = ctx; notificationManager = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);
// Path: src/com/icecondor/nest/ui/alist/Main.java // public class Main extends BaseActivity implements UiActions, // CompoundButton.OnCheckedChangeListener { // // private CompoundButton onOff; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // Log.d(Constants.APP_TAG, "alist.MainActivity onCreate"); // // actionBarExtraSetup(); // // if (savedInstanceState == null) { // switchFragment(actListFragment); // } // } // // public void actionBarExtraSetup() { // LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, // LayoutParams.WRAP_CONTENT, // Gravity.RIGHT | Gravity.CENTER_VERTICAL); // View customNav = LayoutInflater.from(this).inflate(R.layout.action_bar_extra, null); // onOff = (CompoundButton)customNav.findViewById(R.id.actionbar_onoff); // onOff.setOnCheckedChangeListener(this); // ActionBar bar = getSupportActionBar(); // bar.setCustomView(customNav, lp); // bar.setDisplayShowCustomEnabled(true); // } // // @Override // protected void onResume() { // super.onResume(); // Log.d(Constants.APP_TAG, "alist.MainActivity onResume"); // onOff.setChecked(prefs.isOnOff()); // enableServiceHandler(); // authCheck(); // } // // @Override // protected void onPause() { // super.onPause(); // disableServiceHandler(); // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // } // return super.onOptionsItemSelected(item); // } // // @Override // public void onConnecting(URI uri) { // Log.d(Constants.APP_TAG, "alist.MainActivity callback onConnecting"); // } // // @Override // public void onConnected() { // Log.d(Constants.APP_TAG, "alist.MainActivity callback onConnected"); // } // // @Override // public void onDisconnected() { // Log.d(Constants.APP_TAG, "alist.MainActivity callback onDisconnected"); // } // // @Override // public void onConnectTimeout() { // Log.d(Constants.APP_TAG, "alist.MainActivity callback onTimeout"); // } // // @Override // public void onConnectException(Exception ex) { // Log.d(Constants.APP_TAG, "alist.MainActivity callback onConnectException "+ex); // } // // @Override // public void onNewActivity() { // Log.d(Constants.APP_TAG, "alist.MainActivity: callback onNewActivity"); // actListFragment.invalidateView(); // } // // @Override // public void onApiResult(String id, JSONObject result) { // Log.d(Constants.APP_TAG, "alist.Main onApiResult "+id+" "+result); // } // // @Override // public void onApiError(String id, JSONObject error) { // Log.d(Constants.APP_TAG, "alist.Main onApierror "+id+" "+error); // } // // @Override // public void onCheckedChanged(CompoundButton btn, boolean isChecked) { // if(btn.getId() == R.id.actionbar_onoff){ // if(condor != null) { // condor.setRecording(isChecked); // } // } // } // // public void doLogout() { // called from SettingsFragment // prefs.clearAuthenticatedUser(); // if(condor != null) { // condor.disconnect(); // } // Intent intent = new Intent(this, com.icecondor.nest.ui.login.Main.class); // startActivity(intent); // finish(); // } // // public void resetApiUrl(URI url) { // condor.resetApiUrl(url); // } // // public void configChangeRecord(String key, String desc) { // condor.configChange(key, desc); // } // // public void resetTimersAndConnection() { // // frequency changed. stop/start all the things // if(condor != null) { // condor.stopRecording(); // condor.startRecording(); // } // } // } // Path: src/com/icecondor/nest/NotificationBar.java import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import com.icecondor.nest.ui.alist.Main; package com.icecondor.nest; public class NotificationBar { private NotificationManager notificationManager; private Notification ongoingNotification; private PendingIntent contentIntent; private Context ctx; public NotificationBar(Context ctx) { this.ctx = ctx; notificationManager = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);
contentIntent = PendingIntent.getActivity(ctx, 0, new Intent(ctx, Main.class),
icecondor/android
src/com/icecondor/nest/ui/login/LoginPassFragment.java
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // }
import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import com.icecondor.nest.Constants; import com.icecondor.nest.R;
package com.icecondor.nest.ui.login; public class LoginPassFragment extends Fragment { private EditText passwordField; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState);
// Path: src/com/icecondor/nest/Constants.java // public class Constants { // // public static final String APP_TAG = "icecondor"; // public static final int SIGNAL_NEW_ACTIVITY = 1; // public static final String ACTION_WAKE_ALARM = "com.icecondor.WAKE_ALARM"; // public static final String ICECONDOR_API_URL = "wss://api.icecondor.com/v2"; // public static final String VERSION = "20150402"; // // /* internal app settings */ // public static final String SETTING_ON_OFF = "on_off"; // public static final String SETTING_DEVICE_ID = "device_id"; // // /* user preferences */ // public static final String PREFERENCE_AUTOSTART = "autostart"; // public static final String PREFERENCE_API_URL = "api_url"; // public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = "recording_frequency"; // public static final String PREFERENCE_SOURCE_GPS = "source_gps"; // public static final String PREFERENCE_SOURCE_CELL = "source_cell"; // public static final String PREFERENCE_SOURCE_WIFI = "source_wifi"; // public static final String PREFERENCE_VERSION = "version_string"; // public static final String PREFERENCE_LOGOUT = "logout_pref"; // public static final String PREFERENCE_PERSISTENT_RECONNECT = "persistent_reconnect"; // public static final String PREFERENCE_EVENT_CONNECTING = "event_connecting"; // public static final String PREFERENCE_EVENT_CONNECTED = "event_connected"; // public static final String PREFERENCE_EVENT_DISCONNECTED = "event_disconnected"; // public static final String PREFERENCE_EVENT_HEARTBEAT= "event_heartbeat"; // // } // Path: src/com/icecondor/nest/ui/login/LoginPassFragment.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import com.icecondor.nest.Constants; import com.icecondor.nest.R; package com.icecondor.nest.ui.login; public class LoginPassFragment extends Fragment { private EditText passwordField; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState);
Log.d(Constants.APP_TAG, "LoginPassFragment onActivityCreated");
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/text/Encoding.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // }
import eu.digitisation.log.Messages; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import org.apache.tika.io.TikaInputStream; import org.apache.tika.parser.txt.CharsetDetector;
/* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.text; /** * Detect the encoding of a text file * * @author R.C.C. */ public class Encoding { /** * * @param file a text file * @return the encoding or Charset */ public static Charset detect(File file) { try { InputStream is = TikaInputStream.get(new FileInputStream(file)); CharsetDetector detector = new CharsetDetector(); detector.setText(is); return Charset.forName(detector.detect().getName()); } catch (IOException ex) {
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/text/Encoding.java import eu.digitisation.log.Messages; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import org.apache.tika.io.TikaInputStream; import org.apache.tika.parser.txt.CharsetDetector; /* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.text; /** * Detect the encoding of a text file * * @author R.C.C. */ public class Encoding { /** * * @param file a text file * @return the encoding or Charset */ public static Charset detect(File file) { try { InputStream is = TikaInputStream.get(new FileInputStream(file)); CharsetDetector detector = new CharsetDetector(); detector.setText(is); return Charset.forName(detector.detect().getName()); } catch (IOException ex) {
Messages.info(Encoding.class.getName() + ": " + ex);
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/text/CharMap.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // }
import eu.digitisation.input.ExtensionFilter; import eu.digitisation.log.Messages; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.EnumMap; import java.util.HashMap; import java.util.Locale; import java.util.Map;
for (String filename : filenames) { addCSV(new File(filename)); } } else if (file.isFile()) { addCSV(file); } } /** * Add the equivalences contained in a CSV file * * @param file the CSV file */ private void addCSV(File file) { try { BufferedReader reader = new BufferedReader(new FileReader(file)); while (reader.ready()) { String line = reader.readLine(); String[] tokens = line.split("([,;\t])"); if (tokens.length > 1) { // allow comments in line Character key = (char) Integer.parseInt(tokens[0].trim(), 16); String value = UnicodeReader.codepointsToString(tokens[1]); equivalences.put(key, value); } else { throw new IOException("Wrong line" + line + " at file " + file); } } reader.close(); } catch (IOException ex) {
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/text/CharMap.java import eu.digitisation.input.ExtensionFilter; import eu.digitisation.log.Messages; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.EnumMap; import java.util.HashMap; import java.util.Locale; import java.util.Map; for (String filename : filenames) { addCSV(new File(filename)); } } else if (file.isFile()) { addCSV(file); } } /** * Add the equivalences contained in a CSV file * * @param file the CSV file */ private void addCSV(File file) { try { BufferedReader reader = new BufferedReader(new FileReader(file)); while (reader.ready()) { String line = reader.readLine(); String[] tokens = line.split("([,;\t])"); if (tokens.length > 1) { // allow comments in line Character key = (char) Integer.parseInt(tokens[0].trim(), 16); String value = UnicodeReader.codepointsToString(tokens[1]); equivalences.put(key, value); } else { throw new IOException("Wrong line" + line + " at file " + file); } } reader.close(); } catch (IOException ex) {
Messages.info(CharFilter.class.getName() + ": " + ex);
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/xml/DocumentParser.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // }
import eu.digitisation.log.Messages; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.xml.sax.SAXException;
/* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.xml; /** * A builder and parser for XML documents * * @author R.C.C. * @version 2011.03.10 */ public class DocumentParser { static javax.xml.parsers.DocumentBuilder docBuilder; static { try { docBuilder = javax.xml.parsers.DocumentBuilderFactory .newInstance().newDocumentBuilder(); } catch (ParserConfigurationException ex) {
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/xml/DocumentParser.java import eu.digitisation.log.Messages; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.xml.sax.SAXException; /* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.xml; /** * A builder and parser for XML documents * * @author R.C.C. * @version 2011.03.10 */ public class DocumentParser { static javax.xml.parsers.DocumentBuilder docBuilder; static { try { docBuilder = javax.xml.parsers.DocumentBuilderFactory .newInstance().newDocumentBuilder(); } catch (ParserConfigurationException ex) {
Messages.info(DocumentParser.class.getName() + ": " + ex);
tesseract4java/tesseract4java
ocrevalUAtion/src/test/java/eu/digitisation/distance/StringEditDistanceTest.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/text/StringNormalizer.java // public class StringNormalizer { // // final static java.text.Normalizer.Form decomposed = java.text.Normalizer.Form.NFD; // final static java.text.Normalizer.Form composed = java.text.Normalizer.Form.NFC; // static final java.text.Normalizer.Form compatible = java.text.Normalizer.Form.NFKC; // // /** // * Reduce whitespace (including line and paragraph separators) // * // * @param s // * a string. // * @return The string with simple spaces between words. // */ // public static String reduceWS(String s) { // return s.replaceAll("-\n", "").replaceAll( // "(\\p{Space}|\u2028|\u2029)+", " ").trim(); // } // // /** // * @param s // * a string // * @return the canonical representation of the string. // */ // public static String composed(String s) { // return java.text.Normalizer.normalize(s, composed); // } // // /** // * @param s // * a string // * @return the canonical representation of the string with normalized // * compatible characters. // */ // public static String compatible(String s) { // return java.text.Normalizer.normalize(s, compatible); // } // // /** // * @param s // * a string // * @return the string with all diacritics removed. // */ // public static String removeDiacritics(String s) { // return java.text.Normalizer.normalize(s, decomposed) // .replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); // } // // /** // * @param s // * a string // * @return the string with all punctuation symbols removed. // */ // public static String removePunctuation(String s) { // return s.replaceAll("\\p{P}+", ""); // } // // /** // * @param s // * a string // * @return the string with leading and trailing whitespace and punctuation // * symbols removed. // */ // public static String trim(String s) { // return s.replaceAll("^(\\p{P}|\\p{Space})+", "") // .replaceAll("(\\p{P}|\\p{Space})+$", ""); // } // // /** // * // * @param s // * the input string // * @param ignoreCase // * true if case is irrelevant // * @param ignoreDiacritics // * true if diacritics are irrelevant // * @param ignorePunctuation // * true if punctuation is irrelevant // * @return the canonical representation for comparison // */ // public static String canonical(String s, // boolean ignoreCase, // boolean ignoreDiacritics, // boolean ignorePunctuation) { // // String res = (ignorePunctuation) ? removePunctuation(s) : s; // if (ignoreCase) { // if (ignoreDiacritics) { // return StringNormalizer.removeDiacritics(res).toLowerCase(); // } else { // return res.toLowerCase(); // } // } else if (ignoreDiacritics) { // return StringNormalizer.removeDiacritics(res); // } else { // return res; // } // } // // /** // * Remove everything except for letters (with diacritics), numbers and // * spaces // * // * @param s // * a string // * @return the string with only letters, numbers, spaces and diacritics. // */ // public static String strip(String s) { // return s.replaceAll("[^\\p{L}\\p{M}\\p{N}\\p{Space}]", ""); // } // // /** // * @param s // * a string // * @return the string with characters <, >, &, " escaped // */ // public static String encode(String s) { // StringBuilder result = new StringBuilder(); // for (Character c : s.toCharArray()) { // if (c.equals('<')) { // result.append("&lt;"); // } else if (c.equals('>')) { // result.append("&gt;"); // } else if (c.equals('"')) { // result.append("&quot;"); // } else if (c.equals('&')) { // result.append("&amp;"); // } else { // result.append(c); // } // } // return result.toString(); // } // }
import eu.digitisation.text.StringNormalizer; import eu.digitisation.math.BiCounter; import static junit.framework.TestCase.assertEquals; import org.junit.Test;
/* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.distance; /** * * @author R.C.C */ public class StringEditDistanceTest { public StringEditDistanceTest() { } /** * Test of indel method, of class StringEditDistance. */ @Test public void testIndelDistance() { System.out.println("indelDistance"); String first = "patata"; String second = "apta"; int expResult = 4; int result = StringEditDistance.indel(first, second); assertEquals(expResult, result); } /** * Test of levenshtein method, of class StringEditDistance. */ @Test public void testLevenshteinDistance() { System.out.println("levenshteinDistance"); String first = "patata"; String second = "apta"; int expResult = 3; int result = StringEditDistance.levenshtein(first, second); assertEquals(expResult, result); // A second test first = "holanda"; second = "wordland"; result = StringEditDistance.levenshtein(first, second); assertEquals(4, result); // Test with normalization
// Path: ocrevalUAtion/src/main/java/eu/digitisation/text/StringNormalizer.java // public class StringNormalizer { // // final static java.text.Normalizer.Form decomposed = java.text.Normalizer.Form.NFD; // final static java.text.Normalizer.Form composed = java.text.Normalizer.Form.NFC; // static final java.text.Normalizer.Form compatible = java.text.Normalizer.Form.NFKC; // // /** // * Reduce whitespace (including line and paragraph separators) // * // * @param s // * a string. // * @return The string with simple spaces between words. // */ // public static String reduceWS(String s) { // return s.replaceAll("-\n", "").replaceAll( // "(\\p{Space}|\u2028|\u2029)+", " ").trim(); // } // // /** // * @param s // * a string // * @return the canonical representation of the string. // */ // public static String composed(String s) { // return java.text.Normalizer.normalize(s, composed); // } // // /** // * @param s // * a string // * @return the canonical representation of the string with normalized // * compatible characters. // */ // public static String compatible(String s) { // return java.text.Normalizer.normalize(s, compatible); // } // // /** // * @param s // * a string // * @return the string with all diacritics removed. // */ // public static String removeDiacritics(String s) { // return java.text.Normalizer.normalize(s, decomposed) // .replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); // } // // /** // * @param s // * a string // * @return the string with all punctuation symbols removed. // */ // public static String removePunctuation(String s) { // return s.replaceAll("\\p{P}+", ""); // } // // /** // * @param s // * a string // * @return the string with leading and trailing whitespace and punctuation // * symbols removed. // */ // public static String trim(String s) { // return s.replaceAll("^(\\p{P}|\\p{Space})+", "") // .replaceAll("(\\p{P}|\\p{Space})+$", ""); // } // // /** // * // * @param s // * the input string // * @param ignoreCase // * true if case is irrelevant // * @param ignoreDiacritics // * true if diacritics are irrelevant // * @param ignorePunctuation // * true if punctuation is irrelevant // * @return the canonical representation for comparison // */ // public static String canonical(String s, // boolean ignoreCase, // boolean ignoreDiacritics, // boolean ignorePunctuation) { // // String res = (ignorePunctuation) ? removePunctuation(s) : s; // if (ignoreCase) { // if (ignoreDiacritics) { // return StringNormalizer.removeDiacritics(res).toLowerCase(); // } else { // return res.toLowerCase(); // } // } else if (ignoreDiacritics) { // return StringNormalizer.removeDiacritics(res); // } else { // return res; // } // } // // /** // * Remove everything except for letters (with diacritics), numbers and // * spaces // * // * @param s // * a string // * @return the string with only letters, numbers, spaces and diacritics. // */ // public static String strip(String s) { // return s.replaceAll("[^\\p{L}\\p{M}\\p{N}\\p{Space}]", ""); // } // // /** // * @param s // * a string // * @return the string with characters <, >, &, " escaped // */ // public static String encode(String s) { // StringBuilder result = new StringBuilder(); // for (Character c : s.toCharArray()) { // if (c.equals('<')) { // result.append("&lt;"); // } else if (c.equals('>')) { // result.append("&gt;"); // } else if (c.equals('"')) { // result.append("&quot;"); // } else if (c.equals('&')) { // result.append("&amp;"); // } else { // result.append(c); // } // } // return result.toString(); // } // } // Path: ocrevalUAtion/src/test/java/eu/digitisation/distance/StringEditDistanceTest.java import eu.digitisation.text.StringNormalizer; import eu.digitisation.math.BiCounter; import static junit.framework.TestCase.assertEquals; import org.junit.Test; /* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.distance; /** * * @author R.C.C */ public class StringEditDistanceTest { public StringEditDistanceTest() { } /** * Test of indel method, of class StringEditDistance. */ @Test public void testIndelDistance() { System.out.println("indelDistance"); String first = "patata"; String second = "apta"; int expResult = 4; int result = StringEditDistance.indel(first, second); assertEquals(expResult, result); } /** * Test of levenshtein method, of class StringEditDistance. */ @Test public void testLevenshteinDistance() { System.out.println("levenshteinDistance"); String first = "patata"; String second = "apta"; int expResult = 3; int result = StringEditDistance.levenshtein(first, second); assertEquals(expResult, result); // A second test first = "holanda"; second = "wordland"; result = StringEditDistance.levenshtein(first, second); assertEquals(4, result); // Test with normalization
first = StringNormalizer.reduceWS("Mi enhorabuena");
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/distance/OcrOpWeight.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/input/Parameters.java // public class Parameters { // // private static final long serialVersionUID = 1L; // // Define program parameters: input files // public final Parameter<File> gtfile; // public final Parameter<File> ocrfile; // public final Parameter<File> eqfile; // equivalences // public final Parameter<File> swfile; // stop words // public final Parameter<File> lmfile; // language model // public final Parameter<File> outfile; // // Define program parameters: boolean options // public final Parameter<Boolean> ignoreCase; // public final Parameter<Boolean> ignoreDiacritics; // public final Parameter<Boolean> ignorePunctuation; // public final Parameter<Boolean> compatibility; // // Define program parameters: String options // public final Parameter<String> encoding; // // Set verbosity during debugging (unused) // public final Parameter<Boolean> verbose; // // public Parameters() { // gtfile = new Parameter<File>("ground-truth file"); // ocrfile = new Parameter<File>("OCR file"); // eqfile = new Parameter<File>("Unicode equivalences file"); // swfile = new Parameter<File>("stop-words file"); // lmfile = new Parameter<File>("Language model file"); // outfile = new Parameter<File>("output file"); // ignoreCase = new Parameter<Boolean>("Ignore case", false, ""); // ignoreDiacritics = new Parameter<Boolean>("Ignore diacritics", false, ""); // ignorePunctuation = new Parameter<Boolean>("Ignore punctuation", false, ""); // compatibility = new Parameter<Boolean>("Unicode compatibility characters", false, // "http://unicode.org/reports/tr15/#Canon_Compat_Equivalence"); // encoding = new Parameter<String>("Text file encoding"); // verbose = new Parameter<Boolean>("Verbose", false, ""); // } // // public void clear() { // gtfile.setValue(null); // ocrfile.setValue(null); // eqfile.setValue(null); // swfile.setValue(null); // lmfile.setValue(null); // outfile.setValue(null); // ignoreCase.setValue(null); // ignoreDiacritics.setValue(null); // ignorePunctuation.setValue(null); // compatibility.setValue(null); // encoding.setValue(null); // } // }
import eu.digitisation.input.Parameters;
/* * Copyright (C) 2014 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.distance; /** * Integer weights for basic edit operations. * * @author R.C.C. */ public class OcrOpWeight implements EdOpWeight { // boolean ignoreCase; // boolean ignoreDiacritics; boolean ignorePunctuation; /** * * @param ignoreCase true if case must be ignored * @param ignoreDiacritics true if diacritics must be ignored * @param ignorePunctuation true if punctuation must be ignored */ public OcrOpWeight(boolean ignorePunctuation) { // this.ignoreCase = ignoreCase; // this.ignoreDiacritics = ignoreDiacritics; this.ignorePunctuation = ignorePunctuation; }
// Path: ocrevalUAtion/src/main/java/eu/digitisation/input/Parameters.java // public class Parameters { // // private static final long serialVersionUID = 1L; // // Define program parameters: input files // public final Parameter<File> gtfile; // public final Parameter<File> ocrfile; // public final Parameter<File> eqfile; // equivalences // public final Parameter<File> swfile; // stop words // public final Parameter<File> lmfile; // language model // public final Parameter<File> outfile; // // Define program parameters: boolean options // public final Parameter<Boolean> ignoreCase; // public final Parameter<Boolean> ignoreDiacritics; // public final Parameter<Boolean> ignorePunctuation; // public final Parameter<Boolean> compatibility; // // Define program parameters: String options // public final Parameter<String> encoding; // // Set verbosity during debugging (unused) // public final Parameter<Boolean> verbose; // // public Parameters() { // gtfile = new Parameter<File>("ground-truth file"); // ocrfile = new Parameter<File>("OCR file"); // eqfile = new Parameter<File>("Unicode equivalences file"); // swfile = new Parameter<File>("stop-words file"); // lmfile = new Parameter<File>("Language model file"); // outfile = new Parameter<File>("output file"); // ignoreCase = new Parameter<Boolean>("Ignore case", false, ""); // ignoreDiacritics = new Parameter<Boolean>("Ignore diacritics", false, ""); // ignorePunctuation = new Parameter<Boolean>("Ignore punctuation", false, ""); // compatibility = new Parameter<Boolean>("Unicode compatibility characters", false, // "http://unicode.org/reports/tr15/#Canon_Compat_Equivalence"); // encoding = new Parameter<String>("Text file encoding"); // verbose = new Parameter<Boolean>("Verbose", false, ""); // } // // public void clear() { // gtfile.setValue(null); // ocrfile.setValue(null); // eqfile.setValue(null); // swfile.setValue(null); // lmfile.setValue(null); // outfile.setValue(null); // ignoreCase.setValue(null); // ignoreDiacritics.setValue(null); // ignorePunctuation.setValue(null); // compatibility.setValue(null); // encoding.setValue(null); // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/distance/OcrOpWeight.java import eu.digitisation.input.Parameters; /* * Copyright (C) 2014 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.distance; /** * Integer weights for basic edit operations. * * @author R.C.C. */ public class OcrOpWeight implements EdOpWeight { // boolean ignoreCase; // boolean ignoreDiacritics; boolean ignorePunctuation; /** * * @param ignoreCase true if case must be ignored * @param ignoreDiacritics true if diacritics must be ignored * @param ignorePunctuation true if punctuation must be ignored */ public OcrOpWeight(boolean ignorePunctuation) { // this.ignoreCase = ignoreCase; // this.ignoreDiacritics = ignoreDiacritics; this.ignorePunctuation = ignorePunctuation; }
public OcrOpWeight(Parameters pars) {
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/text/CharFilter.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // }
import eu.digitisation.input.ExtensionFilter; import eu.digitisation.log.Messages; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.nio.channels.FileChannel; import java.util.HashMap; import java.util.Map;
} } reader.close(); } catch (IOException ex) { } } /** * Add the equivalences in CSV format * * @param reader * a BufferedReader with CSV lines */ public void addCSV(BufferedReader reader) { try { while (reader.ready()) { String line = reader.readLine(); String[] tokens = line.split("([,;\t])"); if (tokens.length > 1) { // allow comments in line String key = UnicodeReader.codepointsToString(tokens[0]); String value = UnicodeReader.codepointsToString(tokens[1]); put(key, value); System.out.println(key + ", " + value); } else { throw new IOException("Wrong CSV line" + line); } } reader.close(); } catch (IOException ex) {
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/text/CharFilter.java import eu.digitisation.input.ExtensionFilter; import eu.digitisation.log.Messages; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.nio.channels.FileChannel; import java.util.HashMap; import java.util.Map; } } reader.close(); } catch (IOException ex) { } } /** * Add the equivalences in CSV format * * @param reader * a BufferedReader with CSV lines */ public void addCSV(BufferedReader reader) { try { while (reader.ready()) { String line = reader.readLine(); String[] tokens = line.split("([,;\t])"); if (tokens.length > 1) { // allow comments in line String key = UnicodeReader.codepointsToString(tokens[0]); String value = UnicodeReader.codepointsToString(tokens[1]); put(key, value); System.out.println(key + ", " + value); } else { throw new IOException("Wrong CSV line" + line); } } reader.close(); } catch (IOException ex) {
Messages.info(CharFilter.class.getName() + ": " + ex);
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/xml/XML2text.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/input/Parameters.java // public class Parameters { // // private static final long serialVersionUID = 1L; // // Define program parameters: input files // public final Parameter<File> gtfile; // public final Parameter<File> ocrfile; // public final Parameter<File> eqfile; // equivalences // public final Parameter<File> swfile; // stop words // public final Parameter<File> lmfile; // language model // public final Parameter<File> outfile; // // Define program parameters: boolean options // public final Parameter<Boolean> ignoreCase; // public final Parameter<Boolean> ignoreDiacritics; // public final Parameter<Boolean> ignorePunctuation; // public final Parameter<Boolean> compatibility; // // Define program parameters: String options // public final Parameter<String> encoding; // // Set verbosity during debugging (unused) // public final Parameter<Boolean> verbose; // // public Parameters() { // gtfile = new Parameter<File>("ground-truth file"); // ocrfile = new Parameter<File>("OCR file"); // eqfile = new Parameter<File>("Unicode equivalences file"); // swfile = new Parameter<File>("stop-words file"); // lmfile = new Parameter<File>("Language model file"); // outfile = new Parameter<File>("output file"); // ignoreCase = new Parameter<Boolean>("Ignore case", false, ""); // ignoreDiacritics = new Parameter<Boolean>("Ignore diacritics", false, ""); // ignorePunctuation = new Parameter<Boolean>("Ignore punctuation", false, ""); // compatibility = new Parameter<Boolean>("Unicode compatibility characters", false, // "http://unicode.org/reports/tr15/#Canon_Compat_Equivalence"); // encoding = new Parameter<String>("Text file encoding"); // verbose = new Parameter<Boolean>("Verbose", false, ""); // } // // public void clear() { // gtfile.setValue(null); // ocrfile.setValue(null); // eqfile.setValue(null); // swfile.setValue(null); // lmfile.setValue(null); // outfile.setValue(null); // ignoreCase.setValue(null); // ignoreDiacritics.setValue(null); // ignorePunctuation.setValue(null); // compatibility.setValue(null); // encoding.setValue(null); // } // } // // Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // }
import eu.digitisation.input.Parameters; import eu.digitisation.log.Messages; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler;
return name.endsWith(".xml"); } }; @Override public void characters(char[] c, int start, int length) { if (length > 0) { buffer.append(c, start, length); } } @Override public void startElement(String uri, String localName, String tag, Attributes attributes) { buffer.append(" "); } @Override public void endElement(String uri, String localName, String tag) { buffer.append(" "); } private XMLReader getXMLReader() { XMLReader reader = null; try { reader = SAXParserFactory.newInstance() .newSAXParser().getXMLReader(); reader.setContentHandler(this); } catch (SAXException ex) {
// Path: ocrevalUAtion/src/main/java/eu/digitisation/input/Parameters.java // public class Parameters { // // private static final long serialVersionUID = 1L; // // Define program parameters: input files // public final Parameter<File> gtfile; // public final Parameter<File> ocrfile; // public final Parameter<File> eqfile; // equivalences // public final Parameter<File> swfile; // stop words // public final Parameter<File> lmfile; // language model // public final Parameter<File> outfile; // // Define program parameters: boolean options // public final Parameter<Boolean> ignoreCase; // public final Parameter<Boolean> ignoreDiacritics; // public final Parameter<Boolean> ignorePunctuation; // public final Parameter<Boolean> compatibility; // // Define program parameters: String options // public final Parameter<String> encoding; // // Set verbosity during debugging (unused) // public final Parameter<Boolean> verbose; // // public Parameters() { // gtfile = new Parameter<File>("ground-truth file"); // ocrfile = new Parameter<File>("OCR file"); // eqfile = new Parameter<File>("Unicode equivalences file"); // swfile = new Parameter<File>("stop-words file"); // lmfile = new Parameter<File>("Language model file"); // outfile = new Parameter<File>("output file"); // ignoreCase = new Parameter<Boolean>("Ignore case", false, ""); // ignoreDiacritics = new Parameter<Boolean>("Ignore diacritics", false, ""); // ignorePunctuation = new Parameter<Boolean>("Ignore punctuation", false, ""); // compatibility = new Parameter<Boolean>("Unicode compatibility characters", false, // "http://unicode.org/reports/tr15/#Canon_Compat_Equivalence"); // encoding = new Parameter<String>("Text file encoding"); // verbose = new Parameter<Boolean>("Verbose", false, ""); // } // // public void clear() { // gtfile.setValue(null); // ocrfile.setValue(null); // eqfile.setValue(null); // swfile.setValue(null); // lmfile.setValue(null); // outfile.setValue(null); // ignoreCase.setValue(null); // ignoreDiacritics.setValue(null); // ignorePunctuation.setValue(null); // compatibility.setValue(null); // encoding.setValue(null); // } // } // // Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/xml/XML2text.java import eu.digitisation.input.Parameters; import eu.digitisation.log.Messages; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; return name.endsWith(".xml"); } }; @Override public void characters(char[] c, int start, int length) { if (length > 0) { buffer.append(c, start, length); } } @Override public void startElement(String uri, String localName, String tag, Attributes attributes) { buffer.append(" "); } @Override public void endElement(String uri, String localName, String tag) { buffer.append(" "); } private XMLReader getXMLReader() { XMLReader reader = null; try { reader = SAXParserFactory.newInstance() .newSAXParser().getXMLReader(); reader.setContentHandler(this); } catch (SAXException ex) {
Messages.info(XML2text.class.getName() + ": " + ex);
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/xml/XML2text.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/input/Parameters.java // public class Parameters { // // private static final long serialVersionUID = 1L; // // Define program parameters: input files // public final Parameter<File> gtfile; // public final Parameter<File> ocrfile; // public final Parameter<File> eqfile; // equivalences // public final Parameter<File> swfile; // stop words // public final Parameter<File> lmfile; // language model // public final Parameter<File> outfile; // // Define program parameters: boolean options // public final Parameter<Boolean> ignoreCase; // public final Parameter<Boolean> ignoreDiacritics; // public final Parameter<Boolean> ignorePunctuation; // public final Parameter<Boolean> compatibility; // // Define program parameters: String options // public final Parameter<String> encoding; // // Set verbosity during debugging (unused) // public final Parameter<Boolean> verbose; // // public Parameters() { // gtfile = new Parameter<File>("ground-truth file"); // ocrfile = new Parameter<File>("OCR file"); // eqfile = new Parameter<File>("Unicode equivalences file"); // swfile = new Parameter<File>("stop-words file"); // lmfile = new Parameter<File>("Language model file"); // outfile = new Parameter<File>("output file"); // ignoreCase = new Parameter<Boolean>("Ignore case", false, ""); // ignoreDiacritics = new Parameter<Boolean>("Ignore diacritics", false, ""); // ignorePunctuation = new Parameter<Boolean>("Ignore punctuation", false, ""); // compatibility = new Parameter<Boolean>("Unicode compatibility characters", false, // "http://unicode.org/reports/tr15/#Canon_Compat_Equivalence"); // encoding = new Parameter<String>("Text file encoding"); // verbose = new Parameter<Boolean>("Verbose", false, ""); // } // // public void clear() { // gtfile.setValue(null); // ocrfile.setValue(null); // eqfile.setValue(null); // swfile.setValue(null); // lmfile.setValue(null); // outfile.setValue(null); // ignoreCase.setValue(null); // ignoreDiacritics.setValue(null); // ignorePunctuation.setValue(null); // compatibility.setValue(null); // encoding.setValue(null); // } // } // // Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // }
import eu.digitisation.input.Parameters; import eu.digitisation.log.Messages; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler;
} /** * Read file and return text content. * * @param fileName the name of the file. * @return text in file without markup. */ public String getText(String fileName) { XMLReader reader = getXMLReader(); buffer = new StringBuilder(10000); try { reader.parse(fileName); } catch (IOException ex) { Messages.info(XML2text.class.getName() + ": " + ex); } catch (SAXException ex) { Messages.info(XML2text.class.getName() + ": " + ex); } return buffer.toString(); } /** * Main function * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { XML2text xml = new XML2text(); String outDir = null;
// Path: ocrevalUAtion/src/main/java/eu/digitisation/input/Parameters.java // public class Parameters { // // private static final long serialVersionUID = 1L; // // Define program parameters: input files // public final Parameter<File> gtfile; // public final Parameter<File> ocrfile; // public final Parameter<File> eqfile; // equivalences // public final Parameter<File> swfile; // stop words // public final Parameter<File> lmfile; // language model // public final Parameter<File> outfile; // // Define program parameters: boolean options // public final Parameter<Boolean> ignoreCase; // public final Parameter<Boolean> ignoreDiacritics; // public final Parameter<Boolean> ignorePunctuation; // public final Parameter<Boolean> compatibility; // // Define program parameters: String options // public final Parameter<String> encoding; // // Set verbosity during debugging (unused) // public final Parameter<Boolean> verbose; // // public Parameters() { // gtfile = new Parameter<File>("ground-truth file"); // ocrfile = new Parameter<File>("OCR file"); // eqfile = new Parameter<File>("Unicode equivalences file"); // swfile = new Parameter<File>("stop-words file"); // lmfile = new Parameter<File>("Language model file"); // outfile = new Parameter<File>("output file"); // ignoreCase = new Parameter<Boolean>("Ignore case", false, ""); // ignoreDiacritics = new Parameter<Boolean>("Ignore diacritics", false, ""); // ignorePunctuation = new Parameter<Boolean>("Ignore punctuation", false, ""); // compatibility = new Parameter<Boolean>("Unicode compatibility characters", false, // "http://unicode.org/reports/tr15/#Canon_Compat_Equivalence"); // encoding = new Parameter<String>("Text file encoding"); // verbose = new Parameter<Boolean>("Verbose", false, ""); // } // // public void clear() { // gtfile.setValue(null); // ocrfile.setValue(null); // eqfile.setValue(null); // swfile.setValue(null); // lmfile.setValue(null); // outfile.setValue(null); // ignoreCase.setValue(null); // ignoreDiacritics.setValue(null); // ignorePunctuation.setValue(null); // compatibility.setValue(null); // encoding.setValue(null); // } // } // // Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/xml/XML2text.java import eu.digitisation.input.Parameters; import eu.digitisation.log.Messages; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; } /** * Read file and return text content. * * @param fileName the name of the file. * @return text in file without markup. */ public String getText(String fileName) { XMLReader reader = getXMLReader(); buffer = new StringBuilder(10000); try { reader.parse(fileName); } catch (IOException ex) { Messages.info(XML2text.class.getName() + ": " + ex); } catch (SAXException ex) { Messages.info(XML2text.class.getName() + ": " + ex); } return buffer.toString(); } /** * Main function * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { XML2text xml = new XML2text(); String outDir = null;
Parameters pars = new Parameters();
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/input/Link.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // // Path: ocrevalUAtion/src/main/java/eu/digitisation/output/Browser.java // public class Browser { // // /** // * Open a URI // * // * @param uri the location of the file or resource // */ // public static void open(URI uri) { // System.out.println(uri); // if (Desktop.isDesktopSupported()) { // Desktop desktop = Desktop.getDesktop(); // if (desktop.isSupported(Action.BROWSE)) { // try { // Desktop.getDesktop().browse(uri); // } catch (IOException ex) { // Messages.info(Browser.class.getName() + ": " + ex); // } // } // } else { // try { // Runtime.getRuntime().exec( // "rundll32 url.dll,FileProtocolHandler " + uri); // } catch (IOException ex) { // Messages.info(Browser.class.getName() + ": " + ex); // } // } // } // }
import javax.swing.JLabel; import javax.swing.JPanel; import eu.digitisation.log.Messages; import eu.digitisation.output.Browser; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.net.URI; import java.net.URISyntaxException; import java.util.logging.Level; import java.util.logging.Logger;
/* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.input; /** * * @author R.C.C */ public class Link extends JPanel { private static final long serialVersionUID = 1L; JLabel link; /** * Basic constructor * @param title the text to be shown * @param url the linked URL * @param color the color of the link */ public Link(final String title, final String url, Color color) { setPreferredSize(new Dimension(600,30)); link = new JLabel(); link.setFont(new Font("Verdana", Font.PLAIN, 12)); link.setAlignmentX(LEFT_ALIGNMENT); link.setText("<html><body>" + title + "<a style=\"color:#4c501E\" href=\"" + url + "\">" + url + "</a></body></html>"); link.setCursor(new Cursor(Cursor.HAND_CURSOR)); link.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try {
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // // Path: ocrevalUAtion/src/main/java/eu/digitisation/output/Browser.java // public class Browser { // // /** // * Open a URI // * // * @param uri the location of the file or resource // */ // public static void open(URI uri) { // System.out.println(uri); // if (Desktop.isDesktopSupported()) { // Desktop desktop = Desktop.getDesktop(); // if (desktop.isSupported(Action.BROWSE)) { // try { // Desktop.getDesktop().browse(uri); // } catch (IOException ex) { // Messages.info(Browser.class.getName() + ": " + ex); // } // } // } else { // try { // Runtime.getRuntime().exec( // "rundll32 url.dll,FileProtocolHandler " + uri); // } catch (IOException ex) { // Messages.info(Browser.class.getName() + ": " + ex); // } // } // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/input/Link.java import javax.swing.JLabel; import javax.swing.JPanel; import eu.digitisation.log.Messages; import eu.digitisation.output.Browser; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.net.URI; import java.net.URISyntaxException; import java.util.logging.Level; import java.util.logging.Logger; /* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.input; /** * * @author R.C.C */ public class Link extends JPanel { private static final long serialVersionUID = 1L; JLabel link; /** * Basic constructor * @param title the text to be shown * @param url the linked URL * @param color the color of the link */ public Link(final String title, final String url, Color color) { setPreferredSize(new Dimension(600,30)); link = new JLabel(); link.setFont(new Font("Verdana", Font.PLAIN, 12)); link.setAlignmentX(LEFT_ALIGNMENT); link.setText("<html><body>" + title + "<a style=\"color:#4c501E\" href=\"" + url + "\">" + url + "</a></body></html>"); link.setCursor(new Cursor(Cursor.HAND_CURSOR)); link.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try {
Browser.open(new URI(url));
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/input/Link.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // // Path: ocrevalUAtion/src/main/java/eu/digitisation/output/Browser.java // public class Browser { // // /** // * Open a URI // * // * @param uri the location of the file or resource // */ // public static void open(URI uri) { // System.out.println(uri); // if (Desktop.isDesktopSupported()) { // Desktop desktop = Desktop.getDesktop(); // if (desktop.isSupported(Action.BROWSE)) { // try { // Desktop.getDesktop().browse(uri); // } catch (IOException ex) { // Messages.info(Browser.class.getName() + ": " + ex); // } // } // } else { // try { // Runtime.getRuntime().exec( // "rundll32 url.dll,FileProtocolHandler " + uri); // } catch (IOException ex) { // Messages.info(Browser.class.getName() + ": " + ex); // } // } // } // }
import javax.swing.JLabel; import javax.swing.JPanel; import eu.digitisation.log.Messages; import eu.digitisation.output.Browser; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.net.URI; import java.net.URISyntaxException; import java.util.logging.Level; import java.util.logging.Logger;
/* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.input; /** * * @author R.C.C */ public class Link extends JPanel { private static final long serialVersionUID = 1L; JLabel link; /** * Basic constructor * @param title the text to be shown * @param url the linked URL * @param color the color of the link */ public Link(final String title, final String url, Color color) { setPreferredSize(new Dimension(600,30)); link = new JLabel(); link.setFont(new Font("Verdana", Font.PLAIN, 12)); link.setAlignmentX(LEFT_ALIGNMENT); link.setText("<html><body>" + title + "<a style=\"color:#4c501E\" href=\"" + url + "\">" + url + "</a></body></html>"); link.setCursor(new Cursor(Cursor.HAND_CURSOR)); link.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { Browser.open(new URI(url)); } catch (URISyntaxException ex) {
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // // Path: ocrevalUAtion/src/main/java/eu/digitisation/output/Browser.java // public class Browser { // // /** // * Open a URI // * // * @param uri the location of the file or resource // */ // public static void open(URI uri) { // System.out.println(uri); // if (Desktop.isDesktopSupported()) { // Desktop desktop = Desktop.getDesktop(); // if (desktop.isSupported(Action.BROWSE)) { // try { // Desktop.getDesktop().browse(uri); // } catch (IOException ex) { // Messages.info(Browser.class.getName() + ": " + ex); // } // } // } else { // try { // Runtime.getRuntime().exec( // "rundll32 url.dll,FileProtocolHandler " + uri); // } catch (IOException ex) { // Messages.info(Browser.class.getName() + ": " + ex); // } // } // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/input/Link.java import javax.swing.JLabel; import javax.swing.JPanel; import eu.digitisation.log.Messages; import eu.digitisation.output.Browser; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.net.URI; import java.net.URISyntaxException; import java.util.logging.Level; import java.util.logging.Logger; /* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.input; /** * * @author R.C.C */ public class Link extends JPanel { private static final long serialVersionUID = 1L; JLabel link; /** * Basic constructor * @param title the text to be shown * @param url the linked URL * @param color the color of the link */ public Link(final String title, final String url, Color color) { setPreferredSize(new Dimension(600,30)); link = new JLabel(); link.setFont(new Font("Verdana", Font.PLAIN, 12)); link.setAlignmentX(LEFT_ALIGNMENT); link.setText("<html><body>" + title + "<a style=\"color:#4c501E\" href=\"" + url + "\">" + url + "</a></body></html>"); link.setCursor(new Cursor(Cursor.HAND_CURSOR)); link.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { Browser.open(new URI(url)); } catch (URISyntaxException ex) {
Messages.severe(Link.class.getName() + ex);
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/xml/DocumentWriter.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // }
import eu.digitisation.log.Messages; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import org.w3c.dom.Document;
/* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.xml; /** * Writes XML document to String or File * * @author R.C.C. */ public class DocumentWriter { static javax.xml.transform.Transformer transformer; javax.xml.transform.dom.DOMSource source; javax.xml.transform.stream.StreamResult result; static { try { transformer = javax.xml.transform.TransformerFactory .newInstance().newTransformer(); } catch (TransformerConfigurationException ex) {
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/xml/DocumentWriter.java import eu.digitisation.log.Messages; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import org.w3c.dom.Document; /* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.xml; /** * Writes XML document to String or File * * @author R.C.C. */ public class DocumentWriter { static javax.xml.transform.Transformer transformer; javax.xml.transform.dom.DOMSource source; javax.xml.transform.stream.StreamResult result; static { try { transformer = javax.xml.transform.TransformerFactory .newInstance().newTransformer(); } catch (TransformerConfigurationException ex) {
Messages.info(DocumentWriter.class.getName() + ": " + ex);
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/text/UnicodeReader.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // }
import eu.digitisation.log.Messages; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter;
} /** * Search for a Unicode sequence and highlight them in browser * * @param files files where the sequence is searched * @param outFile the output file * @param codepoints the Unicode sequence */ public static void find(File[] files, String codepoints, File outFile) { try { String pattern = codepointsToString(codepoints); for (File file : files) { BufferedReader reader = new BufferedReader(new FileReader(file)); PrintWriter writer = new PrintWriter(outFile); writer.print("<p><font color='blue'>" + file + "</font></p>"); while (reader.ready()) { String line = reader.readLine(); if (line.contains(pattern)) { writer.print("<p><font color='red'>" + StringNormalizer.encode(line) + "</font></p>"); } else { writer.print("<p>" + StringNormalizer.encode(line) + "</p>"); } } reader.close(); writer.close(); } } catch (IOException ex) {
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/text/UnicodeReader.java import eu.digitisation.log.Messages; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; } /** * Search for a Unicode sequence and highlight them in browser * * @param files files where the sequence is searched * @param outFile the output file * @param codepoints the Unicode sequence */ public static void find(File[] files, String codepoints, File outFile) { try { String pattern = codepointsToString(codepoints); for (File file : files) { BufferedReader reader = new BufferedReader(new FileReader(file)); PrintWriter writer = new PrintWriter(outFile); writer.print("<p><font color='blue'>" + file + "</font></p>"); while (reader.ready()) { String line = reader.readLine(); if (line.contains(pattern)) { writer.print("<p><font color='red'>" + StringNormalizer.encode(line) + "</font></p>"); } else { writer.print("<p>" + StringNormalizer.encode(line) + "</p>"); } } reader.close(); writer.close(); } } catch (IOException ex) {
Messages.info(CharFilter.class.getName() + ": " + ex);
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/input/FileSelector.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // }
import eu.digitisation.log.Messages; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JTextPane;
} @Override public void dragOver(DropTargetDragEvent e) { } @Override public void dropActionChanged(DropTargetDragEvent e) { } @Override @SuppressWarnings("unchecked") public void drop(DropTargetDropEvent e) { try { // Accept the drop first! e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); if (e.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { java.util.List<File> list; list = (java.util.List<File>) e.getTransferable() .getTransferData(DataFlavor.javaFileListFlavor); param.setValue(list.get(0)); } else if (e.isDataFlavorSupported(DataFlavor.stringFlavor)) { String name = (String) e.getTransferable() .getTransferData(DataFlavor.stringFlavor); param.setValue(new File(new URI(name.trim()))); } area.setText(getFile().getName()); dir = getFile().getParentFile(); shade(Color.decode("#B5CC9E")); } catch (URISyntaxException ex) {
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/input/FileSelector.java import eu.digitisation.log.Messages; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JTextPane; } @Override public void dragOver(DropTargetDragEvent e) { } @Override public void dropActionChanged(DropTargetDragEvent e) { } @Override @SuppressWarnings("unchecked") public void drop(DropTargetDropEvent e) { try { // Accept the drop first! e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); if (e.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { java.util.List<File> list; list = (java.util.List<File>) e.getTransferable() .getTransferData(DataFlavor.javaFileListFlavor); param.setValue(list.get(0)); } else if (e.isDataFlavorSupported(DataFlavor.stringFlavor)) { String name = (String) e.getTransferable() .getTransferData(DataFlavor.stringFlavor); param.setValue(new File(new URI(name.trim()))); } area.setText(getFile().getName()); dir = getFile().getParentFile(); shade(Color.decode("#B5CC9E")); } catch (URISyntaxException ex) {
Messages.info(FileSelector.class.getName() + ": " + ex);
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/xml/XMLPath.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // }
import eu.digitisation.log.Messages; import java.io.File; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList;
/* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.xml; /** * Evaluate XPath expressions. */ public class XMLPath { final static XPath xpath; static { xpath = XPathFactory.newInstance().newXPath(); } /** * Evaluate XPath expression * * @param doc the container document * @param expression XPath expression * @return the list of nodes matching the query */ public static NodeList evaluate(Document doc, String expression) { try { return (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET); } catch (XPathExpressionException ex) {
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/xml/XMLPath.java import eu.digitisation.log.Messages; import java.io.File; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.xml; /** * Evaluate XPath expressions. */ public class XMLPath { final static XPath xpath; static { xpath = XPathFactory.newInstance().newXPath(); } /** * Evaluate XPath expression * * @param doc the container document * @param expression XPath expression * @return the list of nodes matching the query */ public static NodeList evaluate(Document doc, String expression) { try { return (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET); } catch (XPathExpressionException ex) {
Messages.info(XMLPath.class.getName() + ": " + ex);
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/output/Browser.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // }
import eu.digitisation.log.Messages; import java.awt.Desktop; import java.awt.Desktop.Action; import java.io.IOException; import java.net.URI;
/* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.output; /** * Open a file or URL with an operating system application * * @author R.C.C. */ public class Browser { /** * Open a URI * * @param uri the location of the file or resource */ public static void open(URI uri) { System.out.println(uri); if (Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); if (desktop.isSupported(Action.BROWSE)) { try { Desktop.getDesktop().browse(uri); } catch (IOException ex) {
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/output/Browser.java import eu.digitisation.log.Messages; import java.awt.Desktop; import java.awt.Desktop.Action; import java.io.IOException; import java.net.URI; /* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.output; /** * Open a file or URL with an operating system application * * @author R.C.C. */ public class Browser { /** * Open a URI * * @param uri the location of the file or resource */ public static void open(URI uri) { System.out.println(uri); if (Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); if (desktop.isSupported(Action.BROWSE)) { try { Desktop.getDesktop().browse(uri); } catch (IOException ex) {
Messages.info(Browser.class.getName() + ": " + ex);
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/input/Settings.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // }
import eu.digitisation.log.Messages; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Properties;
/* * Copyright (C) 2014 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.input; /** * Start-up actions: load default and user properties (user-defined values * overwrite defaults). * * @author R.C.C. */ public class Settings { private static Properties props = new Properties(); /** * Get application directory */ private static File appDir() { try {
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/input/Settings.java import eu.digitisation.log.Messages; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Properties; /* * Copyright (C) 2014 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.input; /** * Start-up actions: load default and user properties (user-defined values * overwrite defaults). * * @author R.C.C. */ public class Settings { private static Properties props = new Properties(); /** * Get application directory */ private static File appDir() { try {
URI uri = Messages.class.getProtectionDomain()
tesseract4java/tesseract4java
ocrevalUAtion/src/test/java/eu/digitisation/distance/OcrOpWeightTest.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/text/StringNormalizer.java // public class StringNormalizer { // // final static java.text.Normalizer.Form decomposed = java.text.Normalizer.Form.NFD; // final static java.text.Normalizer.Form composed = java.text.Normalizer.Form.NFC; // static final java.text.Normalizer.Form compatible = java.text.Normalizer.Form.NFKC; // // /** // * Reduce whitespace (including line and paragraph separators) // * // * @param s // * a string. // * @return The string with simple spaces between words. // */ // public static String reduceWS(String s) { // return s.replaceAll("-\n", "").replaceAll( // "(\\p{Space}|\u2028|\u2029)+", " ").trim(); // } // // /** // * @param s // * a string // * @return the canonical representation of the string. // */ // public static String composed(String s) { // return java.text.Normalizer.normalize(s, composed); // } // // /** // * @param s // * a string // * @return the canonical representation of the string with normalized // * compatible characters. // */ // public static String compatible(String s) { // return java.text.Normalizer.normalize(s, compatible); // } // // /** // * @param s // * a string // * @return the string with all diacritics removed. // */ // public static String removeDiacritics(String s) { // return java.text.Normalizer.normalize(s, decomposed) // .replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); // } // // /** // * @param s // * a string // * @return the string with all punctuation symbols removed. // */ // public static String removePunctuation(String s) { // return s.replaceAll("\\p{P}+", ""); // } // // /** // * @param s // * a string // * @return the string with leading and trailing whitespace and punctuation // * symbols removed. // */ // public static String trim(String s) { // return s.replaceAll("^(\\p{P}|\\p{Space})+", "") // .replaceAll("(\\p{P}|\\p{Space})+$", ""); // } // // /** // * // * @param s // * the input string // * @param ignoreCase // * true if case is irrelevant // * @param ignoreDiacritics // * true if diacritics are irrelevant // * @param ignorePunctuation // * true if punctuation is irrelevant // * @return the canonical representation for comparison // */ // public static String canonical(String s, // boolean ignoreCase, // boolean ignoreDiacritics, // boolean ignorePunctuation) { // // String res = (ignorePunctuation) ? removePunctuation(s) : s; // if (ignoreCase) { // if (ignoreDiacritics) { // return StringNormalizer.removeDiacritics(res).toLowerCase(); // } else { // return res.toLowerCase(); // } // } else if (ignoreDiacritics) { // return StringNormalizer.removeDiacritics(res); // } else { // return res; // } // } // // /** // * Remove everything except for letters (with diacritics), numbers and // * spaces // * // * @param s // * a string // * @return the string with only letters, numbers, spaces and diacritics. // */ // public static String strip(String s) { // return s.replaceAll("[^\\p{L}\\p{M}\\p{N}\\p{Space}]", ""); // } // // /** // * @param s // * a string // * @return the string with characters <, >, &, " escaped // */ // public static String encode(String s) { // StringBuilder result = new StringBuilder(); // for (Character c : s.toCharArray()) { // if (c.equals('<')) { // result.append("&lt;"); // } else if (c.equals('>')) { // result.append("&gt;"); // } else if (c.equals('"')) { // result.append("&quot;"); // } else if (c.equals('&')) { // result.append("&amp;"); // } else { // result.append(c); // } // } // return result.toString(); // } // }
import eu.digitisation.text.StringNormalizer; import static org.junit.Assert.assertEquals; import org.junit.Test;
/* * Copyright (C) 2014 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.distance; /** * * @author rafa */ public class OcrOpWeightTest { /** * Test of sub method, of class OcrWeights. */ @Test public void testSub() { System.out.println("sub"); char[] c1 = {'Á', 'Á', 'Á', 'Á', 'Á'}; char[] c2 = {'Á', 'A', 'á', 'a', ' '}; int[] w1 = {0, 1, 1, 1, 2}; OcrOpWeight W1 = new OcrOpWeight(); // fully-sensitive for (int n = 0; n < w1.length; ++n) {
// Path: ocrevalUAtion/src/main/java/eu/digitisation/text/StringNormalizer.java // public class StringNormalizer { // // final static java.text.Normalizer.Form decomposed = java.text.Normalizer.Form.NFD; // final static java.text.Normalizer.Form composed = java.text.Normalizer.Form.NFC; // static final java.text.Normalizer.Form compatible = java.text.Normalizer.Form.NFKC; // // /** // * Reduce whitespace (including line and paragraph separators) // * // * @param s // * a string. // * @return The string with simple spaces between words. // */ // public static String reduceWS(String s) { // return s.replaceAll("-\n", "").replaceAll( // "(\\p{Space}|\u2028|\u2029)+", " ").trim(); // } // // /** // * @param s // * a string // * @return the canonical representation of the string. // */ // public static String composed(String s) { // return java.text.Normalizer.normalize(s, composed); // } // // /** // * @param s // * a string // * @return the canonical representation of the string with normalized // * compatible characters. // */ // public static String compatible(String s) { // return java.text.Normalizer.normalize(s, compatible); // } // // /** // * @param s // * a string // * @return the string with all diacritics removed. // */ // public static String removeDiacritics(String s) { // return java.text.Normalizer.normalize(s, decomposed) // .replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); // } // // /** // * @param s // * a string // * @return the string with all punctuation symbols removed. // */ // public static String removePunctuation(String s) { // return s.replaceAll("\\p{P}+", ""); // } // // /** // * @param s // * a string // * @return the string with leading and trailing whitespace and punctuation // * symbols removed. // */ // public static String trim(String s) { // return s.replaceAll("^(\\p{P}|\\p{Space})+", "") // .replaceAll("(\\p{P}|\\p{Space})+$", ""); // } // // /** // * // * @param s // * the input string // * @param ignoreCase // * true if case is irrelevant // * @param ignoreDiacritics // * true if diacritics are irrelevant // * @param ignorePunctuation // * true if punctuation is irrelevant // * @return the canonical representation for comparison // */ // public static String canonical(String s, // boolean ignoreCase, // boolean ignoreDiacritics, // boolean ignorePunctuation) { // // String res = (ignorePunctuation) ? removePunctuation(s) : s; // if (ignoreCase) { // if (ignoreDiacritics) { // return StringNormalizer.removeDiacritics(res).toLowerCase(); // } else { // return res.toLowerCase(); // } // } else if (ignoreDiacritics) { // return StringNormalizer.removeDiacritics(res); // } else { // return res; // } // } // // /** // * Remove everything except for letters (with diacritics), numbers and // * spaces // * // * @param s // * a string // * @return the string with only letters, numbers, spaces and diacritics. // */ // public static String strip(String s) { // return s.replaceAll("[^\\p{L}\\p{M}\\p{N}\\p{Space}]", ""); // } // // /** // * @param s // * a string // * @return the string with characters <, >, &, " escaped // */ // public static String encode(String s) { // StringBuilder result = new StringBuilder(); // for (Character c : s.toCharArray()) { // if (c.equals('<')) { // result.append("&lt;"); // } else if (c.equals('>')) { // result.append("&gt;"); // } else if (c.equals('"')) { // result.append("&quot;"); // } else if (c.equals('&')) { // result.append("&amp;"); // } else { // result.append(c); // } // } // return result.toString(); // } // } // Path: ocrevalUAtion/src/test/java/eu/digitisation/distance/OcrOpWeightTest.java import eu.digitisation.text.StringNormalizer; import static org.junit.Assert.assertEquals; import org.junit.Test; /* * Copyright (C) 2014 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.distance; /** * * @author rafa */ public class OcrOpWeightTest { /** * Test of sub method, of class OcrWeights. */ @Test public void testSub() { System.out.println("sub"); char[] c1 = {'Á', 'Á', 'Á', 'Á', 'Á'}; char[] c2 = {'Á', 'A', 'á', 'a', ' '}; int[] w1 = {0, 1, 1, 1, 2}; OcrOpWeight W1 = new OcrOpWeight(); // fully-sensitive for (int n = 0; n < w1.length; ++n) {
String s1 = StringNormalizer.canonical(String.valueOf(c1[n]), false, false, false);
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/text/WordSet.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/input/WarningException.java // public class WarningException extends Exception { // private static final long serialVersionUID = 1L; // // /** // * Default constructor // * @param message // */ // public WarningException(String message) { // super(message); // } // }
import eu.digitisation.input.WarningException; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashSet;
/* * Copyright (C) 2014 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.text; /** * * @author R.C.C. */ public class WordSet extends HashSet<String> { private static final long serialVersionUID = 1L; /** * Default constructor * * @param file the file containing the list of stop-words (separated by * blanks or newlines) * @throws IOException */
// Path: ocrevalUAtion/src/main/java/eu/digitisation/input/WarningException.java // public class WarningException extends Exception { // private static final long serialVersionUID = 1L; // // /** // * Default constructor // * @param message // */ // public WarningException(String message) { // super(message); // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/text/WordSet.java import eu.digitisation.input.WarningException; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashSet; /* * Copyright (C) 2014 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.text; /** * * @author R.C.C. */ public class WordSet extends HashSet<String> { private static final long serialVersionUID = 1L; /** * Default constructor * * @param file the file containing the list of stop-words (separated by * blanks or newlines) * @throws IOException */
public WordSet(File file) throws WarningException {
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/xml/DocumentBuilder.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // }
import eu.digitisation.log.Messages; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList;
/* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.xml; /** * Adds some useful auxiliary functions to handle XML documents * * @author R.C.C */ public class DocumentBuilder { Document doc; /** * Create an empty document * * @param doctype the document type */ public DocumentBuilder(String doctype) { try { doc = javax.xml.parsers.DocumentBuilderFactory .newInstance().newDocumentBuilder() .newDocument(); Element root = doc.createElement(doctype); doc.appendChild(root); } catch (ParserConfigurationException ex) {
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/xml/DocumentBuilder.java import eu.digitisation.log.Messages; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.xml; /** * Adds some useful auxiliary functions to handle XML documents * * @author R.C.C */ public class DocumentBuilder { Document doc; /** * Create an empty document * * @param doctype the document type */ public DocumentBuilder(String doctype) { try { doc = javax.xml.parsers.DocumentBuilderFactory .newInstance().newDocumentBuilder() .newDocument(); Element root = doc.createElement(doctype); doc.appendChild(root); } catch (ParserConfigurationException ex) {
Messages.info(DocumentBuilder.class.getName() + ": " + ex);
tesseract4java/tesseract4java
ocrevalUAtion/src/test/java/eu/digitisation/text/TestUnicodeReader.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/text/UnicodeReader.java // public class UnicodeReader { // // /** // * Transform a sequence of Unicode values (blocks of four hexadecimal // * digits) into the string they represent. For example, "00410042" (or "0041 // * 0042") represents "AB" // * // * @param codes the sequence of one or more Unicode hex values // * @return the string represented by these codes // * @throws java.io.IOException // */ // protected static String codepointsToString(String codes) throws IOException { // StringBuilder builder = new StringBuilder(); // String[] tokens = codes.trim().split("\\p{Space}+"); // // for (String token : tokens) { // if (token.length() % 4 != 0) { // throw new IOException(token // + " is not a valid Unicode hex sequence"); // } // for (int pos = 0; pos + 3 < token.length(); pos += 4) { // String sub = token.substring(pos, pos + 4); // int val = Integer.parseInt(sub, 16); // builder.append((char) val); // } // } // return builder.toString(); // } // // /** // * Build a string from the codepoints (Unicode values) defining its content // * // * @param codes // * @return the string represented by those codepoints // */ // public static String codepointsToString(int[] codes) { // StringBuilder buff = new StringBuilder(); // for (int code : codes) { // buff.append((char) code); // } // return buff.toString(); // } // // /** // * Convert a string into a sequence of Unicode values // * // * @param s a Java String // * @return The array of Unicode values of the characters in s // */ // public static int[] toCodepoints(String s) { // int[] codes = new int[s.length()]; // for (int n = 0; n < s.length(); ++n) { // codes[n] = (int) s.charAt(n); // } // return codes; // } // // /** // * Transform an array of integers into their hexadecimal representation // * // * @param values an integer array // * @return the hexadecimal strings representing their value. // */ // private static String[] toHexString(int[] values) { // String[] hex = new String[values.length]; // for (int n = 0; n < values.length; ++n) { // hex[n] = Integer.toHexString(values[n]); // } // return hex; // } // // /** // * Convert a string into a sequence of Unicode hexadecimal values // * // * @param s a Java String // * @return The array of Unicode values (hexadecimal representation) of the // * characters in s // */ // public static String[] toHexCodepoints(String s) { // return toHexString(toCodepoints(s)); // } // // /** // * Read a text file and print the content as codepoints (Unicode values) in // * it // * // * @param file the input file // * @throws Exception // */ // public static void printHexCodepoints(File file) // throws Exception { // BufferedReader reader = new BufferedReader(new FileReader(file)); // while (reader.ready()) { // String line = reader.readLine(); // String[] hexcodes = toHexCodepoints(line); // System.out.println(java.util.Arrays.toString(hexcodes)); // } // reader.close(); // } // // /** // * Search for a Unicode sequence and highlight them in browser // * // * @param files files where the sequence is searched // * @param outFile the output file // * @param codepoints the Unicode sequence // */ // public static void find(File[] files, String codepoints, File outFile) { // try { // String pattern = codepointsToString(codepoints); // for (File file : files) { // BufferedReader reader = new BufferedReader(new FileReader(file)); // PrintWriter writer = new PrintWriter(outFile); // writer.print("<p><font color='blue'>" // + file + "</font></p>"); // while (reader.ready()) { // String line = reader.readLine(); // if (line.contains(pattern)) { // writer.print("<p><font color='red'>" // + StringNormalizer.encode(line) + "</font></p>"); // } else { // writer.print("<p>" + StringNormalizer.encode(line) + "</p>"); // } // } // reader.close(); // writer.close(); // } // } catch (IOException ex) { // Messages.info(CharFilter.class.getName() + ": " + ex); // } // } // }
import eu.digitisation.text.UnicodeReader; import junit.framework.TestCase;
package eu.digitisation.text; /** * * @author R.C.C */ public class TestUnicodeReader extends TestCase { public void testUnicodeReader() { String input = "día, mes y año"; String ref = "[100, 237, 97, 44, 32, 109, 101, 115, 32, 121, 32, 97, 241, 111]"; String output =
// Path: ocrevalUAtion/src/main/java/eu/digitisation/text/UnicodeReader.java // public class UnicodeReader { // // /** // * Transform a sequence of Unicode values (blocks of four hexadecimal // * digits) into the string they represent. For example, "00410042" (or "0041 // * 0042") represents "AB" // * // * @param codes the sequence of one or more Unicode hex values // * @return the string represented by these codes // * @throws java.io.IOException // */ // protected static String codepointsToString(String codes) throws IOException { // StringBuilder builder = new StringBuilder(); // String[] tokens = codes.trim().split("\\p{Space}+"); // // for (String token : tokens) { // if (token.length() % 4 != 0) { // throw new IOException(token // + " is not a valid Unicode hex sequence"); // } // for (int pos = 0; pos + 3 < token.length(); pos += 4) { // String sub = token.substring(pos, pos + 4); // int val = Integer.parseInt(sub, 16); // builder.append((char) val); // } // } // return builder.toString(); // } // // /** // * Build a string from the codepoints (Unicode values) defining its content // * // * @param codes // * @return the string represented by those codepoints // */ // public static String codepointsToString(int[] codes) { // StringBuilder buff = new StringBuilder(); // for (int code : codes) { // buff.append((char) code); // } // return buff.toString(); // } // // /** // * Convert a string into a sequence of Unicode values // * // * @param s a Java String // * @return The array of Unicode values of the characters in s // */ // public static int[] toCodepoints(String s) { // int[] codes = new int[s.length()]; // for (int n = 0; n < s.length(); ++n) { // codes[n] = (int) s.charAt(n); // } // return codes; // } // // /** // * Transform an array of integers into their hexadecimal representation // * // * @param values an integer array // * @return the hexadecimal strings representing their value. // */ // private static String[] toHexString(int[] values) { // String[] hex = new String[values.length]; // for (int n = 0; n < values.length; ++n) { // hex[n] = Integer.toHexString(values[n]); // } // return hex; // } // // /** // * Convert a string into a sequence of Unicode hexadecimal values // * // * @param s a Java String // * @return The array of Unicode values (hexadecimal representation) of the // * characters in s // */ // public static String[] toHexCodepoints(String s) { // return toHexString(toCodepoints(s)); // } // // /** // * Read a text file and print the content as codepoints (Unicode values) in // * it // * // * @param file the input file // * @throws Exception // */ // public static void printHexCodepoints(File file) // throws Exception { // BufferedReader reader = new BufferedReader(new FileReader(file)); // while (reader.ready()) { // String line = reader.readLine(); // String[] hexcodes = toHexCodepoints(line); // System.out.println(java.util.Arrays.toString(hexcodes)); // } // reader.close(); // } // // /** // * Search for a Unicode sequence and highlight them in browser // * // * @param files files where the sequence is searched // * @param outFile the output file // * @param codepoints the Unicode sequence // */ // public static void find(File[] files, String codepoints, File outFile) { // try { // String pattern = codepointsToString(codepoints); // for (File file : files) { // BufferedReader reader = new BufferedReader(new FileReader(file)); // PrintWriter writer = new PrintWriter(outFile); // writer.print("<p><font color='blue'>" // + file + "</font></p>"); // while (reader.ready()) { // String line = reader.readLine(); // if (line.contains(pattern)) { // writer.print("<p><font color='red'>" // + StringNormalizer.encode(line) + "</font></p>"); // } else { // writer.print("<p>" + StringNormalizer.encode(line) + "</p>"); // } // } // reader.close(); // writer.close(); // } // } catch (IOException ex) { // Messages.info(CharFilter.class.getName() + ": " + ex); // } // } // } // Path: ocrevalUAtion/src/test/java/eu/digitisation/text/TestUnicodeReader.java import eu.digitisation.text.UnicodeReader; import junit.framework.TestCase; package eu.digitisation.text; /** * * @author R.C.C */ public class TestUnicodeReader extends TestCase { public void testUnicodeReader() { String input = "día, mes y año"; String ref = "[100, 237, 97, 44, 32, 109, 101, 115, 32, 121, 32, 97, 241, 111]"; String output =
java.util.Arrays.toString(UnicodeReader.toCodepoints(input));
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/input/Help.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // // Path: ocrevalUAtion/src/main/java/eu/digitisation/output/Browser.java // public class Browser { // // /** // * Open a URI // * // * @param uri the location of the file or resource // */ // public static void open(URI uri) { // System.out.println(uri); // if (Desktop.isDesktopSupported()) { // Desktop desktop = Desktop.getDesktop(); // if (desktop.isSupported(Action.BROWSE)) { // try { // Desktop.getDesktop().browse(uri); // } catch (IOException ex) { // Messages.info(Browser.class.getName() + ": " + ex); // } // } // } else { // try { // Runtime.getRuntime().exec( // "rundll32 url.dll,FileProtocolHandler " + uri); // } catch (IOException ex) { // Messages.info(Browser.class.getName() + ": " + ex); // } // } // } // }
import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JOptionPane; import eu.digitisation.log.Messages; import eu.digitisation.output.Browser; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Ellipse2D; import java.net.URI; import java.net.URISyntaxException; import java.util.logging.Level;
/* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.input; /** * Help text or URL for additional information (URL must start with http:) * * @author R.C.C. */ public class Help extends JButton { private static final long serialVersionUID = 1L; String text; // help text /** * Default constructor * * @param helpText the help text or URL * @param forecolor foreground color * @param bgcolor background color */ public Help(String helpText, Color forecolor, Color bgcolor) { super("?"); setPreferredSize(new Dimension(10, 10)); setForeground(forecolor); setBackground(bgcolor); setContentAreaFilled(false); this.text = helpText; addActionListener(new ActionListener() { Container container = getParent(); @Override public void actionPerformed(ActionEvent e) { if (text.startsWith("http:")) { try {
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // // Path: ocrevalUAtion/src/main/java/eu/digitisation/output/Browser.java // public class Browser { // // /** // * Open a URI // * // * @param uri the location of the file or resource // */ // public static void open(URI uri) { // System.out.println(uri); // if (Desktop.isDesktopSupported()) { // Desktop desktop = Desktop.getDesktop(); // if (desktop.isSupported(Action.BROWSE)) { // try { // Desktop.getDesktop().browse(uri); // } catch (IOException ex) { // Messages.info(Browser.class.getName() + ": " + ex); // } // } // } else { // try { // Runtime.getRuntime().exec( // "rundll32 url.dll,FileProtocolHandler " + uri); // } catch (IOException ex) { // Messages.info(Browser.class.getName() + ": " + ex); // } // } // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/input/Help.java import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JOptionPane; import eu.digitisation.log.Messages; import eu.digitisation.output.Browser; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Ellipse2D; import java.net.URI; import java.net.URISyntaxException; import java.util.logging.Level; /* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.input; /** * Help text or URL for additional information (URL must start with http:) * * @author R.C.C. */ public class Help extends JButton { private static final long serialVersionUID = 1L; String text; // help text /** * Default constructor * * @param helpText the help text or URL * @param forecolor foreground color * @param bgcolor background color */ public Help(String helpText, Color forecolor, Color bgcolor) { super("?"); setPreferredSize(new Dimension(10, 10)); setForeground(forecolor); setBackground(bgcolor); setContentAreaFilled(false); this.text = helpText; addActionListener(new ActionListener() { Container container = getParent(); @Override public void actionPerformed(ActionEvent e) { if (text.startsWith("http:")) { try {
Browser.open(new URI(text));
tesseract4java/tesseract4java
ocrevalUAtion/src/main/java/eu/digitisation/input/Help.java
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // // Path: ocrevalUAtion/src/main/java/eu/digitisation/output/Browser.java // public class Browser { // // /** // * Open a URI // * // * @param uri the location of the file or resource // */ // public static void open(URI uri) { // System.out.println(uri); // if (Desktop.isDesktopSupported()) { // Desktop desktop = Desktop.getDesktop(); // if (desktop.isSupported(Action.BROWSE)) { // try { // Desktop.getDesktop().browse(uri); // } catch (IOException ex) { // Messages.info(Browser.class.getName() + ": " + ex); // } // } // } else { // try { // Runtime.getRuntime().exec( // "rundll32 url.dll,FileProtocolHandler " + uri); // } catch (IOException ex) { // Messages.info(Browser.class.getName() + ": " + ex); // } // } // } // }
import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JOptionPane; import eu.digitisation.log.Messages; import eu.digitisation.output.Browser; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Ellipse2D; import java.net.URI; import java.net.URISyntaxException; import java.util.logging.Level;
/* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.input; /** * Help text or URL for additional information (URL must start with http:) * * @author R.C.C. */ public class Help extends JButton { private static final long serialVersionUID = 1L; String text; // help text /** * Default constructor * * @param helpText the help text or URL * @param forecolor foreground color * @param bgcolor background color */ public Help(String helpText, Color forecolor, Color bgcolor) { super("?"); setPreferredSize(new Dimension(10, 10)); setForeground(forecolor); setBackground(bgcolor); setContentAreaFilled(false); this.text = helpText; addActionListener(new ActionListener() { Container container = getParent(); @Override public void actionPerformed(ActionEvent e) { if (text.startsWith("http:")) { try { Browser.open(new URI(text)); } catch (URISyntaxException ex) {
// Path: ocrevalUAtion/src/main/java/eu/digitisation/log/Messages.java // public class Messages { // // // private static final Logger logger = Logger.getLogger("ApplicationLog"); // // static { // // try { // // URI uri = Messages.class.getProtectionDomain() // // .getCodeSource().getLocation().toURI(); // // String dir = new File(uri.getPath()).getParent(); // // File file = new File(dir, "ocrevaluation.log"); // // // // addFile(file); // // Messages.info("Logfile is " + file); // // // // // while debugging // // if (java.awt.Desktop.isDesktopSupported()) { // // addFrame(); // // } // // } catch (SecurityException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } catch (URISyntaxException ex) { // // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null, // // ex); // // } // } // // public static void addFile(File file) { // // try { // // FileHandler fh = new FileHandler(file.getAbsolutePath()); // // fh.setFormatter(new LogFormatter()); // // logger.addHandler(fh); // // } catch (IOException ex) { // // Messages.info(Messages.class.getName() + ": " + ex); // // } // } // // public static void addFrame() { // // Only while debugging // // LogFrameHandler lfh = new LogFrameHandler(); // // lfh.setFormatter(new LogFormatter()); // // logger.addHandler(lfh); // } // // public static void info(String s) { // // logger.info(s); // } // // public static void warning(String s) { // // logger.warning(s); // } // // public static void severe(String s) { // // logger.severe(s); // } // } // // Path: ocrevalUAtion/src/main/java/eu/digitisation/output/Browser.java // public class Browser { // // /** // * Open a URI // * // * @param uri the location of the file or resource // */ // public static void open(URI uri) { // System.out.println(uri); // if (Desktop.isDesktopSupported()) { // Desktop desktop = Desktop.getDesktop(); // if (desktop.isSupported(Action.BROWSE)) { // try { // Desktop.getDesktop().browse(uri); // } catch (IOException ex) { // Messages.info(Browser.class.getName() + ": " + ex); // } // } // } else { // try { // Runtime.getRuntime().exec( // "rundll32 url.dll,FileProtocolHandler " + uri); // } catch (IOException ex) { // Messages.info(Browser.class.getName() + ": " + ex); // } // } // } // } // Path: ocrevalUAtion/src/main/java/eu/digitisation/input/Help.java import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JOptionPane; import eu.digitisation.log.Messages; import eu.digitisation.output.Browser; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Ellipse2D; import java.net.URI; import java.net.URISyntaxException; import java.util.logging.Level; /* * Copyright (C) 2013 Universidad de Alicante * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package eu.digitisation.input; /** * Help text or URL for additional information (URL must start with http:) * * @author R.C.C. */ public class Help extends JButton { private static final long serialVersionUID = 1L; String text; // help text /** * Default constructor * * @param helpText the help text or URL * @param forecolor foreground color * @param bgcolor background color */ public Help(String helpText, Color forecolor, Color bgcolor) { super("?"); setPreferredSize(new Dimension(10, 10)); setForeground(forecolor); setBackground(bgcolor); setContentAreaFilled(false); this.text = helpText; addActionListener(new ActionListener() { Container container = getParent(); @Override public void actionPerformed(ActionEvent e) { if (text.startsWith("http:")) { try { Browser.open(new URI(text)); } catch (URISyntaxException ex) {
Messages.severe(Help.class.getName() + ex);
fuinorg/utils4j
src/test/java/org/fuin/utils4j/Utils4JTest.java
// Path: src/test/java/org/fuin/utils4j/test/ClassWithPrivateConstructor.java // public class ClassWithPrivateConstructor { // // private ClassWithPrivateConstructor() { // } // // }
import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.net.MalformedURLException; import java.net.URL; import java.nio.channels.FileLock; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import org.apache.commons.io.FileUtils; import org.fuin.utils4j.test.ClassWithPrivateConstructor; import org.junit.BeforeClass; import org.junit.Test;
@Test public final void testCreateInstanceOK() { final Object obj = Utils4J.createInstance(Utils4JTest.class.getName()); assertThat(obj).isInstanceOf(Utils4JTest.class); } @Test public final void testCreateInstanceClassNotFound() { try { Utils4J.createInstance("x.y.Z"); fail(); } catch (final RuntimeException ex) { assertThat(ex.getCause()).isInstanceOf(ClassNotFoundException.class); } } @Test public final void testCreateInstanceInstantiationProblem() { try { Utils4J.createInstance(Cancelable.class.getName()); fail(); } catch (final RuntimeException ex) { assertThat(ex.getCause()).isInstanceOf(NoSuchMethodException.class); } } @Test public final void testCreateInstanceIllegalAccess() { try {
// Path: src/test/java/org/fuin/utils4j/test/ClassWithPrivateConstructor.java // public class ClassWithPrivateConstructor { // // private ClassWithPrivateConstructor() { // } // // } // Path: src/test/java/org/fuin/utils4j/Utils4JTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.net.MalformedURLException; import java.net.URL; import java.nio.channels.FileLock; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import org.apache.commons.io.FileUtils; import org.fuin.utils4j.test.ClassWithPrivateConstructor; import org.junit.BeforeClass; import org.junit.Test; @Test public final void testCreateInstanceOK() { final Object obj = Utils4J.createInstance(Utils4JTest.class.getName()); assertThat(obj).isInstanceOf(Utils4JTest.class); } @Test public final void testCreateInstanceClassNotFound() { try { Utils4J.createInstance("x.y.Z"); fail(); } catch (final RuntimeException ex) { assertThat(ex.getCause()).isInstanceOf(ClassNotFoundException.class); } } @Test public final void testCreateInstanceInstantiationProblem() { try { Utils4J.createInstance(Cancelable.class.getName()); fail(); } catch (final RuntimeException ex) { assertThat(ex.getCause()).isInstanceOf(NoSuchMethodException.class); } } @Test public final void testCreateInstanceIllegalAccess() { try {
Utils4J.createInstance(ClassWithPrivateConstructor.class.getName());
fuinorg/utils4j
src/test/java/org/fuin/utils4j/examples/CDataJaxbExample.java
// Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> String marshal(final T data, final Class<?>... classesToBeBound) { // return marshal(data, null, classesToBeBound); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> T unmarshal(final String xmlData, final Class<?>... classesToBeBound) { // final Unmarshaller unmarshaller = new UnmarshallerBuilder().addClassesToBeBound(classesToBeBound).build(); // return unmarshal(unmarshaller, xmlData); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/CDataXmlAdapter.java // public final class CDataXmlAdapter extends XmlAdapter<String, String> { // // @Override // public final String marshal(final String value) throws Exception { // if (value == null) { // return null; // } // return "<![CDATA[" + value + "]]>"; // } // // @Override // public final String unmarshal(final String value) throws Exception { // if (value == null) { // return null; // } // return value; // } // // } // // Path: src/main/java/org/fuin/utils4j/jaxb/CDataXmlStreamWriter.java // public final class CDataXmlStreamWriter extends XMLStreamWriterAdapter { // // /** // * Constructor with delegate. // * // * @param delegate // * All method calls are delegated to this writer. // */ // public CDataXmlStreamWriter(final XMLStreamWriter delegate) { // super(delegate); // } // // @Override // public final void writeCharacters(final String text) throws XMLStreamException { // writeText(text); // } // // @Override // public final void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException { // writeText(new String(text, start, len)); // } // // private void writeText(final String text) throws XMLStreamException { // if (text.startsWith("<![CDATA[") && text.endsWith("]]>")) { // final String str = text.substring(9, text.length() - 3); // super.writeCData(str); // } else { // super.writeCharacters(text); // } // } // // } // // Path: src/test/java/org/fuin/utils4j/jaxb/MyClassWithCData.java // @XmlRootElement(name = "my-class-with-cdata") // public final class MyClassWithCData { // // @XmlValue // @XmlJavaTypeAdapter(CDataXmlAdapter.class) // private String content; // // /** // * Default constructor for JAXB. // */ // protected MyClassWithCData() { // super(); // } // // /** // * Constructor with mandatory data. // * // * @param content // * CDATA content. // */ // public MyClassWithCData(final String content) { // super(); // this.content = content; // } // // /** // * Returns the content. // * // * @return Content. // */ // public String getContent() { // return content; // } // // }
import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; import java.io.StringWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import jakarta.xml.bind.JAXBContext; import org.fuin.utils4j.jaxb.CDataXmlAdapter; import org.fuin.utils4j.jaxb.CDataXmlStreamWriter; import org.fuin.utils4j.jaxb.MyClassWithCData;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.examples; /** * Short example for using the {@link CDataXmlStreamWriter} together with the {@link CDataXmlAdapter}. */ // CHECKSTYLE:OFF public class CDataJaxbExample { /** * Executes the example. * * @param args * Not used. */ public static void main(String[] args) throws Exception { // Create writers final StringWriter writer = new StringWriter(); final XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer);
// Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> String marshal(final T data, final Class<?>... classesToBeBound) { // return marshal(data, null, classesToBeBound); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> T unmarshal(final String xmlData, final Class<?>... classesToBeBound) { // final Unmarshaller unmarshaller = new UnmarshallerBuilder().addClassesToBeBound(classesToBeBound).build(); // return unmarshal(unmarshaller, xmlData); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/CDataXmlAdapter.java // public final class CDataXmlAdapter extends XmlAdapter<String, String> { // // @Override // public final String marshal(final String value) throws Exception { // if (value == null) { // return null; // } // return "<![CDATA[" + value + "]]>"; // } // // @Override // public final String unmarshal(final String value) throws Exception { // if (value == null) { // return null; // } // return value; // } // // } // // Path: src/main/java/org/fuin/utils4j/jaxb/CDataXmlStreamWriter.java // public final class CDataXmlStreamWriter extends XMLStreamWriterAdapter { // // /** // * Constructor with delegate. // * // * @param delegate // * All method calls are delegated to this writer. // */ // public CDataXmlStreamWriter(final XMLStreamWriter delegate) { // super(delegate); // } // // @Override // public final void writeCharacters(final String text) throws XMLStreamException { // writeText(text); // } // // @Override // public final void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException { // writeText(new String(text, start, len)); // } // // private void writeText(final String text) throws XMLStreamException { // if (text.startsWith("<![CDATA[") && text.endsWith("]]>")) { // final String str = text.substring(9, text.length() - 3); // super.writeCData(str); // } else { // super.writeCharacters(text); // } // } // // } // // Path: src/test/java/org/fuin/utils4j/jaxb/MyClassWithCData.java // @XmlRootElement(name = "my-class-with-cdata") // public final class MyClassWithCData { // // @XmlValue // @XmlJavaTypeAdapter(CDataXmlAdapter.class) // private String content; // // /** // * Default constructor for JAXB. // */ // protected MyClassWithCData() { // super(); // } // // /** // * Constructor with mandatory data. // * // * @param content // * CDATA content. // */ // public MyClassWithCData(final String content) { // super(); // this.content = content; // } // // /** // * Returns the content. // * // * @return Content. // */ // public String getContent() { // return content; // } // // } // Path: src/test/java/org/fuin/utils4j/examples/CDataJaxbExample.java import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; import java.io.StringWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import jakarta.xml.bind.JAXBContext; import org.fuin.utils4j.jaxb.CDataXmlAdapter; import org.fuin.utils4j.jaxb.CDataXmlStreamWriter; import org.fuin.utils4j.jaxb.MyClassWithCData; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.examples; /** * Short example for using the {@link CDataXmlStreamWriter} together with the {@link CDataXmlAdapter}. */ // CHECKSTYLE:OFF public class CDataJaxbExample { /** * Executes the example. * * @param args * Not used. */ public static void main(String[] args) throws Exception { // Create writers final StringWriter writer = new StringWriter(); final XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer);
final CDataXmlStreamWriter cdataWriter = new CDataXmlStreamWriter(xmlWriter);
fuinorg/utils4j
src/test/java/org/fuin/utils4j/examples/CDataJaxbExample.java
// Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> String marshal(final T data, final Class<?>... classesToBeBound) { // return marshal(data, null, classesToBeBound); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> T unmarshal(final String xmlData, final Class<?>... classesToBeBound) { // final Unmarshaller unmarshaller = new UnmarshallerBuilder().addClassesToBeBound(classesToBeBound).build(); // return unmarshal(unmarshaller, xmlData); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/CDataXmlAdapter.java // public final class CDataXmlAdapter extends XmlAdapter<String, String> { // // @Override // public final String marshal(final String value) throws Exception { // if (value == null) { // return null; // } // return "<![CDATA[" + value + "]]>"; // } // // @Override // public final String unmarshal(final String value) throws Exception { // if (value == null) { // return null; // } // return value; // } // // } // // Path: src/main/java/org/fuin/utils4j/jaxb/CDataXmlStreamWriter.java // public final class CDataXmlStreamWriter extends XMLStreamWriterAdapter { // // /** // * Constructor with delegate. // * // * @param delegate // * All method calls are delegated to this writer. // */ // public CDataXmlStreamWriter(final XMLStreamWriter delegate) { // super(delegate); // } // // @Override // public final void writeCharacters(final String text) throws XMLStreamException { // writeText(text); // } // // @Override // public final void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException { // writeText(new String(text, start, len)); // } // // private void writeText(final String text) throws XMLStreamException { // if (text.startsWith("<![CDATA[") && text.endsWith("]]>")) { // final String str = text.substring(9, text.length() - 3); // super.writeCData(str); // } else { // super.writeCharacters(text); // } // } // // } // // Path: src/test/java/org/fuin/utils4j/jaxb/MyClassWithCData.java // @XmlRootElement(name = "my-class-with-cdata") // public final class MyClassWithCData { // // @XmlValue // @XmlJavaTypeAdapter(CDataXmlAdapter.class) // private String content; // // /** // * Default constructor for JAXB. // */ // protected MyClassWithCData() { // super(); // } // // /** // * Constructor with mandatory data. // * // * @param content // * CDATA content. // */ // public MyClassWithCData(final String content) { // super(); // this.content = content; // } // // /** // * Returns the content. // * // * @return Content. // */ // public String getContent() { // return content; // } // // }
import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; import java.io.StringWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import jakarta.xml.bind.JAXBContext; import org.fuin.utils4j.jaxb.CDataXmlAdapter; import org.fuin.utils4j.jaxb.CDataXmlStreamWriter; import org.fuin.utils4j.jaxb.MyClassWithCData;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.examples; /** * Short example for using the {@link CDataXmlStreamWriter} together with the {@link CDataXmlAdapter}. */ // CHECKSTYLE:OFF public class CDataJaxbExample { /** * Executes the example. * * @param args * Not used. */ public static void main(String[] args) throws Exception { // Create writers final StringWriter writer = new StringWriter(); final XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer); final CDataXmlStreamWriter cdataWriter = new CDataXmlStreamWriter(xmlWriter); // Create JAXB context with example class
// Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> String marshal(final T data, final Class<?>... classesToBeBound) { // return marshal(data, null, classesToBeBound); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> T unmarshal(final String xmlData, final Class<?>... classesToBeBound) { // final Unmarshaller unmarshaller = new UnmarshallerBuilder().addClassesToBeBound(classesToBeBound).build(); // return unmarshal(unmarshaller, xmlData); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/CDataXmlAdapter.java // public final class CDataXmlAdapter extends XmlAdapter<String, String> { // // @Override // public final String marshal(final String value) throws Exception { // if (value == null) { // return null; // } // return "<![CDATA[" + value + "]]>"; // } // // @Override // public final String unmarshal(final String value) throws Exception { // if (value == null) { // return null; // } // return value; // } // // } // // Path: src/main/java/org/fuin/utils4j/jaxb/CDataXmlStreamWriter.java // public final class CDataXmlStreamWriter extends XMLStreamWriterAdapter { // // /** // * Constructor with delegate. // * // * @param delegate // * All method calls are delegated to this writer. // */ // public CDataXmlStreamWriter(final XMLStreamWriter delegate) { // super(delegate); // } // // @Override // public final void writeCharacters(final String text) throws XMLStreamException { // writeText(text); // } // // @Override // public final void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException { // writeText(new String(text, start, len)); // } // // private void writeText(final String text) throws XMLStreamException { // if (text.startsWith("<![CDATA[") && text.endsWith("]]>")) { // final String str = text.substring(9, text.length() - 3); // super.writeCData(str); // } else { // super.writeCharacters(text); // } // } // // } // // Path: src/test/java/org/fuin/utils4j/jaxb/MyClassWithCData.java // @XmlRootElement(name = "my-class-with-cdata") // public final class MyClassWithCData { // // @XmlValue // @XmlJavaTypeAdapter(CDataXmlAdapter.class) // private String content; // // /** // * Default constructor for JAXB. // */ // protected MyClassWithCData() { // super(); // } // // /** // * Constructor with mandatory data. // * // * @param content // * CDATA content. // */ // public MyClassWithCData(final String content) { // super(); // this.content = content; // } // // /** // * Returns the content. // * // * @return Content. // */ // public String getContent() { // return content; // } // // } // Path: src/test/java/org/fuin/utils4j/examples/CDataJaxbExample.java import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; import java.io.StringWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import jakarta.xml.bind.JAXBContext; import org.fuin.utils4j.jaxb.CDataXmlAdapter; import org.fuin.utils4j.jaxb.CDataXmlStreamWriter; import org.fuin.utils4j.jaxb.MyClassWithCData; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.examples; /** * Short example for using the {@link CDataXmlStreamWriter} together with the {@link CDataXmlAdapter}. */ // CHECKSTYLE:OFF public class CDataJaxbExample { /** * Executes the example. * * @param args * Not used. */ public static void main(String[] args) throws Exception { // Create writers final StringWriter writer = new StringWriter(); final XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer); final CDataXmlStreamWriter cdataWriter = new CDataXmlStreamWriter(xmlWriter); // Create JAXB context with example class
final JAXBContext ctx = JAXBContext.newInstance(MyClassWithCData.class);
fuinorg/utils4j
src/test/java/org/fuin/utils4j/examples/CDataJaxbExample.java
// Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> String marshal(final T data, final Class<?>... classesToBeBound) { // return marshal(data, null, classesToBeBound); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> T unmarshal(final String xmlData, final Class<?>... classesToBeBound) { // final Unmarshaller unmarshaller = new UnmarshallerBuilder().addClassesToBeBound(classesToBeBound).build(); // return unmarshal(unmarshaller, xmlData); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/CDataXmlAdapter.java // public final class CDataXmlAdapter extends XmlAdapter<String, String> { // // @Override // public final String marshal(final String value) throws Exception { // if (value == null) { // return null; // } // return "<![CDATA[" + value + "]]>"; // } // // @Override // public final String unmarshal(final String value) throws Exception { // if (value == null) { // return null; // } // return value; // } // // } // // Path: src/main/java/org/fuin/utils4j/jaxb/CDataXmlStreamWriter.java // public final class CDataXmlStreamWriter extends XMLStreamWriterAdapter { // // /** // * Constructor with delegate. // * // * @param delegate // * All method calls are delegated to this writer. // */ // public CDataXmlStreamWriter(final XMLStreamWriter delegate) { // super(delegate); // } // // @Override // public final void writeCharacters(final String text) throws XMLStreamException { // writeText(text); // } // // @Override // public final void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException { // writeText(new String(text, start, len)); // } // // private void writeText(final String text) throws XMLStreamException { // if (text.startsWith("<![CDATA[") && text.endsWith("]]>")) { // final String str = text.substring(9, text.length() - 3); // super.writeCData(str); // } else { // super.writeCharacters(text); // } // } // // } // // Path: src/test/java/org/fuin/utils4j/jaxb/MyClassWithCData.java // @XmlRootElement(name = "my-class-with-cdata") // public final class MyClassWithCData { // // @XmlValue // @XmlJavaTypeAdapter(CDataXmlAdapter.class) // private String content; // // /** // * Default constructor for JAXB. // */ // protected MyClassWithCData() { // super(); // } // // /** // * Constructor with mandatory data. // * // * @param content // * CDATA content. // */ // public MyClassWithCData(final String content) { // super(); // this.content = content; // } // // /** // * Returns the content. // * // * @return Content. // */ // public String getContent() { // return content; // } // // }
import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; import java.io.StringWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import jakarta.xml.bind.JAXBContext; import org.fuin.utils4j.jaxb.CDataXmlAdapter; import org.fuin.utils4j.jaxb.CDataXmlStreamWriter; import org.fuin.utils4j.jaxb.MyClassWithCData;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.examples; /** * Short example for using the {@link CDataXmlStreamWriter} together with the {@link CDataXmlAdapter}. */ // CHECKSTYLE:OFF public class CDataJaxbExample { /** * Executes the example. * * @param args * Not used. */ public static void main(String[] args) throws Exception { // Create writers final StringWriter writer = new StringWriter(); final XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer); final CDataXmlStreamWriter cdataWriter = new CDataXmlStreamWriter(xmlWriter); // Create JAXB context with example class final JAXBContext ctx = JAXBContext.newInstance(MyClassWithCData.class); final MyClassWithCData testee = new MyClassWithCData("<whatever this=\"is\"/>"); // Convert instance to XML
// Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> String marshal(final T data, final Class<?>... classesToBeBound) { // return marshal(data, null, classesToBeBound); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> T unmarshal(final String xmlData, final Class<?>... classesToBeBound) { // final Unmarshaller unmarshaller = new UnmarshallerBuilder().addClassesToBeBound(classesToBeBound).build(); // return unmarshal(unmarshaller, xmlData); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/CDataXmlAdapter.java // public final class CDataXmlAdapter extends XmlAdapter<String, String> { // // @Override // public final String marshal(final String value) throws Exception { // if (value == null) { // return null; // } // return "<![CDATA[" + value + "]]>"; // } // // @Override // public final String unmarshal(final String value) throws Exception { // if (value == null) { // return null; // } // return value; // } // // } // // Path: src/main/java/org/fuin/utils4j/jaxb/CDataXmlStreamWriter.java // public final class CDataXmlStreamWriter extends XMLStreamWriterAdapter { // // /** // * Constructor with delegate. // * // * @param delegate // * All method calls are delegated to this writer. // */ // public CDataXmlStreamWriter(final XMLStreamWriter delegate) { // super(delegate); // } // // @Override // public final void writeCharacters(final String text) throws XMLStreamException { // writeText(text); // } // // @Override // public final void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException { // writeText(new String(text, start, len)); // } // // private void writeText(final String text) throws XMLStreamException { // if (text.startsWith("<![CDATA[") && text.endsWith("]]>")) { // final String str = text.substring(9, text.length() - 3); // super.writeCData(str); // } else { // super.writeCharacters(text); // } // } // // } // // Path: src/test/java/org/fuin/utils4j/jaxb/MyClassWithCData.java // @XmlRootElement(name = "my-class-with-cdata") // public final class MyClassWithCData { // // @XmlValue // @XmlJavaTypeAdapter(CDataXmlAdapter.class) // private String content; // // /** // * Default constructor for JAXB. // */ // protected MyClassWithCData() { // super(); // } // // /** // * Constructor with mandatory data. // * // * @param content // * CDATA content. // */ // public MyClassWithCData(final String content) { // super(); // this.content = content; // } // // /** // * Returns the content. // * // * @return Content. // */ // public String getContent() { // return content; // } // // } // Path: src/test/java/org/fuin/utils4j/examples/CDataJaxbExample.java import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; import java.io.StringWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import jakarta.xml.bind.JAXBContext; import org.fuin.utils4j.jaxb.CDataXmlAdapter; import org.fuin.utils4j.jaxb.CDataXmlStreamWriter; import org.fuin.utils4j.jaxb.MyClassWithCData; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.examples; /** * Short example for using the {@link CDataXmlStreamWriter} together with the {@link CDataXmlAdapter}. */ // CHECKSTYLE:OFF public class CDataJaxbExample { /** * Executes the example. * * @param args * Not used. */ public static void main(String[] args) throws Exception { // Create writers final StringWriter writer = new StringWriter(); final XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer); final CDataXmlStreamWriter cdataWriter = new CDataXmlStreamWriter(xmlWriter); // Create JAXB context with example class final JAXBContext ctx = JAXBContext.newInstance(MyClassWithCData.class); final MyClassWithCData testee = new MyClassWithCData("<whatever this=\"is\"/>"); // Convert instance to XML
marshal(ctx, testee, null, cdataWriter);
fuinorg/utils4j
src/test/java/org/fuin/utils4j/examples/CDataJaxbExample.java
// Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> String marshal(final T data, final Class<?>... classesToBeBound) { // return marshal(data, null, classesToBeBound); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> T unmarshal(final String xmlData, final Class<?>... classesToBeBound) { // final Unmarshaller unmarshaller = new UnmarshallerBuilder().addClassesToBeBound(classesToBeBound).build(); // return unmarshal(unmarshaller, xmlData); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/CDataXmlAdapter.java // public final class CDataXmlAdapter extends XmlAdapter<String, String> { // // @Override // public final String marshal(final String value) throws Exception { // if (value == null) { // return null; // } // return "<![CDATA[" + value + "]]>"; // } // // @Override // public final String unmarshal(final String value) throws Exception { // if (value == null) { // return null; // } // return value; // } // // } // // Path: src/main/java/org/fuin/utils4j/jaxb/CDataXmlStreamWriter.java // public final class CDataXmlStreamWriter extends XMLStreamWriterAdapter { // // /** // * Constructor with delegate. // * // * @param delegate // * All method calls are delegated to this writer. // */ // public CDataXmlStreamWriter(final XMLStreamWriter delegate) { // super(delegate); // } // // @Override // public final void writeCharacters(final String text) throws XMLStreamException { // writeText(text); // } // // @Override // public final void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException { // writeText(new String(text, start, len)); // } // // private void writeText(final String text) throws XMLStreamException { // if (text.startsWith("<![CDATA[") && text.endsWith("]]>")) { // final String str = text.substring(9, text.length() - 3); // super.writeCData(str); // } else { // super.writeCharacters(text); // } // } // // } // // Path: src/test/java/org/fuin/utils4j/jaxb/MyClassWithCData.java // @XmlRootElement(name = "my-class-with-cdata") // public final class MyClassWithCData { // // @XmlValue // @XmlJavaTypeAdapter(CDataXmlAdapter.class) // private String content; // // /** // * Default constructor for JAXB. // */ // protected MyClassWithCData() { // super(); // } // // /** // * Constructor with mandatory data. // * // * @param content // * CDATA content. // */ // public MyClassWithCData(final String content) { // super(); // this.content = content; // } // // /** // * Returns the content. // * // * @return Content. // */ // public String getContent() { // return content; // } // // }
import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; import java.io.StringWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import jakarta.xml.bind.JAXBContext; import org.fuin.utils4j.jaxb.CDataXmlAdapter; import org.fuin.utils4j.jaxb.CDataXmlStreamWriter; import org.fuin.utils4j.jaxb.MyClassWithCData;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.examples; /** * Short example for using the {@link CDataXmlStreamWriter} together with the {@link CDataXmlAdapter}. */ // CHECKSTYLE:OFF public class CDataJaxbExample { /** * Executes the example. * * @param args * Not used. */ public static void main(String[] args) throws Exception { // Create writers final StringWriter writer = new StringWriter(); final XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer); final CDataXmlStreamWriter cdataWriter = new CDataXmlStreamWriter(xmlWriter); // Create JAXB context with example class final JAXBContext ctx = JAXBContext.newInstance(MyClassWithCData.class); final MyClassWithCData testee = new MyClassWithCData("<whatever this=\"is\"/>"); // Convert instance to XML marshal(ctx, testee, null, cdataWriter); final String xml = writer.toString(); // Prints out the result System.out.println(xml); // <?xml version="1.0" ?><my-class-with-cdata><![CDATA[<whatever // this="is"/>]]></my-class-with-cdata> // Convert it back to object
// Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> String marshal(final T data, final Class<?>... classesToBeBound) { // return marshal(data, null, classesToBeBound); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> T unmarshal(final String xmlData, final Class<?>... classesToBeBound) { // final Unmarshaller unmarshaller = new UnmarshallerBuilder().addClassesToBeBound(classesToBeBound).build(); // return unmarshal(unmarshaller, xmlData); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/CDataXmlAdapter.java // public final class CDataXmlAdapter extends XmlAdapter<String, String> { // // @Override // public final String marshal(final String value) throws Exception { // if (value == null) { // return null; // } // return "<![CDATA[" + value + "]]>"; // } // // @Override // public final String unmarshal(final String value) throws Exception { // if (value == null) { // return null; // } // return value; // } // // } // // Path: src/main/java/org/fuin/utils4j/jaxb/CDataXmlStreamWriter.java // public final class CDataXmlStreamWriter extends XMLStreamWriterAdapter { // // /** // * Constructor with delegate. // * // * @param delegate // * All method calls are delegated to this writer. // */ // public CDataXmlStreamWriter(final XMLStreamWriter delegate) { // super(delegate); // } // // @Override // public final void writeCharacters(final String text) throws XMLStreamException { // writeText(text); // } // // @Override // public final void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException { // writeText(new String(text, start, len)); // } // // private void writeText(final String text) throws XMLStreamException { // if (text.startsWith("<![CDATA[") && text.endsWith("]]>")) { // final String str = text.substring(9, text.length() - 3); // super.writeCData(str); // } else { // super.writeCharacters(text); // } // } // // } // // Path: src/test/java/org/fuin/utils4j/jaxb/MyClassWithCData.java // @XmlRootElement(name = "my-class-with-cdata") // public final class MyClassWithCData { // // @XmlValue // @XmlJavaTypeAdapter(CDataXmlAdapter.class) // private String content; // // /** // * Default constructor for JAXB. // */ // protected MyClassWithCData() { // super(); // } // // /** // * Constructor with mandatory data. // * // * @param content // * CDATA content. // */ // public MyClassWithCData(final String content) { // super(); // this.content = content; // } // // /** // * Returns the content. // * // * @return Content. // */ // public String getContent() { // return content; // } // // } // Path: src/test/java/org/fuin/utils4j/examples/CDataJaxbExample.java import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; import java.io.StringWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import jakarta.xml.bind.JAXBContext; import org.fuin.utils4j.jaxb.CDataXmlAdapter; import org.fuin.utils4j.jaxb.CDataXmlStreamWriter; import org.fuin.utils4j.jaxb.MyClassWithCData; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.examples; /** * Short example for using the {@link CDataXmlStreamWriter} together with the {@link CDataXmlAdapter}. */ // CHECKSTYLE:OFF public class CDataJaxbExample { /** * Executes the example. * * @param args * Not used. */ public static void main(String[] args) throws Exception { // Create writers final StringWriter writer = new StringWriter(); final XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer); final CDataXmlStreamWriter cdataWriter = new CDataXmlStreamWriter(xmlWriter); // Create JAXB context with example class final JAXBContext ctx = JAXBContext.newInstance(MyClassWithCData.class); final MyClassWithCData testee = new MyClassWithCData("<whatever this=\"is\"/>"); // Convert instance to XML marshal(ctx, testee, null, cdataWriter); final String xml = writer.toString(); // Prints out the result System.out.println(xml); // <?xml version="1.0" ?><my-class-with-cdata><![CDATA[<whatever // this="is"/>]]></my-class-with-cdata> // Convert it back to object
final MyClassWithCData copy = unmarshal(xml, MyClassWithCData.class);
fuinorg/utils4j
src/main/java/org/fuin/utils4j/filter/IntegerPropertyFilter.java
// Path: src/main/java/org/fuin/utils4j/filter/ComparableFilter.java // public static final class Operator { // // /** Less than. */ // public static final Operator LT = new Operator("LT", "<"); // // /** Less than or equal. */ // public static final Operator LTE = new Operator("LTE", "<="); // // /** Equal. */ // public static final Operator EQ = new Operator("EQ", "="); // // /** Greater than. */ // public static final Operator GT = new Operator("GT", ">"); // // /** Greater than or equal. */ // public static final Operator GTE = new Operator("GTE", ">="); // // /** List of all known instances. */ // public static final List<Operator> INSTANCES = asList(LT, LTE, EQ, GT, GTE); // NOSONAR // // private final String id; // // private final String sign; // // private Operator(final String id, final String sign) { // Utils4J.checkNotNull("id", id); // Utils4J.checkNotNull("sign", sign); // this.id = id; // this.sign = sign; // } // // /** // * Returns the unique name of the operator. // * // * @return ID. // */ // public final String getId() { // return id; // } // // /** // * Returns the symbol for the operator. // * // * @return Sign. // */ // public final String getSign() { // return sign; // } // // /** // * Determines if a given id is valid. // * // * @param id // * Name to check - Cannot be <code>null</code>. // * // * @return If the name is valid <code>true</code> else <code>false</code>. // */ // public static boolean isValid(final String id) { // Utils4J.checkNotNull("id", id); // for (final Operator op : INSTANCES) { // if (op.getId().equals(id)) { // return true; // } // } // return false; // } // // /** // * Returns an instance for a given id. // * // * @param id // * Name to return an instance for - Cannot be <code>null</code> and must be a valid name. // * // * @return Instance. // */ // public static Operator getInstance(final String id) { // Utils4J.checkNotNull("id", id); // for (final Operator op : INSTANCES) { // if (op.getId().equals(id)) { // return op; // } // } // throw new IllegalArgumentException("The id '" + id + "' is unknown!"); // } // // @Override // public final String toString() { // return sign; // } // // private static List<Operator> asList(final Operator... operators) { // final List<Operator> list = new ArrayList<>(operators.length); // for (final Operator operator : operators) { // list.add(operator); // } // return Collections.unmodifiableList(list); // } // // }
import org.fuin.utils4j.filter.ComparableFilter.Operator;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.filter; /** * Defines a filter on a Integer property. */ public class IntegerPropertyFilter extends ComparablePropertyFilter { /** * Constructor. * * @param newPropertyName * Name of the property. * @param newOperator * Operator to use. * @param constValue * Value to compare with. */ public IntegerPropertyFilter(final String newPropertyName, final String newOperator, final Integer constValue) { super(newPropertyName, new IntegerFilter(newOperator, constValue)); } /** * Constructor. * * @param newPropertyName * Name of the property. * @param newOperator * Operator to use. * @param constValue * Value to compare with. */
// Path: src/main/java/org/fuin/utils4j/filter/ComparableFilter.java // public static final class Operator { // // /** Less than. */ // public static final Operator LT = new Operator("LT", "<"); // // /** Less than or equal. */ // public static final Operator LTE = new Operator("LTE", "<="); // // /** Equal. */ // public static final Operator EQ = new Operator("EQ", "="); // // /** Greater than. */ // public static final Operator GT = new Operator("GT", ">"); // // /** Greater than or equal. */ // public static final Operator GTE = new Operator("GTE", ">="); // // /** List of all known instances. */ // public static final List<Operator> INSTANCES = asList(LT, LTE, EQ, GT, GTE); // NOSONAR // // private final String id; // // private final String sign; // // private Operator(final String id, final String sign) { // Utils4J.checkNotNull("id", id); // Utils4J.checkNotNull("sign", sign); // this.id = id; // this.sign = sign; // } // // /** // * Returns the unique name of the operator. // * // * @return ID. // */ // public final String getId() { // return id; // } // // /** // * Returns the symbol for the operator. // * // * @return Sign. // */ // public final String getSign() { // return sign; // } // // /** // * Determines if a given id is valid. // * // * @param id // * Name to check - Cannot be <code>null</code>. // * // * @return If the name is valid <code>true</code> else <code>false</code>. // */ // public static boolean isValid(final String id) { // Utils4J.checkNotNull("id", id); // for (final Operator op : INSTANCES) { // if (op.getId().equals(id)) { // return true; // } // } // return false; // } // // /** // * Returns an instance for a given id. // * // * @param id // * Name to return an instance for - Cannot be <code>null</code> and must be a valid name. // * // * @return Instance. // */ // public static Operator getInstance(final String id) { // Utils4J.checkNotNull("id", id); // for (final Operator op : INSTANCES) { // if (op.getId().equals(id)) { // return op; // } // } // throw new IllegalArgumentException("The id '" + id + "' is unknown!"); // } // // @Override // public final String toString() { // return sign; // } // // private static List<Operator> asList(final Operator... operators) { // final List<Operator> list = new ArrayList<>(operators.length); // for (final Operator operator : operators) { // list.add(operator); // } // return Collections.unmodifiableList(list); // } // // } // Path: src/main/java/org/fuin/utils4j/filter/IntegerPropertyFilter.java import org.fuin.utils4j.filter.ComparableFilter.Operator; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.filter; /** * Defines a filter on a Integer property. */ public class IntegerPropertyFilter extends ComparablePropertyFilter { /** * Constructor. * * @param newPropertyName * Name of the property. * @param newOperator * Operator to use. * @param constValue * Value to compare with. */ public IntegerPropertyFilter(final String newPropertyName, final String newOperator, final Integer constValue) { super(newPropertyName, new IntegerFilter(newOperator, constValue)); } /** * Constructor. * * @param newPropertyName * Name of the property. * @param newOperator * Operator to use. * @param constValue * Value to compare with. */
public IntegerPropertyFilter(final String newPropertyName, final Operator newOperator, final Integer constValue) {
fuinorg/utils4j
src/test/java/org/fuin/utils4j/examples/WaitHelperExample.java
// Path: src/main/java/org/fuin/utils4j/WaitHelper.java // @Deprecated // public final class WaitHelper { // // private final long sleepMillis; // // private final long maxTries; // // /** // * Constructor with mandatory data. // * // * @param sleepMillis // * Number of milliseconds to sleep between tries. // * @param maxTries // * Number of retries before waiting terminates. // */ // public WaitHelper(final long sleepMillis, final long maxTries) { // super(); // this.sleepMillis = sleepMillis; // this.maxTries = maxTries; // } // // /** // * Wait until no more expected exception is thrown or the number of wait cycles has been exceeded. // * // * @param runnable // * Code to run. // * @param expectedExceptions // * List of expected exceptions. // */ // public void waitUntilNoMoreException(final Runnable runnable, final List<Class<? extends Exception>> expectedExceptions) { // // final List<RuntimeException> actualExceptions = new ArrayList<>(); // int tries = 0; // while (tries < maxTries) { // try { // runnable.run(); // return; // } catch (final RuntimeException ex) { // if (!Utils4J.expectedException(ex, expectedExceptions) && !Utils4J.expectedCause(ex, expectedExceptions)) { // throw ex; // } // actualExceptions.add(ex); // tries++; // Utils4J.sleep(sleepMillis); // } // } // throw new IllegalStateException("Waited too long for execution without exception. Expected exceptions: " + expectedExceptions // + ", Actual exceptions: " + actualExceptions); // // } // // /** // * Wait until one of the expected values was returned or the number of wait cycles has been exceeded. Throws // * {@link IllegalStateException} if the timeout is reached. // * // * @param function // * Function to read the value from. // * @param expectedValues // * List of values that are acceptable. // * // * @return Result. // * // * @throws Exception // * The function raised an exception. // * // * @param <T> // * Expected return type that must be an object that support equals/hasCode that is not the {@link Object}'s default method. // */ // public <T> T waitUntilResult(final Callable<T> function, final List<T> expectedValues) throws Exception { // // final List<T> actualResults = new ArrayList<>(); // int tries = 0; // while (tries < maxTries) { // final T result = function.call(); // if (expectedValues.contains(result)) { // return result; // } // actualResults.add(result); // tries++; // Utils4J.sleep(sleepMillis); // } // throw new IllegalStateException( // "Waited too long for one of the expected results: " + expectedValues + ", Actual results: " + actualResults); // // } // // }
import java.util.Arrays; import java.util.UUID; import org.fuin.utils4j.WaitHelper;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.examples; /** * Short example for using the {@link WaitHelper}. */ // CHECKSTYLE:OFF public class WaitHelperExample { /** * Example function that loads a customer name, but always throws an exception. * * @param id * Unique ID of the customer to load the name for. * * @return Customer name. * * @throws CustomerNotFoundException * No customer with the given ID was found. */ private static String loadCustomerName(final UUID id) throws CustomerNotFoundException { throw new CustomerNotFoundException(); } /** * Example function that loads a customer name. * * @param id * Unique ID of the customer to load the name for. * * @return Customer name. * * @throws CustomerNotFoundException * No customer with the given ID was found. */ private static String loadCustomerName2(final UUID id) throws CustomerNotFoundException { return "Harry Osborn, Inc"; } /** * Executes the example. * * @param args * Not used. */ public static void main(String[] args) throws Exception { // Customer ID to load a name for final UUID customerId = UUID.randomUUID(); // Wait one second between tries final long sleepMillis = 1000; // Try 5 times (wait at max 5 seconds) final long maxTries = 5; // Create helper class
// Path: src/main/java/org/fuin/utils4j/WaitHelper.java // @Deprecated // public final class WaitHelper { // // private final long sleepMillis; // // private final long maxTries; // // /** // * Constructor with mandatory data. // * // * @param sleepMillis // * Number of milliseconds to sleep between tries. // * @param maxTries // * Number of retries before waiting terminates. // */ // public WaitHelper(final long sleepMillis, final long maxTries) { // super(); // this.sleepMillis = sleepMillis; // this.maxTries = maxTries; // } // // /** // * Wait until no more expected exception is thrown or the number of wait cycles has been exceeded. // * // * @param runnable // * Code to run. // * @param expectedExceptions // * List of expected exceptions. // */ // public void waitUntilNoMoreException(final Runnable runnable, final List<Class<? extends Exception>> expectedExceptions) { // // final List<RuntimeException> actualExceptions = new ArrayList<>(); // int tries = 0; // while (tries < maxTries) { // try { // runnable.run(); // return; // } catch (final RuntimeException ex) { // if (!Utils4J.expectedException(ex, expectedExceptions) && !Utils4J.expectedCause(ex, expectedExceptions)) { // throw ex; // } // actualExceptions.add(ex); // tries++; // Utils4J.sleep(sleepMillis); // } // } // throw new IllegalStateException("Waited too long for execution without exception. Expected exceptions: " + expectedExceptions // + ", Actual exceptions: " + actualExceptions); // // } // // /** // * Wait until one of the expected values was returned or the number of wait cycles has been exceeded. Throws // * {@link IllegalStateException} if the timeout is reached. // * // * @param function // * Function to read the value from. // * @param expectedValues // * List of values that are acceptable. // * // * @return Result. // * // * @throws Exception // * The function raised an exception. // * // * @param <T> // * Expected return type that must be an object that support equals/hasCode that is not the {@link Object}'s default method. // */ // public <T> T waitUntilResult(final Callable<T> function, final List<T> expectedValues) throws Exception { // // final List<T> actualResults = new ArrayList<>(); // int tries = 0; // while (tries < maxTries) { // final T result = function.call(); // if (expectedValues.contains(result)) { // return result; // } // actualResults.add(result); // tries++; // Utils4J.sleep(sleepMillis); // } // throw new IllegalStateException( // "Waited too long for one of the expected results: " + expectedValues + ", Actual results: " + actualResults); // // } // // } // Path: src/test/java/org/fuin/utils4j/examples/WaitHelperExample.java import java.util.Arrays; import java.util.UUID; import org.fuin.utils4j.WaitHelper; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.examples; /** * Short example for using the {@link WaitHelper}. */ // CHECKSTYLE:OFF public class WaitHelperExample { /** * Example function that loads a customer name, but always throws an exception. * * @param id * Unique ID of the customer to load the name for. * * @return Customer name. * * @throws CustomerNotFoundException * No customer with the given ID was found. */ private static String loadCustomerName(final UUID id) throws CustomerNotFoundException { throw new CustomerNotFoundException(); } /** * Example function that loads a customer name. * * @param id * Unique ID of the customer to load the name for. * * @return Customer name. * * @throws CustomerNotFoundException * No customer with the given ID was found. */ private static String loadCustomerName2(final UUID id) throws CustomerNotFoundException { return "Harry Osborn, Inc"; } /** * Executes the example. * * @param args * Not used. */ public static void main(String[] args) throws Exception { // Customer ID to load a name for final UUID customerId = UUID.randomUUID(); // Wait one second between tries final long sleepMillis = 1000; // Try 5 times (wait at max 5 seconds) final long maxTries = 5; // Create helper class
final WaitHelper waitHelper = new WaitHelper(sleepMillis, maxTries);
fuinorg/utils4j
src/test/java/org/fuin/utils4j/PropertiesFileTest.java
// Path: src/main/java/org/fuin/utils4j/MergeException.java // public static final class Problem implements Serializable { // // private static final long serialVersionUID = 1L; // // /** Message describing the problem. */ // private final String text; // // /** Property from memory. */ // private final Property prop; // // /** Property from file. */ // private final Property fileProp; // // /** // * Constructor with message and properties. // * // * @param text // * Message describing the problem. // * @param prop // * Property from memory. // * @param fileProp // * Property from file. // */ // public Problem(final String text, final Property prop, final Property fileProp) { // super(); // // Utils4J.checkNotNull("text", text); // this.text = text; // // Utils4J.checkNotNull("prop", prop); // this.prop = prop; // // Utils4J.checkNotNull("fileProp", fileProp); // this.fileProp = fileProp; // // } // // /** // * Returns the message describing the problem. // * // * @return Detailed message. // */ // public final String getText() { // return text; // } // // /** // * Returns the property from memory. // * // * @return Property. // */ // public final Property getProp() { // return prop; // } // // /** // * Returns the property from disk. // * // * @return Property. // */ // public final Property getFileProp() { // return fileProp; // } // // @Override // public final String toString() { // return text + " - Property: {" + prop + "}, File Property: {" + fileProp + "}"; // } // // }
import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; import org.fuin.utils4j.MergeException.Problem; import org.junit.After;
// Check result TestHelper.assertPropertiesEqual(new File(dir, "PropertiesFileTestE.properties"), testFile); } @Test public final void testMergeError() throws IOException, MergeException, LockingFailedException { // Load first one final PropertiesFile propFile1 = new PropertiesFile(testFile); propFile1.load(); // Load second one final PropertiesFile propFile2 = new PropertiesFile(testFile); propFile2.load(); // Modify the same property concurrently propFile1.put("A", "a"); propFile2.put("A", "x"); // Save first one propFile1.save("Test", true); // Save second one try { propFile2.save("Test", true); System.out.println("------"); fail("Expected " + MergeException.class.getName() + " [" + testFile + "]"); } catch (final MergeException ex) {
// Path: src/main/java/org/fuin/utils4j/MergeException.java // public static final class Problem implements Serializable { // // private static final long serialVersionUID = 1L; // // /** Message describing the problem. */ // private final String text; // // /** Property from memory. */ // private final Property prop; // // /** Property from file. */ // private final Property fileProp; // // /** // * Constructor with message and properties. // * // * @param text // * Message describing the problem. // * @param prop // * Property from memory. // * @param fileProp // * Property from file. // */ // public Problem(final String text, final Property prop, final Property fileProp) { // super(); // // Utils4J.checkNotNull("text", text); // this.text = text; // // Utils4J.checkNotNull("prop", prop); // this.prop = prop; // // Utils4J.checkNotNull("fileProp", fileProp); // this.fileProp = fileProp; // // } // // /** // * Returns the message describing the problem. // * // * @return Detailed message. // */ // public final String getText() { // return text; // } // // /** // * Returns the property from memory. // * // * @return Property. // */ // public final Property getProp() { // return prop; // } // // /** // * Returns the property from disk. // * // * @return Property. // */ // public final Property getFileProp() { // return fileProp; // } // // @Override // public final String toString() { // return text + " - Property: {" + prop + "}, File Property: {" + fileProp + "}"; // } // // } // Path: src/test/java/org/fuin/utils4j/PropertiesFileTest.java import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; import org.fuin.utils4j.MergeException.Problem; import org.junit.After; // Check result TestHelper.assertPropertiesEqual(new File(dir, "PropertiesFileTestE.properties"), testFile); } @Test public final void testMergeError() throws IOException, MergeException, LockingFailedException { // Load first one final PropertiesFile propFile1 = new PropertiesFile(testFile); propFile1.load(); // Load second one final PropertiesFile propFile2 = new PropertiesFile(testFile); propFile2.load(); // Modify the same property concurrently propFile1.put("A", "a"); propFile2.put("A", "x"); // Save first one propFile1.save("Test", true); // Save second one try { propFile2.save("Test", true); System.out.println("------"); fail("Expected " + MergeException.class.getName() + " [" + testFile + "]"); } catch (final MergeException ex) {
final Problem[] problems = ex.getProblems();
fuinorg/utils4j
src/test/java/org/fuin/utils4j/jaxb/CDataJaxbTest.java
// Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> String marshal(final T data, final Class<?>... classesToBeBound) { // return marshal(data, null, classesToBeBound); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> T unmarshal(final String xmlData, final Class<?>... classesToBeBound) { // final Unmarshaller unmarshaller = new UnmarshallerBuilder().addClassesToBeBound(classesToBeBound).build(); // return unmarshal(unmarshaller, xmlData); // }
import static org.assertj.core.api.Assertions.assertThat; import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; import java.io.StringWriter; import javax.xml.stream.XMLOutputFactory; import jakarta.xml.bind.JAXBContext; import org.junit.Test;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.jaxb; // CHECKSTYLE:OFF public class CDataJaxbTest { private static final String DATA = "<whatever this=\"is\"/>"; @Test public final void testMarshal() throws Exception { final StringWriter writer = new StringWriter(); try (final CDataXmlStreamWriter sw = new CDataXmlStreamWriter(XMLOutputFactory.newInstance().createXMLStreamWriter(writer));) { // PREPARE final JAXBContext ctx = JAXBContext.newInstance(MyClassWithCData.class); final MyClassWithCData testee = new MyClassWithCData(DATA); // TEST
// Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> String marshal(final T data, final Class<?>... classesToBeBound) { // return marshal(data, null, classesToBeBound); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> T unmarshal(final String xmlData, final Class<?>... classesToBeBound) { // final Unmarshaller unmarshaller = new UnmarshallerBuilder().addClassesToBeBound(classesToBeBound).build(); // return unmarshal(unmarshaller, xmlData); // } // Path: src/test/java/org/fuin/utils4j/jaxb/CDataJaxbTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; import java.io.StringWriter; import javax.xml.stream.XMLOutputFactory; import jakarta.xml.bind.JAXBContext; import org.junit.Test; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.jaxb; // CHECKSTYLE:OFF public class CDataJaxbTest { private static final String DATA = "<whatever this=\"is\"/>"; @Test public final void testMarshal() throws Exception { final StringWriter writer = new StringWriter(); try (final CDataXmlStreamWriter sw = new CDataXmlStreamWriter(XMLOutputFactory.newInstance().createXMLStreamWriter(writer));) { // PREPARE final JAXBContext ctx = JAXBContext.newInstance(MyClassWithCData.class); final MyClassWithCData testee = new MyClassWithCData(DATA); // TEST
marshal(ctx, testee, null, sw);
fuinorg/utils4j
src/test/java/org/fuin/utils4j/jaxb/CDataJaxbTest.java
// Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> String marshal(final T data, final Class<?>... classesToBeBound) { // return marshal(data, null, classesToBeBound); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> T unmarshal(final String xmlData, final Class<?>... classesToBeBound) { // final Unmarshaller unmarshaller = new UnmarshallerBuilder().addClassesToBeBound(classesToBeBound).build(); // return unmarshal(unmarshaller, xmlData); // }
import static org.assertj.core.api.Assertions.assertThat; import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; import java.io.StringWriter; import javax.xml.stream.XMLOutputFactory; import jakarta.xml.bind.JAXBContext; import org.junit.Test;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.jaxb; // CHECKSTYLE:OFF public class CDataJaxbTest { private static final String DATA = "<whatever this=\"is\"/>"; @Test public final void testMarshal() throws Exception { final StringWriter writer = new StringWriter(); try (final CDataXmlStreamWriter sw = new CDataXmlStreamWriter(XMLOutputFactory.newInstance().createXMLStreamWriter(writer));) { // PREPARE final JAXBContext ctx = JAXBContext.newInstance(MyClassWithCData.class); final MyClassWithCData testee = new MyClassWithCData(DATA); // TEST marshal(ctx, testee, null, sw); final String result = writer.toString(); // VERIFY assertThat(result) .isEqualTo("<?xml version=\"1.0\" ?><my-class-with-cdata>" + "<![CDATA[" + DATA + "]]>" + "</my-class-with-cdata>"); } } @Test public final void testUnmarshal() throws Exception { // TEST
// Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> String marshal(final T data, final Class<?>... classesToBeBound) { // return marshal(data, null, classesToBeBound); // } // // Path: src/main/java/org/fuin/utils4j/jaxb/JaxbUtils.java // public static <T> T unmarshal(final String xmlData, final Class<?>... classesToBeBound) { // final Unmarshaller unmarshaller = new UnmarshallerBuilder().addClassesToBeBound(classesToBeBound).build(); // return unmarshal(unmarshaller, xmlData); // } // Path: src/test/java/org/fuin/utils4j/jaxb/CDataJaxbTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.fuin.utils4j.jaxb.JaxbUtils.marshal; import static org.fuin.utils4j.jaxb.JaxbUtils.unmarshal; import java.io.StringWriter; import javax.xml.stream.XMLOutputFactory; import jakarta.xml.bind.JAXBContext; import org.junit.Test; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.jaxb; // CHECKSTYLE:OFF public class CDataJaxbTest { private static final String DATA = "<whatever this=\"is\"/>"; @Test public final void testMarshal() throws Exception { final StringWriter writer = new StringWriter(); try (final CDataXmlStreamWriter sw = new CDataXmlStreamWriter(XMLOutputFactory.newInstance().createXMLStreamWriter(writer));) { // PREPARE final JAXBContext ctx = JAXBContext.newInstance(MyClassWithCData.class); final MyClassWithCData testee = new MyClassWithCData(DATA); // TEST marshal(ctx, testee, null, sw); final String result = writer.toString(); // VERIFY assertThat(result) .isEqualTo("<?xml version=\"1.0\" ?><my-class-with-cdata>" + "<![CDATA[" + DATA + "]]>" + "</my-class-with-cdata>"); } } @Test public final void testUnmarshal() throws Exception { // TEST
final MyClassWithCData testee = unmarshal("<my-class-with-cdata>" + "<![CDATA[" + DATA + "]]>" + "</my-class-with-cdata>",
fuinorg/utils4j
src/main/java/org/fuin/utils4j/PropertiesUtils.java
// Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static void checkNotNull(final String name, final Object value) { // if (value == null) { // throw new IllegalNullArgumentException(name); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static void checkValidFile(final File file) { // checkNotNull("file", file); // if (!file.exists()) { // throw new IllegalArgumentException("The file '" + file + "' does not exist!"); // } // if (!file.isFile()) { // throw new IllegalArgumentException("The name '" + file + "' is not a file!"); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static URL createUrl(final URL baseUrl, final String path, final String filename) { // checkNotNull("baseUrl", baseUrl); // checkNotNull("filename", filename); // try { // String baseUrlStr = baseUrl.toString(); // if (!baseUrlStr.endsWith(SLASH)) { // baseUrlStr = baseUrlStr + SLASH; // } // final String pathStr; // if ((path == null) || (path.length() == 0)) { // pathStr = ""; // } else { // if (path.endsWith(SLASH)) { // pathStr = path; // } else { // pathStr = path + SLASH; // } // } // return new URL(baseUrlStr + pathStr + filename); // } catch (final IOException ex) { // throw new RuntimeException(ex); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static String getPackagePath(final Class<?> clasz) { // checkNotNull("clasz", clasz); // return clasz.getPackage().getName().replace('.', '/'); // }
import java.util.Properties; import static org.fuin.utils4j.Utils4J.checkNotNull; import static org.fuin.utils4j.Utils4J.checkValidFile; import static org.fuin.utils4j.Utils4J.createUrl; import static org.fuin.utils4j.Utils4J.getPackagePath; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j; /** * Utilities related to the {@link Properties} class. */ public final class PropertiesUtils { /** * Private default constructor. */ private PropertiesUtils() { throw new UnsupportedOperationException("This utility class is not intended to be instanciated!"); } /** * Load properties from classpath. * * @param clasz * Class in the same package as the properties file - Cannot be <code>null</code>. * @param filename * Name of the properties file (without path) - Cannot be <code>null</code>. * * @return Properties. */ public static Properties loadProperties(final Class<?> clasz, final String filename) {
// Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static void checkNotNull(final String name, final Object value) { // if (value == null) { // throw new IllegalNullArgumentException(name); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static void checkValidFile(final File file) { // checkNotNull("file", file); // if (!file.exists()) { // throw new IllegalArgumentException("The file '" + file + "' does not exist!"); // } // if (!file.isFile()) { // throw new IllegalArgumentException("The name '" + file + "' is not a file!"); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static URL createUrl(final URL baseUrl, final String path, final String filename) { // checkNotNull("baseUrl", baseUrl); // checkNotNull("filename", filename); // try { // String baseUrlStr = baseUrl.toString(); // if (!baseUrlStr.endsWith(SLASH)) { // baseUrlStr = baseUrlStr + SLASH; // } // final String pathStr; // if ((path == null) || (path.length() == 0)) { // pathStr = ""; // } else { // if (path.endsWith(SLASH)) { // pathStr = path; // } else { // pathStr = path + SLASH; // } // } // return new URL(baseUrlStr + pathStr + filename); // } catch (final IOException ex) { // throw new RuntimeException(ex); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static String getPackagePath(final Class<?> clasz) { // checkNotNull("clasz", clasz); // return clasz.getPackage().getName().replace('.', '/'); // } // Path: src/main/java/org/fuin/utils4j/PropertiesUtils.java import java.util.Properties; import static org.fuin.utils4j.Utils4J.checkNotNull; import static org.fuin.utils4j.Utils4J.checkValidFile; import static org.fuin.utils4j.Utils4J.createUrl; import static org.fuin.utils4j.Utils4J.getPackagePath; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j; /** * Utilities related to the {@link Properties} class. */ public final class PropertiesUtils { /** * Private default constructor. */ private PropertiesUtils() { throw new UnsupportedOperationException("This utility class is not intended to be instanciated!"); } /** * Load properties from classpath. * * @param clasz * Class in the same package as the properties file - Cannot be <code>null</code>. * @param filename * Name of the properties file (without path) - Cannot be <code>null</code>. * * @return Properties. */ public static Properties loadProperties(final Class<?> clasz, final String filename) {
checkNotNull("clasz", clasz);
fuinorg/utils4j
src/main/java/org/fuin/utils4j/PropertiesUtils.java
// Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static void checkNotNull(final String name, final Object value) { // if (value == null) { // throw new IllegalNullArgumentException(name); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static void checkValidFile(final File file) { // checkNotNull("file", file); // if (!file.exists()) { // throw new IllegalArgumentException("The file '" + file + "' does not exist!"); // } // if (!file.isFile()) { // throw new IllegalArgumentException("The name '" + file + "' is not a file!"); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static URL createUrl(final URL baseUrl, final String path, final String filename) { // checkNotNull("baseUrl", baseUrl); // checkNotNull("filename", filename); // try { // String baseUrlStr = baseUrl.toString(); // if (!baseUrlStr.endsWith(SLASH)) { // baseUrlStr = baseUrlStr + SLASH; // } // final String pathStr; // if ((path == null) || (path.length() == 0)) { // pathStr = ""; // } else { // if (path.endsWith(SLASH)) { // pathStr = path; // } else { // pathStr = path + SLASH; // } // } // return new URL(baseUrlStr + pathStr + filename); // } catch (final IOException ex) { // throw new RuntimeException(ex); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static String getPackagePath(final Class<?> clasz) { // checkNotNull("clasz", clasz); // return clasz.getPackage().getName().replace('.', '/'); // }
import java.util.Properties; import static org.fuin.utils4j.Utils4J.checkNotNull; import static org.fuin.utils4j.Utils4J.checkValidFile; import static org.fuin.utils4j.Utils4J.createUrl; import static org.fuin.utils4j.Utils4J.getPackagePath; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j; /** * Utilities related to the {@link Properties} class. */ public final class PropertiesUtils { /** * Private default constructor. */ private PropertiesUtils() { throw new UnsupportedOperationException("This utility class is not intended to be instanciated!"); } /** * Load properties from classpath. * * @param clasz * Class in the same package as the properties file - Cannot be <code>null</code>. * @param filename * Name of the properties file (without path) - Cannot be <code>null</code>. * * @return Properties. */ public static Properties loadProperties(final Class<?> clasz, final String filename) { checkNotNull("clasz", clasz); checkNotNull("filename", filename);
// Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static void checkNotNull(final String name, final Object value) { // if (value == null) { // throw new IllegalNullArgumentException(name); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static void checkValidFile(final File file) { // checkNotNull("file", file); // if (!file.exists()) { // throw new IllegalArgumentException("The file '" + file + "' does not exist!"); // } // if (!file.isFile()) { // throw new IllegalArgumentException("The name '" + file + "' is not a file!"); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static URL createUrl(final URL baseUrl, final String path, final String filename) { // checkNotNull("baseUrl", baseUrl); // checkNotNull("filename", filename); // try { // String baseUrlStr = baseUrl.toString(); // if (!baseUrlStr.endsWith(SLASH)) { // baseUrlStr = baseUrlStr + SLASH; // } // final String pathStr; // if ((path == null) || (path.length() == 0)) { // pathStr = ""; // } else { // if (path.endsWith(SLASH)) { // pathStr = path; // } else { // pathStr = path + SLASH; // } // } // return new URL(baseUrlStr + pathStr + filename); // } catch (final IOException ex) { // throw new RuntimeException(ex); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static String getPackagePath(final Class<?> clasz) { // checkNotNull("clasz", clasz); // return clasz.getPackage().getName().replace('.', '/'); // } // Path: src/main/java/org/fuin/utils4j/PropertiesUtils.java import java.util.Properties; import static org.fuin.utils4j.Utils4J.checkNotNull; import static org.fuin.utils4j.Utils4J.checkValidFile; import static org.fuin.utils4j.Utils4J.createUrl; import static org.fuin.utils4j.Utils4J.getPackagePath; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j; /** * Utilities related to the {@link Properties} class. */ public final class PropertiesUtils { /** * Private default constructor. */ private PropertiesUtils() { throw new UnsupportedOperationException("This utility class is not intended to be instanciated!"); } /** * Load properties from classpath. * * @param clasz * Class in the same package as the properties file - Cannot be <code>null</code>. * @param filename * Name of the properties file (without path) - Cannot be <code>null</code>. * * @return Properties. */ public static Properties loadProperties(final Class<?> clasz, final String filename) { checkNotNull("clasz", clasz); checkNotNull("filename", filename);
final String path = getPackagePath(clasz);
fuinorg/utils4j
src/main/java/org/fuin/utils4j/PropertiesUtils.java
// Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static void checkNotNull(final String name, final Object value) { // if (value == null) { // throw new IllegalNullArgumentException(name); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static void checkValidFile(final File file) { // checkNotNull("file", file); // if (!file.exists()) { // throw new IllegalArgumentException("The file '" + file + "' does not exist!"); // } // if (!file.isFile()) { // throw new IllegalArgumentException("The name '" + file + "' is not a file!"); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static URL createUrl(final URL baseUrl, final String path, final String filename) { // checkNotNull("baseUrl", baseUrl); // checkNotNull("filename", filename); // try { // String baseUrlStr = baseUrl.toString(); // if (!baseUrlStr.endsWith(SLASH)) { // baseUrlStr = baseUrlStr + SLASH; // } // final String pathStr; // if ((path == null) || (path.length() == 0)) { // pathStr = ""; // } else { // if (path.endsWith(SLASH)) { // pathStr = path; // } else { // pathStr = path + SLASH; // } // } // return new URL(baseUrlStr + pathStr + filename); // } catch (final IOException ex) { // throw new RuntimeException(ex); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static String getPackagePath(final Class<?> clasz) { // checkNotNull("clasz", clasz); // return clasz.getPackage().getName().replace('.', '/'); // }
import java.util.Properties; import static org.fuin.utils4j.Utils4J.checkNotNull; import static org.fuin.utils4j.Utils4J.checkValidFile; import static org.fuin.utils4j.Utils4J.createUrl; import static org.fuin.utils4j.Utils4J.getPackagePath; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j; /** * Utilities related to the {@link Properties} class. */ public final class PropertiesUtils { /** * Private default constructor. */ private PropertiesUtils() { throw new UnsupportedOperationException("This utility class is not intended to be instanciated!"); } /** * Load properties from classpath. * * @param clasz * Class in the same package as the properties file - Cannot be <code>null</code>. * @param filename * Name of the properties file (without path) - Cannot be <code>null</code>. * * @return Properties. */ public static Properties loadProperties(final Class<?> clasz, final String filename) { checkNotNull("clasz", clasz); checkNotNull("filename", filename); final String path = getPackagePath(clasz); final String resPath = path + "/" + filename; return loadProperties(clasz.getClassLoader(), resPath); } /** * Loads a resource from the classpath as properties. * * @param loader * Class loader to use. * @param resource * Resource to load. * * @return Properties. */ public static Properties loadProperties(final ClassLoader loader, final String resource) { checkNotNull("loader", loader); checkNotNull("resource", resource); final Properties props = new Properties(); try (final InputStream inStream = loader.getResourceAsStream(resource)) { if (inStream == null) { throw new IllegalArgumentException("Resource '" + resource + "' not found!"); } props.load(inStream); } catch (final IOException ex) { throw new RuntimeException(ex); } return props; } /** * Load properties from a file. * * @param file * Properties file - Cannot be <code>null</code> and must be a valid file. * * @return Properties. */ public static Properties loadProperties(final File file) { checkNotNull("file", file);
// Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static void checkNotNull(final String name, final Object value) { // if (value == null) { // throw new IllegalNullArgumentException(name); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static void checkValidFile(final File file) { // checkNotNull("file", file); // if (!file.exists()) { // throw new IllegalArgumentException("The file '" + file + "' does not exist!"); // } // if (!file.isFile()) { // throw new IllegalArgumentException("The name '" + file + "' is not a file!"); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static URL createUrl(final URL baseUrl, final String path, final String filename) { // checkNotNull("baseUrl", baseUrl); // checkNotNull("filename", filename); // try { // String baseUrlStr = baseUrl.toString(); // if (!baseUrlStr.endsWith(SLASH)) { // baseUrlStr = baseUrlStr + SLASH; // } // final String pathStr; // if ((path == null) || (path.length() == 0)) { // pathStr = ""; // } else { // if (path.endsWith(SLASH)) { // pathStr = path; // } else { // pathStr = path + SLASH; // } // } // return new URL(baseUrlStr + pathStr + filename); // } catch (final IOException ex) { // throw new RuntimeException(ex); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static String getPackagePath(final Class<?> clasz) { // checkNotNull("clasz", clasz); // return clasz.getPackage().getName().replace('.', '/'); // } // Path: src/main/java/org/fuin/utils4j/PropertiesUtils.java import java.util.Properties; import static org.fuin.utils4j.Utils4J.checkNotNull; import static org.fuin.utils4j.Utils4J.checkValidFile; import static org.fuin.utils4j.Utils4J.createUrl; import static org.fuin.utils4j.Utils4J.getPackagePath; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j; /** * Utilities related to the {@link Properties} class. */ public final class PropertiesUtils { /** * Private default constructor. */ private PropertiesUtils() { throw new UnsupportedOperationException("This utility class is not intended to be instanciated!"); } /** * Load properties from classpath. * * @param clasz * Class in the same package as the properties file - Cannot be <code>null</code>. * @param filename * Name of the properties file (without path) - Cannot be <code>null</code>. * * @return Properties. */ public static Properties loadProperties(final Class<?> clasz, final String filename) { checkNotNull("clasz", clasz); checkNotNull("filename", filename); final String path = getPackagePath(clasz); final String resPath = path + "/" + filename; return loadProperties(clasz.getClassLoader(), resPath); } /** * Loads a resource from the classpath as properties. * * @param loader * Class loader to use. * @param resource * Resource to load. * * @return Properties. */ public static Properties loadProperties(final ClassLoader loader, final String resource) { checkNotNull("loader", loader); checkNotNull("resource", resource); final Properties props = new Properties(); try (final InputStream inStream = loader.getResourceAsStream(resource)) { if (inStream == null) { throw new IllegalArgumentException("Resource '" + resource + "' not found!"); } props.load(inStream); } catch (final IOException ex) { throw new RuntimeException(ex); } return props; } /** * Load properties from a file. * * @param file * Properties file - Cannot be <code>null</code> and must be a valid file. * * @return Properties. */ public static Properties loadProperties(final File file) { checkNotNull("file", file);
checkValidFile(file);
fuinorg/utils4j
src/main/java/org/fuin/utils4j/PropertiesUtils.java
// Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static void checkNotNull(final String name, final Object value) { // if (value == null) { // throw new IllegalNullArgumentException(name); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static void checkValidFile(final File file) { // checkNotNull("file", file); // if (!file.exists()) { // throw new IllegalArgumentException("The file '" + file + "' does not exist!"); // } // if (!file.isFile()) { // throw new IllegalArgumentException("The name '" + file + "' is not a file!"); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static URL createUrl(final URL baseUrl, final String path, final String filename) { // checkNotNull("baseUrl", baseUrl); // checkNotNull("filename", filename); // try { // String baseUrlStr = baseUrl.toString(); // if (!baseUrlStr.endsWith(SLASH)) { // baseUrlStr = baseUrlStr + SLASH; // } // final String pathStr; // if ((path == null) || (path.length() == 0)) { // pathStr = ""; // } else { // if (path.endsWith(SLASH)) { // pathStr = path; // } else { // pathStr = path + SLASH; // } // } // return new URL(baseUrlStr + pathStr + filename); // } catch (final IOException ex) { // throw new RuntimeException(ex); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static String getPackagePath(final Class<?> clasz) { // checkNotNull("clasz", clasz); // return clasz.getPackage().getName().replace('.', '/'); // }
import java.util.Properties; import static org.fuin.utils4j.Utils4J.checkNotNull; import static org.fuin.utils4j.Utils4J.checkValidFile; import static org.fuin.utils4j.Utils4J.createUrl; import static org.fuin.utils4j.Utils4J.getPackagePath; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL;
* @param props * Properties to save - Cannot be <code>null</code>. * @param comment * Comment for the file. */ public static void saveProperties(final File file, final Properties props, final String comment) { checkNotNull("file", file); checkNotNull("props", props); if (!file.getParentFile().exists()) { throw new IllegalArgumentException("The parent directory '" + file.getParentFile() + "' does not exist [file='" + file + "']!"); } try (final OutputStream outStream = new FileOutputStream(file)) { props.store(outStream, comment); } catch (final IOException ex) { throw new RuntimeException(ex); } } /** * Load a file from an directory. * * @param baseUrl * Directory URL - Cannot be <code>null</code>. * @param filename * Filename without path - Cannot be <code>null</code>. * * @return Properties. */ public static Properties loadProperties(final URL baseUrl, final String filename) {
// Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static void checkNotNull(final String name, final Object value) { // if (value == null) { // throw new IllegalNullArgumentException(name); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static void checkValidFile(final File file) { // checkNotNull("file", file); // if (!file.exists()) { // throw new IllegalArgumentException("The file '" + file + "' does not exist!"); // } // if (!file.isFile()) { // throw new IllegalArgumentException("The name '" + file + "' is not a file!"); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static URL createUrl(final URL baseUrl, final String path, final String filename) { // checkNotNull("baseUrl", baseUrl); // checkNotNull("filename", filename); // try { // String baseUrlStr = baseUrl.toString(); // if (!baseUrlStr.endsWith(SLASH)) { // baseUrlStr = baseUrlStr + SLASH; // } // final String pathStr; // if ((path == null) || (path.length() == 0)) { // pathStr = ""; // } else { // if (path.endsWith(SLASH)) { // pathStr = path; // } else { // pathStr = path + SLASH; // } // } // return new URL(baseUrlStr + pathStr + filename); // } catch (final IOException ex) { // throw new RuntimeException(ex); // } // } // // Path: src/main/java/org/fuin/utils4j/Utils4J.java // public static String getPackagePath(final Class<?> clasz) { // checkNotNull("clasz", clasz); // return clasz.getPackage().getName().replace('.', '/'); // } // Path: src/main/java/org/fuin/utils4j/PropertiesUtils.java import java.util.Properties; import static org.fuin.utils4j.Utils4J.checkNotNull; import static org.fuin.utils4j.Utils4J.checkValidFile; import static org.fuin.utils4j.Utils4J.createUrl; import static org.fuin.utils4j.Utils4J.getPackagePath; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; * @param props * Properties to save - Cannot be <code>null</code>. * @param comment * Comment for the file. */ public static void saveProperties(final File file, final Properties props, final String comment) { checkNotNull("file", file); checkNotNull("props", props); if (!file.getParentFile().exists()) { throw new IllegalArgumentException("The parent directory '" + file.getParentFile() + "' does not exist [file='" + file + "']!"); } try (final OutputStream outStream = new FileOutputStream(file)) { props.store(outStream, comment); } catch (final IOException ex) { throw new RuntimeException(ex); } } /** * Load a file from an directory. * * @param baseUrl * Directory URL - Cannot be <code>null</code>. * @param filename * Filename without path - Cannot be <code>null</code>. * * @return Properties. */ public static Properties loadProperties(final URL baseUrl, final String filename) {
return loadProperties(createUrl(baseUrl, "", filename));
fuinorg/utils4j
src/test/java/org/fuin/utils4j/classpath/HandlerTest.java
// Path: src/main/java/org/fuin/utils4j/classpath/Handler.java // public final class Handler extends URLStreamHandler { // // static final String HANDLER_PKGS = "java.protocol.handler.pkgs"; // // static final String PKG = "org.fuin.utils4j"; // // /** // * Adds the protocol handler. // */ // public static void add() { // // String current = System.getProperties().getProperty(HANDLER_PKGS, ""); // if (current.length() > 0) { // if (current.contains(PKG)) { // return; // } // current = current + "|"; // } // System.getProperties().put(HANDLER_PKGS, current + PKG); // // } // // /** // * Removes the protocol handler. // */ // public static void remove() { // // final String current = System.getProperties().getProperty(HANDLER_PKGS, ""); // // // Only one // if (current.equals(PKG)) { // System.getProperties().put(HANDLER_PKGS, ""); // return; // } // // // Middle // String token = "|" + PKG + "|"; // int idx = current.indexOf(token); // if (idx > -1) { // final String removed = current.substring(0, idx) + "|" + current.substring(idx + token.length()); // System.getProperties().put(HANDLER_PKGS, removed); // return; // } // // // Beginning // token = PKG + "|"; // idx = current.indexOf(token); // if (idx > -1) { // final String removed = current.substring(idx + token.length()); // System.getProperties().put(HANDLER_PKGS, removed); // return; // } // // // End // token = "|" + PKG; // idx = current.indexOf(token); // if (idx > -1) { // final String removed = current.substring(0, idx); // System.getProperties().put(HANDLER_PKGS, removed); // return; // } // // } // // @Override // protected final URLConnection openConnection(final URL url) throws IOException { // final String path = url.getPath(); // final URL resourceUrl = this.getClass().getResource(path); // if (resourceUrl == null) { // throw new IllegalArgumentException("Resource not found: " + path); // } // return resourceUrl.openConnection(); // } // // }
import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.net.URL; import java.nio.charset.Charset; import java.util.List; import org.apache.commons.io.IOUtils; import org.fuin.utils4j.classpath.Handler; import org.junit.Test;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.classpath; // CHECKSTYLE:OFF public class HandlerTest { @Test public void testRead() throws IOException {
// Path: src/main/java/org/fuin/utils4j/classpath/Handler.java // public final class Handler extends URLStreamHandler { // // static final String HANDLER_PKGS = "java.protocol.handler.pkgs"; // // static final String PKG = "org.fuin.utils4j"; // // /** // * Adds the protocol handler. // */ // public static void add() { // // String current = System.getProperties().getProperty(HANDLER_PKGS, ""); // if (current.length() > 0) { // if (current.contains(PKG)) { // return; // } // current = current + "|"; // } // System.getProperties().put(HANDLER_PKGS, current + PKG); // // } // // /** // * Removes the protocol handler. // */ // public static void remove() { // // final String current = System.getProperties().getProperty(HANDLER_PKGS, ""); // // // Only one // if (current.equals(PKG)) { // System.getProperties().put(HANDLER_PKGS, ""); // return; // } // // // Middle // String token = "|" + PKG + "|"; // int idx = current.indexOf(token); // if (idx > -1) { // final String removed = current.substring(0, idx) + "|" + current.substring(idx + token.length()); // System.getProperties().put(HANDLER_PKGS, removed); // return; // } // // // Beginning // token = PKG + "|"; // idx = current.indexOf(token); // if (idx > -1) { // final String removed = current.substring(idx + token.length()); // System.getProperties().put(HANDLER_PKGS, removed); // return; // } // // // End // token = "|" + PKG; // idx = current.indexOf(token); // if (idx > -1) { // final String removed = current.substring(0, idx); // System.getProperties().put(HANDLER_PKGS, removed); // return; // } // // } // // @Override // protected final URLConnection openConnection(final URL url) throws IOException { // final String path = url.getPath(); // final URL resourceUrl = this.getClass().getResource(path); // if (resourceUrl == null) { // throw new IllegalArgumentException("Resource not found: " + path); // } // return resourceUrl.openConnection(); // } // // } // Path: src/test/java/org/fuin/utils4j/classpath/HandlerTest.java import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.net.URL; import java.nio.charset.Charset; import java.util.List; import org.apache.commons.io.IOUtils; import org.fuin.utils4j.classpath.Handler; import org.junit.Test; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.classpath; // CHECKSTYLE:OFF public class HandlerTest { @Test public void testRead() throws IOException {
final String original = System.getProperties().getProperty(Handler.HANDLER_PKGS, "");
fuinorg/utils4j
src/main/java/org/fuin/utils4j/filter/ComparablePropertyFilter.java
// Path: src/main/java/org/fuin/utils4j/filter/ComparableFilter.java // public static final class Operator { // // /** Less than. */ // public static final Operator LT = new Operator("LT", "<"); // // /** Less than or equal. */ // public static final Operator LTE = new Operator("LTE", "<="); // // /** Equal. */ // public static final Operator EQ = new Operator("EQ", "="); // // /** Greater than. */ // public static final Operator GT = new Operator("GT", ">"); // // /** Greater than or equal. */ // public static final Operator GTE = new Operator("GTE", ">="); // // /** List of all known instances. */ // public static final List<Operator> INSTANCES = asList(LT, LTE, EQ, GT, GTE); // NOSONAR // // private final String id; // // private final String sign; // // private Operator(final String id, final String sign) { // Utils4J.checkNotNull("id", id); // Utils4J.checkNotNull("sign", sign); // this.id = id; // this.sign = sign; // } // // /** // * Returns the unique name of the operator. // * // * @return ID. // */ // public final String getId() { // return id; // } // // /** // * Returns the symbol for the operator. // * // * @return Sign. // */ // public final String getSign() { // return sign; // } // // /** // * Determines if a given id is valid. // * // * @param id // * Name to check - Cannot be <code>null</code>. // * // * @return If the name is valid <code>true</code> else <code>false</code>. // */ // public static boolean isValid(final String id) { // Utils4J.checkNotNull("id", id); // for (final Operator op : INSTANCES) { // if (op.getId().equals(id)) { // return true; // } // } // return false; // } // // /** // * Returns an instance for a given id. // * // * @param id // * Name to return an instance for - Cannot be <code>null</code> and must be a valid name. // * // * @return Instance. // */ // public static Operator getInstance(final String id) { // Utils4J.checkNotNull("id", id); // for (final Operator op : INSTANCES) { // if (op.getId().equals(id)) { // return op; // } // } // throw new IllegalArgumentException("The id '" + id + "' is unknown!"); // } // // @Override // public final String toString() { // return sign; // } // // private static List<Operator> asList(final Operator... operators) { // final List<Operator> list = new ArrayList<>(operators.length); // for (final Operator operator : operators) { // list.add(operator); // } // return Collections.unmodifiableList(list); // } // // }
import org.fuin.utils4j.filter.ComparableFilter.Operator;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.filter; /** * Defines a filter on a Comparable property. */ public abstract class ComparablePropertyFilter extends PropertyFilter { private final ComparableFilter filter; /** * Constructor with a property and an operator. * * @param newPropertyName * Name of the property. * @param filter * Filter to use. */ public ComparablePropertyFilter(final String newPropertyName, final ComparableFilter filter) { super(newPropertyName); this.filter = filter; } @Override public final boolean complies(final Object obj) { final Comparable value = (Comparable) this.getProperty(obj, this.getPropertyName()); return filter.complies(value); } @Override public final String toString() { return getPropertyName() + filter.toString(); } /** * Returns the filter used for compare operations. * * @return Filter. */ protected final ComparableFilter getFilter() { return filter; } /** * Returns the operator for compare operations. * * @return Operator. */
// Path: src/main/java/org/fuin/utils4j/filter/ComparableFilter.java // public static final class Operator { // // /** Less than. */ // public static final Operator LT = new Operator("LT", "<"); // // /** Less than or equal. */ // public static final Operator LTE = new Operator("LTE", "<="); // // /** Equal. */ // public static final Operator EQ = new Operator("EQ", "="); // // /** Greater than. */ // public static final Operator GT = new Operator("GT", ">"); // // /** Greater than or equal. */ // public static final Operator GTE = new Operator("GTE", ">="); // // /** List of all known instances. */ // public static final List<Operator> INSTANCES = asList(LT, LTE, EQ, GT, GTE); // NOSONAR // // private final String id; // // private final String sign; // // private Operator(final String id, final String sign) { // Utils4J.checkNotNull("id", id); // Utils4J.checkNotNull("sign", sign); // this.id = id; // this.sign = sign; // } // // /** // * Returns the unique name of the operator. // * // * @return ID. // */ // public final String getId() { // return id; // } // // /** // * Returns the symbol for the operator. // * // * @return Sign. // */ // public final String getSign() { // return sign; // } // // /** // * Determines if a given id is valid. // * // * @param id // * Name to check - Cannot be <code>null</code>. // * // * @return If the name is valid <code>true</code> else <code>false</code>. // */ // public static boolean isValid(final String id) { // Utils4J.checkNotNull("id", id); // for (final Operator op : INSTANCES) { // if (op.getId().equals(id)) { // return true; // } // } // return false; // } // // /** // * Returns an instance for a given id. // * // * @param id // * Name to return an instance for - Cannot be <code>null</code> and must be a valid name. // * // * @return Instance. // */ // public static Operator getInstance(final String id) { // Utils4J.checkNotNull("id", id); // for (final Operator op : INSTANCES) { // if (op.getId().equals(id)) { // return op; // } // } // throw new IllegalArgumentException("The id '" + id + "' is unknown!"); // } // // @Override // public final String toString() { // return sign; // } // // private static List<Operator> asList(final Operator... operators) { // final List<Operator> list = new ArrayList<>(operators.length); // for (final Operator operator : operators) { // list.add(operator); // } // return Collections.unmodifiableList(list); // } // // } // Path: src/main/java/org/fuin/utils4j/filter/ComparablePropertyFilter.java import org.fuin.utils4j.filter.ComparableFilter.Operator; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.filter; /** * Defines a filter on a Comparable property. */ public abstract class ComparablePropertyFilter extends PropertyFilter { private final ComparableFilter filter; /** * Constructor with a property and an operator. * * @param newPropertyName * Name of the property. * @param filter * Filter to use. */ public ComparablePropertyFilter(final String newPropertyName, final ComparableFilter filter) { super(newPropertyName); this.filter = filter; } @Override public final boolean complies(final Object obj) { final Comparable value = (Comparable) this.getProperty(obj, this.getPropertyName()); return filter.complies(value); } @Override public final String toString() { return getPropertyName() + filter.toString(); } /** * Returns the filter used for compare operations. * * @return Filter. */ protected final ComparableFilter getFilter() { return filter; } /** * Returns the operator for compare operations. * * @return Operator. */
public final Operator getOperator() {
fuinorg/utils4j
src/test/java/org/fuin/utils4j/VariableResolverTest.java
// Path: src/main/java/org/fuin/utils4j/VariableResolver.java // public static Set<String> references(final String value) { // // final HashSet<String> names = new HashSet<>(); // if ((value == null) || (value.length() == 0)) { // return names; // } // // int end = -1; // int from = 0; // int start = -1; // while ((start = value.indexOf("${", from)) > -1) { // end = value.indexOf('}', start + 1); // if (end == -1) { // // No closing bracket found... // from = value.length(); // } else { // names.add(value.substring(start + 2, end)); // from = end + 1; // } // } // // return names; // // }
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.MapEntry.entry; import static org.fuin.utils4j.VariableResolver.references; import java.util.HashMap; import java.util.Map; import org.junit.Test;
// TEST try { new VariableResolver(vars); } catch (final IllegalStateException ex) { assertThat(ex.getMessage()).isEqualTo("Cycle: a > b > c > a"); } } @Test public void testUnresolved() { // PREPARE final Map<String, String> vars = new HashMap<>(); vars.put("a", "1${b}"); vars.put("b", "${c}"); // TEST final VariableResolver testee = new VariableResolver(vars); // VERIFY assertThat(testee.getDepth()).contains(entry("a", 2), entry("b", 1)); assertThat(testee.getResolved()).contains(entry("a", "1${c}"), entry("b", "${c}")); assertThat(testee.getUnresolved()).contains(entry("a", "1${b}"), entry("b", "${c}")); } @Test public void testReferences() {
// Path: src/main/java/org/fuin/utils4j/VariableResolver.java // public static Set<String> references(final String value) { // // final HashSet<String> names = new HashSet<>(); // if ((value == null) || (value.length() == 0)) { // return names; // } // // int end = -1; // int from = 0; // int start = -1; // while ((start = value.indexOf("${", from)) > -1) { // end = value.indexOf('}', start + 1); // if (end == -1) { // // No closing bracket found... // from = value.length(); // } else { // names.add(value.substring(start + 2, end)); // from = end + 1; // } // } // // return names; // // } // Path: src/test/java/org/fuin/utils4j/VariableResolverTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.MapEntry.entry; import static org.fuin.utils4j.VariableResolver.references; import java.util.HashMap; import java.util.Map; import org.junit.Test; // TEST try { new VariableResolver(vars); } catch (final IllegalStateException ex) { assertThat(ex.getMessage()).isEqualTo("Cycle: a > b > c > a"); } } @Test public void testUnresolved() { // PREPARE final Map<String, String> vars = new HashMap<>(); vars.put("a", "1${b}"); vars.put("b", "${c}"); // TEST final VariableResolver testee = new VariableResolver(vars); // VERIFY assertThat(testee.getDepth()).contains(entry("a", 2), entry("b", 1)); assertThat(testee.getResolved()).contains(entry("a", "1${c}"), entry("b", "${c}")); assertThat(testee.getUnresolved()).contains(entry("a", "1${b}"), entry("b", "${c}")); } @Test public void testReferences() {
assertThat(references(null)).isEmpty();
fuinorg/utils4j
src/test/java/org/fuin/utils4j/examples/PropertiesFilePreferencesFactoryExample.java
// Path: src/main/java/org/fuin/utils4j/PropertiesFilePreferencesFactory.java // public final class PropertiesFilePreferencesFactory implements PreferencesFactory { // // /** // * System property key used containing the path and name of the "system" preferences directory. // */ // public static final String SYSTEM_PREF_DIR = "PropertiesFilePreferences.SystemDir"; // // /** // * System property key used containing the path and name of the "user" preferences directory. // */ // public static final String USER_PREF_DIR = "PropertiesFilePreferences.UserDir"; // // private final String systemPrefDir; // // private final String userPrefDir; // // private PropertiesFilePreferences systemRoot = null; // // private PropertiesFilePreferences userRoot = null; // // /** // * Default constructor. // */ // public PropertiesFilePreferencesFactory() { // this(System.getProperty(SYSTEM_PREF_DIR), System.getProperty(USER_PREF_DIR)); // } // // /** // * Constructor with path and filenames of the system and user root directories. // * // * @param systemPrefDir // * Path and name of the "system" preferences directory. // * @param userPrefDir // * Path and name of the "user" preferences directory. // */ // public PropertiesFilePreferencesFactory(final String systemPrefDir, final String userPrefDir) { // super(); // this.systemPrefDir = systemPrefDir; // this.userPrefDir = userPrefDir; // } // // @Override // public final synchronized Preferences systemRoot() { // if (systemRoot == null) { // systemRoot = new PropertiesFilePreferences(getValidDir(SYSTEM_PREF_DIR, systemPrefDir)); // // Always sync at shutdown // Runtime.getRuntime().addShutdownHook(new Thread() { // @Override // public void run() { // try { // systemRoot.flush(); // } catch (final BackingStoreException ex) { // System.err.println("Failed to save 'systemRoot' preferences!"); // ex.printStackTrace(System.err); // } // } // }); // } // return systemRoot; // } // // @Override // public final synchronized Preferences userRoot() { // if (userRoot == null) { // userRoot = new PropertiesFilePreferences(getValidDir(USER_PREF_DIR, userPrefDir)); // // Always sync at shutdown // Runtime.getRuntime().addShutdownHook(new Thread() { // @Override // public void run() { // try { // userRoot.flush(); // } catch (final BackingStoreException ex) { // System.err.println("Failed to save 'userRoot' preferences!"); // ex.printStackTrace(System.err); // } // } // }); // } // return userRoot; // } // // /** // * Checks if the system variable is set and is a valid directory. If this is not the case a {@link RuntimeException} will be thrown. // * // * @param varName // * Name of the system variable. // * @param dirName // * Name of the directory (from the system variable). // * // * @return Directory reference. // */ // private File getValidDir(final String varName, final String dirName) { // if (dirName == null) { // throw new RuntimeException("The system variable '" + varName + "' is not set!"); // } // final File dir = new File(dirName); // if (!dir.exists()) { // throw new IllegalArgumentException("The directory '" + dir + "' does not exist! [system variable '" + varName + "']"); // } // if (!dir.isDirectory()) { // throw new IllegalArgumentException("The name '" + dir + "' is not a directory! [system variable '" + varName + "']"); // } // return dir; // } // // }
import java.io.File; import java.util.prefs.Preferences; import org.fuin.utils4j.PropertiesFilePreferencesFactory;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.examples; /** * Example using the file based preferences factory. */ public final class PropertiesFilePreferencesFactoryExample { /** * Private constructor. */ private PropertiesFilePreferencesFactoryExample() { throw new UnsupportedOperationException("It's not allowed to create an instance of this class!"); } /** * Executes the example. * * @param args * Not used. */ public static void main(final String[] args) { // Create an application wide preferences directory named "config" in // the current startup directory final File systemPrefDir = new File("./config"); if (!systemPrefDir.exists()) { systemPrefDir.mkdir(); } // Create a user preferences directory with your applications name in // the user's home directory final File userHomeDir = new File(System.getProperty("user.home")); final File userPrefDir = new File(userHomeDir, ".myapp"); if (!userPrefDir.exists()) { userPrefDir.mkdir(); } // Set both directories as system properties
// Path: src/main/java/org/fuin/utils4j/PropertiesFilePreferencesFactory.java // public final class PropertiesFilePreferencesFactory implements PreferencesFactory { // // /** // * System property key used containing the path and name of the "system" preferences directory. // */ // public static final String SYSTEM_PREF_DIR = "PropertiesFilePreferences.SystemDir"; // // /** // * System property key used containing the path and name of the "user" preferences directory. // */ // public static final String USER_PREF_DIR = "PropertiesFilePreferences.UserDir"; // // private final String systemPrefDir; // // private final String userPrefDir; // // private PropertiesFilePreferences systemRoot = null; // // private PropertiesFilePreferences userRoot = null; // // /** // * Default constructor. // */ // public PropertiesFilePreferencesFactory() { // this(System.getProperty(SYSTEM_PREF_DIR), System.getProperty(USER_PREF_DIR)); // } // // /** // * Constructor with path and filenames of the system and user root directories. // * // * @param systemPrefDir // * Path and name of the "system" preferences directory. // * @param userPrefDir // * Path and name of the "user" preferences directory. // */ // public PropertiesFilePreferencesFactory(final String systemPrefDir, final String userPrefDir) { // super(); // this.systemPrefDir = systemPrefDir; // this.userPrefDir = userPrefDir; // } // // @Override // public final synchronized Preferences systemRoot() { // if (systemRoot == null) { // systemRoot = new PropertiesFilePreferences(getValidDir(SYSTEM_PREF_DIR, systemPrefDir)); // // Always sync at shutdown // Runtime.getRuntime().addShutdownHook(new Thread() { // @Override // public void run() { // try { // systemRoot.flush(); // } catch (final BackingStoreException ex) { // System.err.println("Failed to save 'systemRoot' preferences!"); // ex.printStackTrace(System.err); // } // } // }); // } // return systemRoot; // } // // @Override // public final synchronized Preferences userRoot() { // if (userRoot == null) { // userRoot = new PropertiesFilePreferences(getValidDir(USER_PREF_DIR, userPrefDir)); // // Always sync at shutdown // Runtime.getRuntime().addShutdownHook(new Thread() { // @Override // public void run() { // try { // userRoot.flush(); // } catch (final BackingStoreException ex) { // System.err.println("Failed to save 'userRoot' preferences!"); // ex.printStackTrace(System.err); // } // } // }); // } // return userRoot; // } // // /** // * Checks if the system variable is set and is a valid directory. If this is not the case a {@link RuntimeException} will be thrown. // * // * @param varName // * Name of the system variable. // * @param dirName // * Name of the directory (from the system variable). // * // * @return Directory reference. // */ // private File getValidDir(final String varName, final String dirName) { // if (dirName == null) { // throw new RuntimeException("The system variable '" + varName + "' is not set!"); // } // final File dir = new File(dirName); // if (!dir.exists()) { // throw new IllegalArgumentException("The directory '" + dir + "' does not exist! [system variable '" + varName + "']"); // } // if (!dir.isDirectory()) { // throw new IllegalArgumentException("The name '" + dir + "' is not a directory! [system variable '" + varName + "']"); // } // return dir; // } // // } // Path: src/test/java/org/fuin/utils4j/examples/PropertiesFilePreferencesFactoryExample.java import java.io.File; import java.util.prefs.Preferences; import org.fuin.utils4j.PropertiesFilePreferencesFactory; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.examples; /** * Example using the file based preferences factory. */ public final class PropertiesFilePreferencesFactoryExample { /** * Private constructor. */ private PropertiesFilePreferencesFactoryExample() { throw new UnsupportedOperationException("It's not allowed to create an instance of this class!"); } /** * Executes the example. * * @param args * Not used. */ public static void main(final String[] args) { // Create an application wide preferences directory named "config" in // the current startup directory final File systemPrefDir = new File("./config"); if (!systemPrefDir.exists()) { systemPrefDir.mkdir(); } // Create a user preferences directory with your applications name in // the user's home directory final File userHomeDir = new File(System.getProperty("user.home")); final File userPrefDir = new File(userHomeDir, ".myapp"); if (!userPrefDir.exists()) { userPrefDir.mkdir(); } // Set both directories as system properties
System.setProperty(PropertiesFilePreferencesFactory.SYSTEM_PREF_DIR, systemPrefDir.toString());
fuinorg/utils4j
src/main/java/org/fuin/utils4j/filter/StringPropertyFilter.java
// Path: src/main/java/org/fuin/utils4j/filter/StringFilter.java // public static final class Operator { // // /** Less than. */ // public static final Operator LT = new Operator("LT", "<"); // // /** Less than or equal. */ // public static final Operator LTE = new Operator("LTE", "<="); // // /** Equal. */ // public static final Operator EQ = new Operator("EQ", "="); // // /** Equal (relaxed) compare for Strings. */ // public static final Operator EQ_RELAXED = new Operator("EQ_RELAXED", "~"); // // /** Greater than. */ // public static final Operator GT = new Operator("GT", ">"); // // /** Greater than or equal. */ // public static final Operator GTE = new Operator("GTE", ">="); // // /** List of all known instances. */ // public static final List<Operator> INSTANCES = asList(LT, LTE, EQ, EQ_RELAXED, GT, GTE); // NOSONAR // // private final String id; // // private final String sign; // // /** // * Constructor with id and sign. // * // * @param id // * Unique name. // * @param sign // * Sign. // */ // private Operator(final String id, final String sign) { // Utils4J.checkNotNull("id", id); // Utils4J.checkNotNull("sign", sign); // this.id = id; // this.sign = sign; // } // // /** // * Returns the unique name of the operator. // * // * @return ID. // */ // public final String getId() { // return id; // } // // /** // * Returns the symbol for the operator. // * // * @return Sign. // */ // public final String getSign() { // return sign; // } // // /** // * Determines if a given id is valid. // * // * @param id // * Name to check - Cannot be <code>null</code>. // * // * @return If the name is valid <code>true</code> else <code>false</code>. // */ // public static boolean isValid(final String id) { // Utils4J.checkNotNull("id", id); // for (final Operator op : INSTANCES) { // if (op.getId().equals(id)) { // return true; // } // } // return false; // } // // /** // * Returns an instance for a given id. // * // * @param id // * Name to return an instance for - Cannot be <code>null</code> and must be a valid name. // * // * @return Instance. // */ // public static Operator getInstance(final String id) { // Utils4J.checkNotNull("id", id); // for (final Operator op : INSTANCES) { // if (op.getId().equals(id)) { // return op; // } // } // throw new IllegalArgumentException("The id '" + id + "' is unknown!"); // } // // @Override // public final String toString() { // return sign; // } // // private static List<Operator> asList(final Operator... operators) { // final List<Operator> list = new ArrayList<>(operators.length); // for (final Operator operator : operators) { // list.add(operator); // } // return Collections.unmodifiableList(list); // } // // }
import org.fuin.utils4j.filter.StringFilter.Operator;
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.filter; /** * Defines a filter on a String property. */ public class StringPropertyFilter extends PropertyFilter { private final StringFilter filter; /** * Constructor with a property and an operator. * * @param newPropertyName * Name of the property. * @param newOperator * Operator to use. * @param constValue * Value to compare with. */
// Path: src/main/java/org/fuin/utils4j/filter/StringFilter.java // public static final class Operator { // // /** Less than. */ // public static final Operator LT = new Operator("LT", "<"); // // /** Less than or equal. */ // public static final Operator LTE = new Operator("LTE", "<="); // // /** Equal. */ // public static final Operator EQ = new Operator("EQ", "="); // // /** Equal (relaxed) compare for Strings. */ // public static final Operator EQ_RELAXED = new Operator("EQ_RELAXED", "~"); // // /** Greater than. */ // public static final Operator GT = new Operator("GT", ">"); // // /** Greater than or equal. */ // public static final Operator GTE = new Operator("GTE", ">="); // // /** List of all known instances. */ // public static final List<Operator> INSTANCES = asList(LT, LTE, EQ, EQ_RELAXED, GT, GTE); // NOSONAR // // private final String id; // // private final String sign; // // /** // * Constructor with id and sign. // * // * @param id // * Unique name. // * @param sign // * Sign. // */ // private Operator(final String id, final String sign) { // Utils4J.checkNotNull("id", id); // Utils4J.checkNotNull("sign", sign); // this.id = id; // this.sign = sign; // } // // /** // * Returns the unique name of the operator. // * // * @return ID. // */ // public final String getId() { // return id; // } // // /** // * Returns the symbol for the operator. // * // * @return Sign. // */ // public final String getSign() { // return sign; // } // // /** // * Determines if a given id is valid. // * // * @param id // * Name to check - Cannot be <code>null</code>. // * // * @return If the name is valid <code>true</code> else <code>false</code>. // */ // public static boolean isValid(final String id) { // Utils4J.checkNotNull("id", id); // for (final Operator op : INSTANCES) { // if (op.getId().equals(id)) { // return true; // } // } // return false; // } // // /** // * Returns an instance for a given id. // * // * @param id // * Name to return an instance for - Cannot be <code>null</code> and must be a valid name. // * // * @return Instance. // */ // public static Operator getInstance(final String id) { // Utils4J.checkNotNull("id", id); // for (final Operator op : INSTANCES) { // if (op.getId().equals(id)) { // return op; // } // } // throw new IllegalArgumentException("The id '" + id + "' is unknown!"); // } // // @Override // public final String toString() { // return sign; // } // // private static List<Operator> asList(final Operator... operators) { // final List<Operator> list = new ArrayList<>(operators.length); // for (final Operator operator : operators) { // list.add(operator); // } // return Collections.unmodifiableList(list); // } // // } // Path: src/main/java/org/fuin/utils4j/filter/StringPropertyFilter.java import org.fuin.utils4j.filter.StringFilter.Operator; /** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.utils4j.filter; /** * Defines a filter on a String property. */ public class StringPropertyFilter extends PropertyFilter { private final StringFilter filter; /** * Constructor with a property and an operator. * * @param newPropertyName * Name of the property. * @param newOperator * Operator to use. * @param constValue * Value to compare with. */
public StringPropertyFilter(final String newPropertyName, final StringFilter.Operator newOperator, final String constValue) {
OasisDigital/nges
src/main/java/com/oasisdigital/nges/event/Demo.java
// Path: src/main/java/com/oasisdigital/nges/cluster/EventUpdate.java // public class EventUpdate implements Serializable { // private static final long serialVersionUID = 4220177459255722476L; // // private long eventId; // // public EventUpdate(long eventId) { // this.eventId = eventId; // } // // public long getEventId() { // return eventId; // } // }
import com.google.common.eventbus.Subscribe; import com.oasisdigital.nges.cluster.EventUpdate;
package com.oasisdigital.nges.event; public class Demo { public static void main(String[] args) { // PGPoolingDataSource dataSource = new PGPoolingDataSource(); // dataSource.setUrl("jdbc:postgresql://localhost/tic_tac_toe"); // dataSource.setUser("konrad"); // dataSource.setPassword("password"); // // // Initialize context // EventStoreContext ctx = new EventStoreContext(dataSource); // ctx.initialize(); // EventStore eventStore = ctx.getEventStore(); // // // Save an event // UUID streamId = UUID.randomUUID(); // UUID correlationId = UUID.randomUUID(); // Event event = new Event(streamId, "EventStoreDemonstrated", correlationId, // "{\"test\": \"Any JSON payload\"}"); // // MessageGroup messageGroup = ctx.getMessageGroup(); // messageGroup.registerSubscriber(new Subscriber()); // messageGroup // .publish("Hello"); // // eventStore.save(Arrays.asList(event), "MyStream", EventStore.NEW_STREAM); // // // Get up to 100 events after event ID 0 // eventStore.getEventsForAllStreams(0, 100); // // // Get up to 100 events for given stream ID, after sequence 0 within that stream // eventStore.getEventsForStream(streamId, 0, 100); // // // Clean up - shut down JGroups cluster and JMX monitoring // ctx.destroy(); } static class Subscriber { @Subscribe
// Path: src/main/java/com/oasisdigital/nges/cluster/EventUpdate.java // public class EventUpdate implements Serializable { // private static final long serialVersionUID = 4220177459255722476L; // // private long eventId; // // public EventUpdate(long eventId) { // this.eventId = eventId; // } // // public long getEventId() { // return eventId; // } // } // Path: src/main/java/com/oasisdigital/nges/event/Demo.java import com.google.common.eventbus.Subscribe; import com.oasisdigital.nges.cluster.EventUpdate; package com.oasisdigital.nges.event; public class Demo { public static void main(String[] args) { // PGPoolingDataSource dataSource = new PGPoolingDataSource(); // dataSource.setUrl("jdbc:postgresql://localhost/tic_tac_toe"); // dataSource.setUser("konrad"); // dataSource.setPassword("password"); // // // Initialize context // EventStoreContext ctx = new EventStoreContext(dataSource); // ctx.initialize(); // EventStore eventStore = ctx.getEventStore(); // // // Save an event // UUID streamId = UUID.randomUUID(); // UUID correlationId = UUID.randomUUID(); // Event event = new Event(streamId, "EventStoreDemonstrated", correlationId, // "{\"test\": \"Any JSON payload\"}"); // // MessageGroup messageGroup = ctx.getMessageGroup(); // messageGroup.registerSubscriber(new Subscriber()); // messageGroup // .publish("Hello"); // // eventStore.save(Arrays.asList(event), "MyStream", EventStore.NEW_STREAM); // // // Get up to 100 events after event ID 0 // eventStore.getEventsForAllStreams(0, 100); // // // Get up to 100 events for given stream ID, after sequence 0 within that stream // eventStore.getEventsForStream(streamId, 0, 100); // // // Clean up - shut down JGroups cluster and JMX monitoring // ctx.destroy(); } static class Subscriber { @Subscribe
public void on(EventUpdate eventUpdate) {
OasisDigital/nges
src/main/java/com/oasisdigital/nges/event/jdbc/SQLExceptionTranslation.java
// Path: src/main/java/com/oasisdigital/nges/event/EventStoreException.java // public class EventStoreException extends RuntimeException { // // private static final long serialVersionUID = -1237680703226042282L; // // public EventStoreException() { // super(); // } // // public EventStoreException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreException(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreException(String message) { // super(message); // } // // public EventStoreException(Throwable cause) { // super(cause); // } // }
import java.sql.SQLException; import com.oasisdigital.nges.event.EventStoreException;
package com.oasisdigital.nges.event.jdbc; class SQLExceptionTranslation { // http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html private static final String UNIQUE_VIOLATION = "23505";
// Path: src/main/java/com/oasisdigital/nges/event/EventStoreException.java // public class EventStoreException extends RuntimeException { // // private static final long serialVersionUID = -1237680703226042282L; // // public EventStoreException() { // super(); // } // // public EventStoreException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreException(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreException(String message) { // super(message); // } // // public EventStoreException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/com/oasisdigital/nges/event/jdbc/SQLExceptionTranslation.java import java.sql.SQLException; import com.oasisdigital.nges.event.EventStoreException; package com.oasisdigital.nges.event.jdbc; class SQLExceptionTranslation { // http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html private static final String UNIQUE_VIOLATION = "23505";
public static EventStoreException translate(SQLException e) {
OasisDigital/nges
src/main/java/com/oasisdigital/nges/event/jdbc/EventLogDao.java
// Path: src/main/java/com/oasisdigital/nges/event/Event.java // public class Event implements Serializable { // private static final long serialVersionUID = 1L; // // /** // * <p> // * Number assigned from a globally increasing sequence. Might contain holes, i.e. it is possible for // * events with IDs 100 and 102 to exist without an event with ID 101. Event with ID N+1 must have been // * saved after the event with ID N. // * </p> // * <p> // * Automatically populated by the system on save, never empty. // * </p> // */ // private long eventId; // // /** // * ID of a stream of events, for example identifying a DDD aggregeate or another kind of entity. Populated // * by the caller on save, mandatory. // */ // private UUID streamId; // // /** // * Type of the event, useful for interpreting the payload etc. Populated by the caller on save. // */ // private String type; // // /** // * Correlation ID. Populated by the caller on save, mandatory. // */ // private UUID correlationId; // // /** // * Sequence number within this particular stream. Events within a stream are automatically assigned // * consecutive numbers starting with 1, without gaps. Never empry. // */ // private long sequence; // // /** // * Time when the event was saved. Events saved in one transaction are assigned the exact same timestamp. // * Automatically populated by the system on save, never empty. // */ // private OffsetDateTime transactionTime; // // /** // * JSON payload. // */ // private String payload; // // public Event() { // } // // public Event(UUID streamId, String type, UUID correlationId, String payload) { // this.streamId = streamId; // this.type = type; // this.correlationId = correlationId; // this.payload = payload; // } // // public void setEventId(long eventId) { // this.eventId = eventId; // } // // public void setStreamId(UUID streamId) { // this.streamId = streamId; // } // // public void setType(String type) { // this.type = type; // } // // public void setTransactionTime(OffsetDateTime transactionTime) { // this.transactionTime = transactionTime; // } // // public void setPayload(String payload) { // this.payload = payload; // } // // public void setCorrelationId(UUID correlationId) { // this.correlationId = correlationId; // } // // public long getEventId() { // return eventId; // } // // public UUID getStreamId() { // return streamId; // } // // public String getType() { // return type; // } // // public OffsetDateTime getTransactionTime() { // return transactionTime; // } // // public String getPayload() { // return payload; // } // // public UUID getCorrelationId() { // return correlationId; // } // // public long getSequence() { // return sequence; // } // // public void setSequence(long sequence) { // this.sequence = sequence; // } // // } // // Path: src/main/java/com/oasisdigital/nges/event/EventStoreException.java // public class EventStoreException extends RuntimeException { // // private static final long serialVersionUID = -1237680703226042282L; // // public EventStoreException() { // super(); // } // // public EventStoreException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreException(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreException(String message) { // super(message); // } // // public EventStoreException(Throwable cause) { // super(cause); // } // }
import static java.util.stream.Collectors.toList; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import com.oasisdigital.nges.event.Event; import com.oasisdigital.nges.event.EventStoreException;
package com.oasisdigital.nges.event.jdbc; class EventLogDao { private final JdbcQueries queries; public EventLogDao(ConnectionSource connectionSource) { this.queries = new JdbcQueries(connectionSource); }
// Path: src/main/java/com/oasisdigital/nges/event/Event.java // public class Event implements Serializable { // private static final long serialVersionUID = 1L; // // /** // * <p> // * Number assigned from a globally increasing sequence. Might contain holes, i.e. it is possible for // * events with IDs 100 and 102 to exist without an event with ID 101. Event with ID N+1 must have been // * saved after the event with ID N. // * </p> // * <p> // * Automatically populated by the system on save, never empty. // * </p> // */ // private long eventId; // // /** // * ID of a stream of events, for example identifying a DDD aggregeate or another kind of entity. Populated // * by the caller on save, mandatory. // */ // private UUID streamId; // // /** // * Type of the event, useful for interpreting the payload etc. Populated by the caller on save. // */ // private String type; // // /** // * Correlation ID. Populated by the caller on save, mandatory. // */ // private UUID correlationId; // // /** // * Sequence number within this particular stream. Events within a stream are automatically assigned // * consecutive numbers starting with 1, without gaps. Never empry. // */ // private long sequence; // // /** // * Time when the event was saved. Events saved in one transaction are assigned the exact same timestamp. // * Automatically populated by the system on save, never empty. // */ // private OffsetDateTime transactionTime; // // /** // * JSON payload. // */ // private String payload; // // public Event() { // } // // public Event(UUID streamId, String type, UUID correlationId, String payload) { // this.streamId = streamId; // this.type = type; // this.correlationId = correlationId; // this.payload = payload; // } // // public void setEventId(long eventId) { // this.eventId = eventId; // } // // public void setStreamId(UUID streamId) { // this.streamId = streamId; // } // // public void setType(String type) { // this.type = type; // } // // public void setTransactionTime(OffsetDateTime transactionTime) { // this.transactionTime = transactionTime; // } // // public void setPayload(String payload) { // this.payload = payload; // } // // public void setCorrelationId(UUID correlationId) { // this.correlationId = correlationId; // } // // public long getEventId() { // return eventId; // } // // public UUID getStreamId() { // return streamId; // } // // public String getType() { // return type; // } // // public OffsetDateTime getTransactionTime() { // return transactionTime; // } // // public String getPayload() { // return payload; // } // // public UUID getCorrelationId() { // return correlationId; // } // // public long getSequence() { // return sequence; // } // // public void setSequence(long sequence) { // this.sequence = sequence; // } // // } // // Path: src/main/java/com/oasisdigital/nges/event/EventStoreException.java // public class EventStoreException extends RuntimeException { // // private static final long serialVersionUID = -1237680703226042282L; // // public EventStoreException() { // super(); // } // // public EventStoreException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreException(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreException(String message) { // super(message); // } // // public EventStoreException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/com/oasisdigital/nges/event/jdbc/EventLogDao.java import static java.util.stream.Collectors.toList; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import com.oasisdigital.nges.event.Event; import com.oasisdigital.nges.event.EventStoreException; package com.oasisdigital.nges.event.jdbc; class EventLogDao { private final JdbcQueries queries; public EventLogDao(ConnectionSource connectionSource) { this.queries = new JdbcQueries(connectionSource); }
public Event getEvent(long eventId) throws EventStoreException {
OasisDigital/nges
src/main/java/com/oasisdigital/nges/event/jdbc/EventLogDao.java
// Path: src/main/java/com/oasisdigital/nges/event/Event.java // public class Event implements Serializable { // private static final long serialVersionUID = 1L; // // /** // * <p> // * Number assigned from a globally increasing sequence. Might contain holes, i.e. it is possible for // * events with IDs 100 and 102 to exist without an event with ID 101. Event with ID N+1 must have been // * saved after the event with ID N. // * </p> // * <p> // * Automatically populated by the system on save, never empty. // * </p> // */ // private long eventId; // // /** // * ID of a stream of events, for example identifying a DDD aggregeate or another kind of entity. Populated // * by the caller on save, mandatory. // */ // private UUID streamId; // // /** // * Type of the event, useful for interpreting the payload etc. Populated by the caller on save. // */ // private String type; // // /** // * Correlation ID. Populated by the caller on save, mandatory. // */ // private UUID correlationId; // // /** // * Sequence number within this particular stream. Events within a stream are automatically assigned // * consecutive numbers starting with 1, without gaps. Never empry. // */ // private long sequence; // // /** // * Time when the event was saved. Events saved in one transaction are assigned the exact same timestamp. // * Automatically populated by the system on save, never empty. // */ // private OffsetDateTime transactionTime; // // /** // * JSON payload. // */ // private String payload; // // public Event() { // } // // public Event(UUID streamId, String type, UUID correlationId, String payload) { // this.streamId = streamId; // this.type = type; // this.correlationId = correlationId; // this.payload = payload; // } // // public void setEventId(long eventId) { // this.eventId = eventId; // } // // public void setStreamId(UUID streamId) { // this.streamId = streamId; // } // // public void setType(String type) { // this.type = type; // } // // public void setTransactionTime(OffsetDateTime transactionTime) { // this.transactionTime = transactionTime; // } // // public void setPayload(String payload) { // this.payload = payload; // } // // public void setCorrelationId(UUID correlationId) { // this.correlationId = correlationId; // } // // public long getEventId() { // return eventId; // } // // public UUID getStreamId() { // return streamId; // } // // public String getType() { // return type; // } // // public OffsetDateTime getTransactionTime() { // return transactionTime; // } // // public String getPayload() { // return payload; // } // // public UUID getCorrelationId() { // return correlationId; // } // // public long getSequence() { // return sequence; // } // // public void setSequence(long sequence) { // this.sequence = sequence; // } // // } // // Path: src/main/java/com/oasisdigital/nges/event/EventStoreException.java // public class EventStoreException extends RuntimeException { // // private static final long serialVersionUID = -1237680703226042282L; // // public EventStoreException() { // super(); // } // // public EventStoreException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreException(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreException(String message) { // super(message); // } // // public EventStoreException(Throwable cause) { // super(cause); // } // }
import static java.util.stream.Collectors.toList; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import com.oasisdigital.nges.event.Event; import com.oasisdigital.nges.event.EventStoreException;
package com.oasisdigital.nges.event.jdbc; class EventLogDao { private final JdbcQueries queries; public EventLogDao(ConnectionSource connectionSource) { this.queries = new JdbcQueries(connectionSource); }
// Path: src/main/java/com/oasisdigital/nges/event/Event.java // public class Event implements Serializable { // private static final long serialVersionUID = 1L; // // /** // * <p> // * Number assigned from a globally increasing sequence. Might contain holes, i.e. it is possible for // * events with IDs 100 and 102 to exist without an event with ID 101. Event with ID N+1 must have been // * saved after the event with ID N. // * </p> // * <p> // * Automatically populated by the system on save, never empty. // * </p> // */ // private long eventId; // // /** // * ID of a stream of events, for example identifying a DDD aggregeate or another kind of entity. Populated // * by the caller on save, mandatory. // */ // private UUID streamId; // // /** // * Type of the event, useful for interpreting the payload etc. Populated by the caller on save. // */ // private String type; // // /** // * Correlation ID. Populated by the caller on save, mandatory. // */ // private UUID correlationId; // // /** // * Sequence number within this particular stream. Events within a stream are automatically assigned // * consecutive numbers starting with 1, without gaps. Never empry. // */ // private long sequence; // // /** // * Time when the event was saved. Events saved in one transaction are assigned the exact same timestamp. // * Automatically populated by the system on save, never empty. // */ // private OffsetDateTime transactionTime; // // /** // * JSON payload. // */ // private String payload; // // public Event() { // } // // public Event(UUID streamId, String type, UUID correlationId, String payload) { // this.streamId = streamId; // this.type = type; // this.correlationId = correlationId; // this.payload = payload; // } // // public void setEventId(long eventId) { // this.eventId = eventId; // } // // public void setStreamId(UUID streamId) { // this.streamId = streamId; // } // // public void setType(String type) { // this.type = type; // } // // public void setTransactionTime(OffsetDateTime transactionTime) { // this.transactionTime = transactionTime; // } // // public void setPayload(String payload) { // this.payload = payload; // } // // public void setCorrelationId(UUID correlationId) { // this.correlationId = correlationId; // } // // public long getEventId() { // return eventId; // } // // public UUID getStreamId() { // return streamId; // } // // public String getType() { // return type; // } // // public OffsetDateTime getTransactionTime() { // return transactionTime; // } // // public String getPayload() { // return payload; // } // // public UUID getCorrelationId() { // return correlationId; // } // // public long getSequence() { // return sequence; // } // // public void setSequence(long sequence) { // this.sequence = sequence; // } // // } // // Path: src/main/java/com/oasisdigital/nges/event/EventStoreException.java // public class EventStoreException extends RuntimeException { // // private static final long serialVersionUID = -1237680703226042282L; // // public EventStoreException() { // super(); // } // // public EventStoreException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreException(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreException(String message) { // super(message); // } // // public EventStoreException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/com/oasisdigital/nges/event/jdbc/EventLogDao.java import static java.util.stream.Collectors.toList; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import com.oasisdigital.nges.event.Event; import com.oasisdigital.nges.event.EventStoreException; package com.oasisdigital.nges.event.jdbc; class EventLogDao { private final JdbcQueries queries; public EventLogDao(ConnectionSource connectionSource) { this.queries = new JdbcQueries(connectionSource); }
public Event getEvent(long eventId) throws EventStoreException {
OasisDigital/nges
src/main/java/com/oasisdigital/nges/event/internal/EventStoreStatusPublisher.java
// Path: src/main/java/com/oasisdigital/nges/cluster/EventUpdate.java // public class EventUpdate implements Serializable { // private static final long serialVersionUID = 4220177459255722476L; // // private long eventId; // // public EventUpdate(long eventId) { // this.eventId = eventId; // } // // public long getEventId() { // return eventId; // } // } // // Path: src/main/java/com/oasisdigital/nges/cluster/MessageGroup.java // public interface MessageGroup { // // /** // * Publish a message to the group. // */ // public abstract void publish(Object message); // // /** // * Register a subscriber for messages from the group. See documentation for a particular implementation to // * learn more about its specifics. // */ // public abstract void registerSubscriber(Object subscriber); // // /** // * Unregister a subscriber from the group. // */ // public abstract void unregisterSubscriber(Object subscriber); // // }
import com.oasisdigital.nges.cluster.EventUpdate; import com.oasisdigital.nges.cluster.MessageGroup;
package com.oasisdigital.nges.event.internal; /** * Publishes notifications to {@link MessageGroup} about the ID of the most recent event ID. Prevents * publishing a number that is before the last published one in order to avoid the stream from going backwards * in case of concurrent calls (e.g. from heartbeat and event store). */ public class EventStoreStatusPublisher { private final MessageGroup messageGroup; private long lastEventId = 0; public EventStoreStatusPublisher(MessageGroup messageGroup) { this.messageGroup = messageGroup; } public synchronized void publishLastEventIfChanged(long eventId) { // It's OK to repeat the message (once could be lost, or a listener might join late), but the clock // cannot go backwards. if (lastEventId <= eventId) {
// Path: src/main/java/com/oasisdigital/nges/cluster/EventUpdate.java // public class EventUpdate implements Serializable { // private static final long serialVersionUID = 4220177459255722476L; // // private long eventId; // // public EventUpdate(long eventId) { // this.eventId = eventId; // } // // public long getEventId() { // return eventId; // } // } // // Path: src/main/java/com/oasisdigital/nges/cluster/MessageGroup.java // public interface MessageGroup { // // /** // * Publish a message to the group. // */ // public abstract void publish(Object message); // // /** // * Register a subscriber for messages from the group. See documentation for a particular implementation to // * learn more about its specifics. // */ // public abstract void registerSubscriber(Object subscriber); // // /** // * Unregister a subscriber from the group. // */ // public abstract void unregisterSubscriber(Object subscriber); // // } // Path: src/main/java/com/oasisdigital/nges/event/internal/EventStoreStatusPublisher.java import com.oasisdigital.nges.cluster.EventUpdate; import com.oasisdigital.nges.cluster.MessageGroup; package com.oasisdigital.nges.event.internal; /** * Publishes notifications to {@link MessageGroup} about the ID of the most recent event ID. Prevents * publishing a number that is before the last published one in order to avoid the stream from going backwards * in case of concurrent calls (e.g. from heartbeat and event store). */ public class EventStoreStatusPublisher { private final MessageGroup messageGroup; private long lastEventId = 0; public EventStoreStatusPublisher(MessageGroup messageGroup) { this.messageGroup = messageGroup; } public synchronized void publishLastEventIfChanged(long eventId) { // It's OK to repeat the message (once could be lost, or a listener might join late), but the clock // cannot go backwards. if (lastEventId <= eventId) {
messageGroup.publish(new EventUpdate(eventId));
OasisDigital/nges
src/main/java/com/oasisdigital/nges/event/jdbc/JdbcQueries.java
// Path: src/main/java/com/oasisdigital/nges/event/EventStoreException.java // public class EventStoreException extends RuntimeException { // // private static final long serialVersionUID = -1237680703226042282L; // // public EventStoreException() { // super(); // } // // public EventStoreException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreException(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreException(String message) { // super(message); // } // // public EventStoreException(Throwable cause) { // super(cause); // } // }
import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import com.oasisdigital.nges.event.EventStoreException;
package com.oasisdigital.nges.event.jdbc; class JdbcQueries { private final ConnectionSource connectionSource; public JdbcQueries(ConnectionSource connectionSource) { super(); this.connectionSource = connectionSource; } public <T> T queryForObject(String query, RowMapper<T> mapper, Object... params)
// Path: src/main/java/com/oasisdigital/nges/event/EventStoreException.java // public class EventStoreException extends RuntimeException { // // private static final long serialVersionUID = -1237680703226042282L; // // public EventStoreException() { // super(); // } // // public EventStoreException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreException(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreException(String message) { // super(message); // } // // public EventStoreException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/com/oasisdigital/nges/event/jdbc/JdbcQueries.java import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import com.oasisdigital.nges.event.EventStoreException; package com.oasisdigital.nges.event.jdbc; class JdbcQueries { private final ConnectionSource connectionSource; public JdbcQueries(ConnectionSource connectionSource) { super(); this.connectionSource = connectionSource; } public <T> T queryForObject(String query, RowMapper<T> mapper, Object... params)
throws EventStoreException {
OasisDigital/nges
src/test/java/com/oasisdigital/nges/event/TestSubscriber.java
// Path: src/main/java/com/oasisdigital/nges/cluster/EventUpdate.java // public class EventUpdate implements Serializable { // private static final long serialVersionUID = 4220177459255722476L; // // private long eventId; // // public EventUpdate(long eventId) { // this.eventId = eventId; // } // // public long getEventId() { // return eventId; // } // }
import com.google.common.eventbus.Subscribe; import com.oasisdigital.nges.cluster.EventUpdate;
package com.oasisdigital.nges.event; public class TestSubscriber { private long lastEvent; @Subscribe
// Path: src/main/java/com/oasisdigital/nges/cluster/EventUpdate.java // public class EventUpdate implements Serializable { // private static final long serialVersionUID = 4220177459255722476L; // // private long eventId; // // public EventUpdate(long eventId) { // this.eventId = eventId; // } // // public long getEventId() { // return eventId; // } // } // Path: src/test/java/com/oasisdigital/nges/event/TestSubscriber.java import com.google.common.eventbus.Subscribe; import com.oasisdigital.nges.cluster.EventUpdate; package com.oasisdigital.nges.event; public class TestSubscriber { private long lastEvent; @Subscribe
public void eventsPublished(EventUpdate eventUpdate) {
OasisDigital/nges
src/main/java/com/oasisdigital/nges/event/EventStoreStatusHeartbeat.java
// Path: src/main/java/com/oasisdigital/nges/cluster/EventUpdate.java // public class EventUpdate implements Serializable { // private static final long serialVersionUID = 4220177459255722476L; // // private long eventId; // // public EventUpdate(long eventId) { // this.eventId = eventId; // } // // public long getEventId() { // return eventId; // } // } // // Path: src/main/java/com/oasisdigital/nges/cluster/MessageGroup.java // public interface MessageGroup { // // /** // * Publish a message to the group. // */ // public abstract void publish(Object message); // // /** // * Register a subscriber for messages from the group. See documentation for a particular implementation to // * learn more about its specifics. // */ // public abstract void registerSubscriber(Object subscriber); // // /** // * Unregister a subscriber from the group. // */ // public abstract void unregisterSubscriber(Object subscriber); // // } // // Path: src/main/java/com/oasisdigital/nges/event/internal/EventStoreStatusPublisher.java // public class EventStoreStatusPublisher { // private final MessageGroup messageGroup; // // private long lastEventId = 0; // // public EventStoreStatusPublisher(MessageGroup messageGroup) { // this.messageGroup = messageGroup; // } // // public synchronized void publishLastEventIfChanged(long eventId) { // // It's OK to repeat the message (once could be lost, or a listener might join late), but the clock // // cannot go backwards. // if (lastEventId <= eventId) { // messageGroup.publish(new EventUpdate(eventId)); // lastEventId = eventId; // } // } // } // // Path: src/main/java/com/oasisdigital/nges/event/util/LogThrottle.java // public class LogThrottle { // private final Cache<String, Object> cache; // // public LogThrottle(long duration, TimeUnit timeUnit) { // this.cache = CacheBuilder.newBuilder().expireAfterWrite(duration, timeUnit).build(); // } // // /** // * // * @return true if the exception should be throttled (has been written recently). // */ // public boolean throttle(Exception exception) { // String exceptionStr = exception.toString(); // boolean throttled = cache.getIfPresent(exceptionStr) != null; // if (!throttled) { // cache.put(exceptionStr, new Object()); // } // return throttled; // } // }
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.oasisdigital.nges.cluster.EventUpdate; import com.oasisdigital.nges.cluster.MessageGroup; import com.oasisdigital.nges.event.internal.EventStoreStatusPublisher; import com.oasisdigital.nges.event.util.LogThrottle;
package com.oasisdigital.nges.event; /** * Periodically publishes {@link MessageGroup} notifications about the most recent event ID in the store. The * notifications are of {@link EventUpdate} type. * */ public class EventStoreStatusHeartbeat { protected final Logger log = LoggerFactory.getLogger(getClass()); private final EventStore eventStore;
// Path: src/main/java/com/oasisdigital/nges/cluster/EventUpdate.java // public class EventUpdate implements Serializable { // private static final long serialVersionUID = 4220177459255722476L; // // private long eventId; // // public EventUpdate(long eventId) { // this.eventId = eventId; // } // // public long getEventId() { // return eventId; // } // } // // Path: src/main/java/com/oasisdigital/nges/cluster/MessageGroup.java // public interface MessageGroup { // // /** // * Publish a message to the group. // */ // public abstract void publish(Object message); // // /** // * Register a subscriber for messages from the group. See documentation for a particular implementation to // * learn more about its specifics. // */ // public abstract void registerSubscriber(Object subscriber); // // /** // * Unregister a subscriber from the group. // */ // public abstract void unregisterSubscriber(Object subscriber); // // } // // Path: src/main/java/com/oasisdigital/nges/event/internal/EventStoreStatusPublisher.java // public class EventStoreStatusPublisher { // private final MessageGroup messageGroup; // // private long lastEventId = 0; // // public EventStoreStatusPublisher(MessageGroup messageGroup) { // this.messageGroup = messageGroup; // } // // public synchronized void publishLastEventIfChanged(long eventId) { // // It's OK to repeat the message (once could be lost, or a listener might join late), but the clock // // cannot go backwards. // if (lastEventId <= eventId) { // messageGroup.publish(new EventUpdate(eventId)); // lastEventId = eventId; // } // } // } // // Path: src/main/java/com/oasisdigital/nges/event/util/LogThrottle.java // public class LogThrottle { // private final Cache<String, Object> cache; // // public LogThrottle(long duration, TimeUnit timeUnit) { // this.cache = CacheBuilder.newBuilder().expireAfterWrite(duration, timeUnit).build(); // } // // /** // * // * @return true if the exception should be throttled (has been written recently). // */ // public boolean throttle(Exception exception) { // String exceptionStr = exception.toString(); // boolean throttled = cache.getIfPresent(exceptionStr) != null; // if (!throttled) { // cache.put(exceptionStr, new Object()); // } // return throttled; // } // } // Path: src/main/java/com/oasisdigital/nges/event/EventStoreStatusHeartbeat.java import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.oasisdigital.nges.cluster.EventUpdate; import com.oasisdigital.nges.cluster.MessageGroup; import com.oasisdigital.nges.event.internal.EventStoreStatusPublisher; import com.oasisdigital.nges.event.util.LogThrottle; package com.oasisdigital.nges.event; /** * Periodically publishes {@link MessageGroup} notifications about the most recent event ID in the store. The * notifications are of {@link EventUpdate} type. * */ public class EventStoreStatusHeartbeat { protected final Logger log = LoggerFactory.getLogger(getClass()); private final EventStore eventStore;
private final EventStoreStatusPublisher publisher;
OasisDigital/nges
src/main/java/com/oasisdigital/nges/event/EventStoreStatusHeartbeat.java
// Path: src/main/java/com/oasisdigital/nges/cluster/EventUpdate.java // public class EventUpdate implements Serializable { // private static final long serialVersionUID = 4220177459255722476L; // // private long eventId; // // public EventUpdate(long eventId) { // this.eventId = eventId; // } // // public long getEventId() { // return eventId; // } // } // // Path: src/main/java/com/oasisdigital/nges/cluster/MessageGroup.java // public interface MessageGroup { // // /** // * Publish a message to the group. // */ // public abstract void publish(Object message); // // /** // * Register a subscriber for messages from the group. See documentation for a particular implementation to // * learn more about its specifics. // */ // public abstract void registerSubscriber(Object subscriber); // // /** // * Unregister a subscriber from the group. // */ // public abstract void unregisterSubscriber(Object subscriber); // // } // // Path: src/main/java/com/oasisdigital/nges/event/internal/EventStoreStatusPublisher.java // public class EventStoreStatusPublisher { // private final MessageGroup messageGroup; // // private long lastEventId = 0; // // public EventStoreStatusPublisher(MessageGroup messageGroup) { // this.messageGroup = messageGroup; // } // // public synchronized void publishLastEventIfChanged(long eventId) { // // It's OK to repeat the message (once could be lost, or a listener might join late), but the clock // // cannot go backwards. // if (lastEventId <= eventId) { // messageGroup.publish(new EventUpdate(eventId)); // lastEventId = eventId; // } // } // } // // Path: src/main/java/com/oasisdigital/nges/event/util/LogThrottle.java // public class LogThrottle { // private final Cache<String, Object> cache; // // public LogThrottle(long duration, TimeUnit timeUnit) { // this.cache = CacheBuilder.newBuilder().expireAfterWrite(duration, timeUnit).build(); // } // // /** // * // * @return true if the exception should be throttled (has been written recently). // */ // public boolean throttle(Exception exception) { // String exceptionStr = exception.toString(); // boolean throttled = cache.getIfPresent(exceptionStr) != null; // if (!throttled) { // cache.put(exceptionStr, new Object()); // } // return throttled; // } // }
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.oasisdigital.nges.cluster.EventUpdate; import com.oasisdigital.nges.cluster.MessageGroup; import com.oasisdigital.nges.event.internal.EventStoreStatusPublisher; import com.oasisdigital.nges.event.util.LogThrottle;
package com.oasisdigital.nges.event; /** * Periodically publishes {@link MessageGroup} notifications about the most recent event ID in the store. The * notifications are of {@link EventUpdate} type. * */ public class EventStoreStatusHeartbeat { protected final Logger log = LoggerFactory.getLogger(getClass()); private final EventStore eventStore; private final EventStoreStatusPublisher publisher; private long initialDelayMs; private long pollingIntervalMs; private ScheduledExecutorService executor; public EventStoreStatusHeartbeat(EventStore eventStore, EventStoreStatusPublisher publisher) { this.eventStore = eventStore; this.publisher = publisher; } synchronized public void setInitialDelayMs(long initialDelayMs) { Preconditions.checkArgument(initialDelayMs >= 0); Preconditions.checkState(executor == null, "Must be called before initialize()"); this.initialDelayMs = initialDelayMs; } synchronized public void setPollingIntervalMs(long pollingIntervalMs) { Preconditions.checkArgument(pollingIntervalMs >= 0); Preconditions.checkState(executor == null, "Must be called before initialize()"); this.pollingIntervalMs = pollingIntervalMs; } synchronized public void initialize() { executor = Executors.newSingleThreadScheduledExecutor(); executor.scheduleAtFixedRate(catchAllAndLogWithThrottle(this::publishLastEvent), initialDelayMs, pollingIntervalMs, TimeUnit.MILLISECONDS); } private Runnable catchAllAndLogWithThrottle(Runnable r) {
// Path: src/main/java/com/oasisdigital/nges/cluster/EventUpdate.java // public class EventUpdate implements Serializable { // private static final long serialVersionUID = 4220177459255722476L; // // private long eventId; // // public EventUpdate(long eventId) { // this.eventId = eventId; // } // // public long getEventId() { // return eventId; // } // } // // Path: src/main/java/com/oasisdigital/nges/cluster/MessageGroup.java // public interface MessageGroup { // // /** // * Publish a message to the group. // */ // public abstract void publish(Object message); // // /** // * Register a subscriber for messages from the group. See documentation for a particular implementation to // * learn more about its specifics. // */ // public abstract void registerSubscriber(Object subscriber); // // /** // * Unregister a subscriber from the group. // */ // public abstract void unregisterSubscriber(Object subscriber); // // } // // Path: src/main/java/com/oasisdigital/nges/event/internal/EventStoreStatusPublisher.java // public class EventStoreStatusPublisher { // private final MessageGroup messageGroup; // // private long lastEventId = 0; // // public EventStoreStatusPublisher(MessageGroup messageGroup) { // this.messageGroup = messageGroup; // } // // public synchronized void publishLastEventIfChanged(long eventId) { // // It's OK to repeat the message (once could be lost, or a listener might join late), but the clock // // cannot go backwards. // if (lastEventId <= eventId) { // messageGroup.publish(new EventUpdate(eventId)); // lastEventId = eventId; // } // } // } // // Path: src/main/java/com/oasisdigital/nges/event/util/LogThrottle.java // public class LogThrottle { // private final Cache<String, Object> cache; // // public LogThrottle(long duration, TimeUnit timeUnit) { // this.cache = CacheBuilder.newBuilder().expireAfterWrite(duration, timeUnit).build(); // } // // /** // * // * @return true if the exception should be throttled (has been written recently). // */ // public boolean throttle(Exception exception) { // String exceptionStr = exception.toString(); // boolean throttled = cache.getIfPresent(exceptionStr) != null; // if (!throttled) { // cache.put(exceptionStr, new Object()); // } // return throttled; // } // } // Path: src/main/java/com/oasisdigital/nges/event/EventStoreStatusHeartbeat.java import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.oasisdigital.nges.cluster.EventUpdate; import com.oasisdigital.nges.cluster.MessageGroup; import com.oasisdigital.nges.event.internal.EventStoreStatusPublisher; import com.oasisdigital.nges.event.util.LogThrottle; package com.oasisdigital.nges.event; /** * Periodically publishes {@link MessageGroup} notifications about the most recent event ID in the store. The * notifications are of {@link EventUpdate} type. * */ public class EventStoreStatusHeartbeat { protected final Logger log = LoggerFactory.getLogger(getClass()); private final EventStore eventStore; private final EventStoreStatusPublisher publisher; private long initialDelayMs; private long pollingIntervalMs; private ScheduledExecutorService executor; public EventStoreStatusHeartbeat(EventStore eventStore, EventStoreStatusPublisher publisher) { this.eventStore = eventStore; this.publisher = publisher; } synchronized public void setInitialDelayMs(long initialDelayMs) { Preconditions.checkArgument(initialDelayMs >= 0); Preconditions.checkState(executor == null, "Must be called before initialize()"); this.initialDelayMs = initialDelayMs; } synchronized public void setPollingIntervalMs(long pollingIntervalMs) { Preconditions.checkArgument(pollingIntervalMs >= 0); Preconditions.checkState(executor == null, "Must be called before initialize()"); this.pollingIntervalMs = pollingIntervalMs; } synchronized public void initialize() { executor = Executors.newSingleThreadScheduledExecutor(); executor.scheduleAtFixedRate(catchAllAndLogWithThrottle(this::publishLastEvent), initialDelayMs, pollingIntervalMs, TimeUnit.MILLISECONDS); } private Runnable catchAllAndLogWithThrottle(Runnable r) {
LogThrottle throttle = new LogThrottle(1, TimeUnit.HOURS);
OasisDigital/nges
src/main/java/com/oasisdigital/nges/event/jdbc/ConnectionSource.java
// Path: src/main/java/com/oasisdigital/nges/event/EventStoreException.java // public class EventStoreException extends RuntimeException { // // private static final long serialVersionUID = -1237680703226042282L; // // public EventStoreException() { // super(); // } // // public EventStoreException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreException(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreException(String message) { // super(message); // } // // public EventStoreException(Throwable cause) { // super(cause); // } // }
import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import com.oasisdigital.nges.event.EventStoreException;
package com.oasisdigital.nges.event.jdbc; class ConnectionSource { private final ThreadLocal<Connection> connection; private final DataSource dataSource; public ConnectionSource(DataSource dataSource) { this.connection = new ThreadLocal<>(); this.dataSource = dataSource; }
// Path: src/main/java/com/oasisdigital/nges/event/EventStoreException.java // public class EventStoreException extends RuntimeException { // // private static final long serialVersionUID = -1237680703226042282L; // // public EventStoreException() { // super(); // } // // public EventStoreException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreException(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreException(String message) { // super(message); // } // // public EventStoreException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/com/oasisdigital/nges/event/jdbc/ConnectionSource.java import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import com.oasisdigital.nges.event.EventStoreException; package com.oasisdigital.nges.event.jdbc; class ConnectionSource { private final ThreadLocal<Connection> connection; private final DataSource dataSource; public ConnectionSource(DataSource dataSource) { this.connection = new ThreadLocal<>(); this.dataSource = dataSource; }
public <T> T withConnection(Callback<T> callback) throws EventStoreException {
OasisDigital/nges
src/main/java/com/oasisdigital/nges/event/jdbc/EventStreamListDao.java
// Path: src/main/java/com/oasisdigital/nges/event/EventStoreConflict.java // public class EventStoreConflict extends EventStoreException { // private static final long serialVersionUID = 1L; // // public EventStoreConflict() { // super(); // } // // public EventStoreConflict(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreConflict(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreConflict(String message) { // super(message); // } // // public EventStoreConflict(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/oasisdigital/nges/event/EventStream.java // public class EventStream { // private UUID streamId; // private String streamType; // private Long lastEventId; // private OffsetDateTime lastTransactionTime; // private Long lastSeqNo; // // public UUID getStreamId() { // return streamId; // } // // public void setStreamId(UUID streamId) { // this.streamId = streamId; // } // // public String getStreamType() { // return streamType; // } // // public void setStreamType(String streamType) { // this.streamType = streamType; // } // // public Long getLastEventId() { // return lastEventId; // } // // public void setLastEventId(Long lastEventId) { // this.lastEventId = lastEventId; // } // // public OffsetDateTime getLastTransactionTime() { // return lastTransactionTime; // } // // public void setLastTransactionTime(OffsetDateTime lastTransactionTime) { // this.lastTransactionTime = lastTransactionTime; // } // // public Long getLastSeqNo() { // return lastSeqNo; // } // // public void setLastSeqNo(Long lastSeqNo) { // this.lastSeqNo = lastSeqNo; // } // // } // // Path: src/main/java/com/oasisdigital/nges/event/EventStoreException.java // public class EventStoreException extends RuntimeException { // // private static final long serialVersionUID = -1237680703226042282L; // // public EventStoreException() { // super(); // } // // public EventStoreException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreException(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreException(String message) { // super(message); // } // // public EventStoreException(Throwable cause) { // super(cause); // } // }
import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; import com.oasisdigital.nges.event.EventStoreConflict; import com.oasisdigital.nges.event.EventStream; import com.oasisdigital.nges.event.EventStoreException;
package com.oasisdigital.nges.event.jdbc; class EventStreamListDao { private final JdbcQueries queries; public EventStreamListDao(ConnectionSource connectionSource) { this.queries = new JdbcQueries(connectionSource); } /** * * @param streamId * @param lastEventId * ID of the last (new) event for the stream * @param lastSequence * sequence number of the last (new) event for the stream * @param expectedSequence * sequence number that the update should be applied to; use "0" to indicate a new sequence * @throws EventStoreException */ public void update(UUID streamId, long lastEventId, long lastSequence, long expectedSequence)
// Path: src/main/java/com/oasisdigital/nges/event/EventStoreConflict.java // public class EventStoreConflict extends EventStoreException { // private static final long serialVersionUID = 1L; // // public EventStoreConflict() { // super(); // } // // public EventStoreConflict(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreConflict(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreConflict(String message) { // super(message); // } // // public EventStoreConflict(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/oasisdigital/nges/event/EventStream.java // public class EventStream { // private UUID streamId; // private String streamType; // private Long lastEventId; // private OffsetDateTime lastTransactionTime; // private Long lastSeqNo; // // public UUID getStreamId() { // return streamId; // } // // public void setStreamId(UUID streamId) { // this.streamId = streamId; // } // // public String getStreamType() { // return streamType; // } // // public void setStreamType(String streamType) { // this.streamType = streamType; // } // // public Long getLastEventId() { // return lastEventId; // } // // public void setLastEventId(Long lastEventId) { // this.lastEventId = lastEventId; // } // // public OffsetDateTime getLastTransactionTime() { // return lastTransactionTime; // } // // public void setLastTransactionTime(OffsetDateTime lastTransactionTime) { // this.lastTransactionTime = lastTransactionTime; // } // // public Long getLastSeqNo() { // return lastSeqNo; // } // // public void setLastSeqNo(Long lastSeqNo) { // this.lastSeqNo = lastSeqNo; // } // // } // // Path: src/main/java/com/oasisdigital/nges/event/EventStoreException.java // public class EventStoreException extends RuntimeException { // // private static final long serialVersionUID = -1237680703226042282L; // // public EventStoreException() { // super(); // } // // public EventStoreException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreException(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreException(String message) { // super(message); // } // // public EventStoreException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/com/oasisdigital/nges/event/jdbc/EventStreamListDao.java import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; import com.oasisdigital.nges.event.EventStoreConflict; import com.oasisdigital.nges.event.EventStream; import com.oasisdigital.nges.event.EventStoreException; package com.oasisdigital.nges.event.jdbc; class EventStreamListDao { private final JdbcQueries queries; public EventStreamListDao(ConnectionSource connectionSource) { this.queries = new JdbcQueries(connectionSource); } /** * * @param streamId * @param lastEventId * ID of the last (new) event for the stream * @param lastSequence * sequence number of the last (new) event for the stream * @param expectedSequence * sequence number that the update should be applied to; use "0" to indicate a new sequence * @throws EventStoreException */ public void update(UUID streamId, long lastEventId, long lastSequence, long expectedSequence)
throws EventStoreException {
OasisDigital/nges
src/main/java/com/oasisdigital/nges/event/jdbc/EventStreamListDao.java
// Path: src/main/java/com/oasisdigital/nges/event/EventStoreConflict.java // public class EventStoreConflict extends EventStoreException { // private static final long serialVersionUID = 1L; // // public EventStoreConflict() { // super(); // } // // public EventStoreConflict(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreConflict(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreConflict(String message) { // super(message); // } // // public EventStoreConflict(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/oasisdigital/nges/event/EventStream.java // public class EventStream { // private UUID streamId; // private String streamType; // private Long lastEventId; // private OffsetDateTime lastTransactionTime; // private Long lastSeqNo; // // public UUID getStreamId() { // return streamId; // } // // public void setStreamId(UUID streamId) { // this.streamId = streamId; // } // // public String getStreamType() { // return streamType; // } // // public void setStreamType(String streamType) { // this.streamType = streamType; // } // // public Long getLastEventId() { // return lastEventId; // } // // public void setLastEventId(Long lastEventId) { // this.lastEventId = lastEventId; // } // // public OffsetDateTime getLastTransactionTime() { // return lastTransactionTime; // } // // public void setLastTransactionTime(OffsetDateTime lastTransactionTime) { // this.lastTransactionTime = lastTransactionTime; // } // // public Long getLastSeqNo() { // return lastSeqNo; // } // // public void setLastSeqNo(Long lastSeqNo) { // this.lastSeqNo = lastSeqNo; // } // // } // // Path: src/main/java/com/oasisdigital/nges/event/EventStoreException.java // public class EventStoreException extends RuntimeException { // // private static final long serialVersionUID = -1237680703226042282L; // // public EventStoreException() { // super(); // } // // public EventStoreException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreException(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreException(String message) { // super(message); // } // // public EventStoreException(Throwable cause) { // super(cause); // } // }
import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; import com.oasisdigital.nges.event.EventStoreConflict; import com.oasisdigital.nges.event.EventStream; import com.oasisdigital.nges.event.EventStoreException;
package com.oasisdigital.nges.event.jdbc; class EventStreamListDao { private final JdbcQueries queries; public EventStreamListDao(ConnectionSource connectionSource) { this.queries = new JdbcQueries(connectionSource); } /** * * @param streamId * @param lastEventId * ID of the last (new) event for the stream * @param lastSequence * sequence number of the last (new) event for the stream * @param expectedSequence * sequence number that the update should be applied to; use "0" to indicate a new sequence * @throws EventStoreException */ public void update(UUID streamId, long lastEventId, long lastSequence, long expectedSequence) throws EventStoreException { // @formatter:off int updated = queries.update( "update event_stream_list set " + " last_event_id = ?, " + " last_transaction_time = current_timestamp, " + " last_seq_no = ? " + "where stream_id = ? and coalesce(last_seq_no, 0) = ?", lastEventId, lastSequence, streamId, expectedSequence); // @formatter:on if (updated == 0) {
// Path: src/main/java/com/oasisdigital/nges/event/EventStoreConflict.java // public class EventStoreConflict extends EventStoreException { // private static final long serialVersionUID = 1L; // // public EventStoreConflict() { // super(); // } // // public EventStoreConflict(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreConflict(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreConflict(String message) { // super(message); // } // // public EventStoreConflict(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/oasisdigital/nges/event/EventStream.java // public class EventStream { // private UUID streamId; // private String streamType; // private Long lastEventId; // private OffsetDateTime lastTransactionTime; // private Long lastSeqNo; // // public UUID getStreamId() { // return streamId; // } // // public void setStreamId(UUID streamId) { // this.streamId = streamId; // } // // public String getStreamType() { // return streamType; // } // // public void setStreamType(String streamType) { // this.streamType = streamType; // } // // public Long getLastEventId() { // return lastEventId; // } // // public void setLastEventId(Long lastEventId) { // this.lastEventId = lastEventId; // } // // public OffsetDateTime getLastTransactionTime() { // return lastTransactionTime; // } // // public void setLastTransactionTime(OffsetDateTime lastTransactionTime) { // this.lastTransactionTime = lastTransactionTime; // } // // public Long getLastSeqNo() { // return lastSeqNo; // } // // public void setLastSeqNo(Long lastSeqNo) { // this.lastSeqNo = lastSeqNo; // } // // } // // Path: src/main/java/com/oasisdigital/nges/event/EventStoreException.java // public class EventStoreException extends RuntimeException { // // private static final long serialVersionUID = -1237680703226042282L; // // public EventStoreException() { // super(); // } // // public EventStoreException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreException(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreException(String message) { // super(message); // } // // public EventStoreException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/com/oasisdigital/nges/event/jdbc/EventStreamListDao.java import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; import com.oasisdigital.nges.event.EventStoreConflict; import com.oasisdigital.nges.event.EventStream; import com.oasisdigital.nges.event.EventStoreException; package com.oasisdigital.nges.event.jdbc; class EventStreamListDao { private final JdbcQueries queries; public EventStreamListDao(ConnectionSource connectionSource) { this.queries = new JdbcQueries(connectionSource); } /** * * @param streamId * @param lastEventId * ID of the last (new) event for the stream * @param lastSequence * sequence number of the last (new) event for the stream * @param expectedSequence * sequence number that the update should be applied to; use "0" to indicate a new sequence * @throws EventStoreException */ public void update(UUID streamId, long lastEventId, long lastSequence, long expectedSequence) throws EventStoreException { // @formatter:off int updated = queries.update( "update event_stream_list set " + " last_event_id = ?, " + " last_transaction_time = current_timestamp, " + " last_seq_no = ? " + "where stream_id = ? and coalesce(last_seq_no, 0) = ?", lastEventId, lastSequence, streamId, expectedSequence); // @formatter:on if (updated == 0) {
throw new EventStoreConflict("Uninitialized stream or concurrent modification: " + streamId);
OasisDigital/nges
src/main/java/com/oasisdigital/nges/event/jdbc/EventStreamListDao.java
// Path: src/main/java/com/oasisdigital/nges/event/EventStoreConflict.java // public class EventStoreConflict extends EventStoreException { // private static final long serialVersionUID = 1L; // // public EventStoreConflict() { // super(); // } // // public EventStoreConflict(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreConflict(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreConflict(String message) { // super(message); // } // // public EventStoreConflict(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/oasisdigital/nges/event/EventStream.java // public class EventStream { // private UUID streamId; // private String streamType; // private Long lastEventId; // private OffsetDateTime lastTransactionTime; // private Long lastSeqNo; // // public UUID getStreamId() { // return streamId; // } // // public void setStreamId(UUID streamId) { // this.streamId = streamId; // } // // public String getStreamType() { // return streamType; // } // // public void setStreamType(String streamType) { // this.streamType = streamType; // } // // public Long getLastEventId() { // return lastEventId; // } // // public void setLastEventId(Long lastEventId) { // this.lastEventId = lastEventId; // } // // public OffsetDateTime getLastTransactionTime() { // return lastTransactionTime; // } // // public void setLastTransactionTime(OffsetDateTime lastTransactionTime) { // this.lastTransactionTime = lastTransactionTime; // } // // public Long getLastSeqNo() { // return lastSeqNo; // } // // public void setLastSeqNo(Long lastSeqNo) { // this.lastSeqNo = lastSeqNo; // } // // } // // Path: src/main/java/com/oasisdigital/nges/event/EventStoreException.java // public class EventStoreException extends RuntimeException { // // private static final long serialVersionUID = -1237680703226042282L; // // public EventStoreException() { // super(); // } // // public EventStoreException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreException(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreException(String message) { // super(message); // } // // public EventStoreException(Throwable cause) { // super(cause); // } // }
import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; import com.oasisdigital.nges.event.EventStoreConflict; import com.oasisdigital.nges.event.EventStream; import com.oasisdigital.nges.event.EventStoreException;
package com.oasisdigital.nges.event.jdbc; class EventStreamListDao { private final JdbcQueries queries; public EventStreamListDao(ConnectionSource connectionSource) { this.queries = new JdbcQueries(connectionSource); } /** * * @param streamId * @param lastEventId * ID of the last (new) event for the stream * @param lastSequence * sequence number of the last (new) event for the stream * @param expectedSequence * sequence number that the update should be applied to; use "0" to indicate a new sequence * @throws EventStoreException */ public void update(UUID streamId, long lastEventId, long lastSequence, long expectedSequence) throws EventStoreException { // @formatter:off int updated = queries.update( "update event_stream_list set " + " last_event_id = ?, " + " last_transaction_time = current_timestamp, " + " last_seq_no = ? " + "where stream_id = ? and coalesce(last_seq_no, 0) = ?", lastEventId, lastSequence, streamId, expectedSequence); // @formatter:on if (updated == 0) { throw new EventStoreConflict("Uninitialized stream or concurrent modification: " + streamId); } }
// Path: src/main/java/com/oasisdigital/nges/event/EventStoreConflict.java // public class EventStoreConflict extends EventStoreException { // private static final long serialVersionUID = 1L; // // public EventStoreConflict() { // super(); // } // // public EventStoreConflict(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreConflict(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreConflict(String message) { // super(message); // } // // public EventStoreConflict(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/oasisdigital/nges/event/EventStream.java // public class EventStream { // private UUID streamId; // private String streamType; // private Long lastEventId; // private OffsetDateTime lastTransactionTime; // private Long lastSeqNo; // // public UUID getStreamId() { // return streamId; // } // // public void setStreamId(UUID streamId) { // this.streamId = streamId; // } // // public String getStreamType() { // return streamType; // } // // public void setStreamType(String streamType) { // this.streamType = streamType; // } // // public Long getLastEventId() { // return lastEventId; // } // // public void setLastEventId(Long lastEventId) { // this.lastEventId = lastEventId; // } // // public OffsetDateTime getLastTransactionTime() { // return lastTransactionTime; // } // // public void setLastTransactionTime(OffsetDateTime lastTransactionTime) { // this.lastTransactionTime = lastTransactionTime; // } // // public Long getLastSeqNo() { // return lastSeqNo; // } // // public void setLastSeqNo(Long lastSeqNo) { // this.lastSeqNo = lastSeqNo; // } // // } // // Path: src/main/java/com/oasisdigital/nges/event/EventStoreException.java // public class EventStoreException extends RuntimeException { // // private static final long serialVersionUID = -1237680703226042282L; // // public EventStoreException() { // super(); // } // // public EventStoreException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreException(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreException(String message) { // super(message); // } // // public EventStoreException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/com/oasisdigital/nges/event/jdbc/EventStreamListDao.java import java.sql.ResultSet; import java.sql.SQLException; import java.util.UUID; import com.oasisdigital.nges.event.EventStoreConflict; import com.oasisdigital.nges.event.EventStream; import com.oasisdigital.nges.event.EventStoreException; package com.oasisdigital.nges.event.jdbc; class EventStreamListDao { private final JdbcQueries queries; public EventStreamListDao(ConnectionSource connectionSource) { this.queries = new JdbcQueries(connectionSource); } /** * * @param streamId * @param lastEventId * ID of the last (new) event for the stream * @param lastSequence * sequence number of the last (new) event for the stream * @param expectedSequence * sequence number that the update should be applied to; use "0" to indicate a new sequence * @throws EventStoreException */ public void update(UUID streamId, long lastEventId, long lastSequence, long expectedSequence) throws EventStoreException { // @formatter:off int updated = queries.update( "update event_stream_list set " + " last_event_id = ?, " + " last_transaction_time = current_timestamp, " + " last_seq_no = ? " + "where stream_id = ? and coalesce(last_seq_no, 0) = ?", lastEventId, lastSequence, streamId, expectedSequence); // @formatter:on if (updated == 0) { throw new EventStoreConflict("Uninitialized stream or concurrent modification: " + streamId); } }
public EventStream findByStreamId(UUID id) throws EventStoreException {
OasisDigital/nges
src/main/java/com/oasisdigital/nges/event/jdbc/ResultSetMapper.java
// Path: src/main/java/com/oasisdigital/nges/event/EventStoreException.java // public class EventStoreException extends RuntimeException { // // private static final long serialVersionUID = -1237680703226042282L; // // public EventStoreException() { // super(); // } // // public EventStoreException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreException(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreException(String message) { // super(message); // } // // public EventStoreException(Throwable cause) { // super(cause); // } // }
import java.sql.ResultSet; import java.sql.SQLException; import com.oasisdigital.nges.event.EventStoreException;
package com.oasisdigital.nges.event.jdbc; @FunctionalInterface interface ResultSetMapper<T> {
// Path: src/main/java/com/oasisdigital/nges/event/EventStoreException.java // public class EventStoreException extends RuntimeException { // // private static final long serialVersionUID = -1237680703226042282L; // // public EventStoreException() { // super(); // } // // public EventStoreException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public EventStoreException(String message, Throwable cause) { // super(message, cause); // } // // public EventStoreException(String message) { // super(message); // } // // public EventStoreException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/com/oasisdigital/nges/event/jdbc/ResultSetMapper.java import java.sql.ResultSet; import java.sql.SQLException; import com.oasisdigital.nges.event.EventStoreException; package com.oasisdigital.nges.event.jdbc; @FunctionalInterface interface ResultSetMapper<T> {
public T mapResultSet(ResultSet rs) throws SQLException, EventStoreException;
shibing624/similarity
src/test/java/org/xm/similarity/dictionary/CilinDictionaryTest.java
// Path: src/main/java/org/xm/similarity/word/clin/CilinDictionary.java // public class CilinDictionary { // private static Logger logger = LoggerFactory.getLogger(CilinDictionary.class); // private final static String path = Similarity.Config.CilinPath; // // 以词语为索引 // private final Map<String, Set<String>> wordIndex = new HashMap<>(); // // 以编码为索引 // private final Map<String, Set<String>> codeIndex = new HashMap<>(); // private static CilinDictionary instance; // // public static CilinDictionary getInstance() { // if (instance == null) { // try { // instance = new CilinDictionary(); // } catch (IOException e) { // logger.error("exception:{}", e.getMessage()); // } // } // return instance; // } // // private CilinDictionary() throws IOException { // InputStream inputStream = new GZIPInputStream(DicReader.getInputStream(path)); // TraverseEvent<String> event = line -> { // String[] items = line.split(" "); // Set<String> set = new HashSet<>(); // for (int i = 2; i < items.length; i++) { // String code = items[i].trim(); // if (StringUtil.isNotBlank(code)) { // set.add(code); // // add to codeIndex // Set<String> codeWords = codeIndex.get(code); // if (codeWords == null) { // codeWords = new HashSet<>(); // } // codeWords.add(items[0]); // codeIndex.put(code, codeWords); // } // } // wordIndex.put(items[0], set); // return false; // }; // logger.info("loading cilin dictionary..."); // long start = System.currentTimeMillis(); // FileUtil.traverseLines(inputStream, "UTF-8", event); // logger.info("loading ciling dictionary complete! time spend:{}", System.currentTimeMillis() - start + "ms"); // } // // /** // * 获取某词语的词林编码,一个词语可以对应多个编码,set表示 // * // * @param word // * @return // */ // public Set<String> getCilinCodes(String word) { // return wordIndex.get(word); // } // // public Set<String> getCilinWords(String code) { // return codeIndex.get(code); // } // // }
import org.junit.Before; import org.junit.Test; import org.xm.similarity.word.clin.CilinDictionary;
package org.xm.similarity.dictionary; /** * @author xuming */ public class CilinDictionaryTest { String code = "";
// Path: src/main/java/org/xm/similarity/word/clin/CilinDictionary.java // public class CilinDictionary { // private static Logger logger = LoggerFactory.getLogger(CilinDictionary.class); // private final static String path = Similarity.Config.CilinPath; // // 以词语为索引 // private final Map<String, Set<String>> wordIndex = new HashMap<>(); // // 以编码为索引 // private final Map<String, Set<String>> codeIndex = new HashMap<>(); // private static CilinDictionary instance; // // public static CilinDictionary getInstance() { // if (instance == null) { // try { // instance = new CilinDictionary(); // } catch (IOException e) { // logger.error("exception:{}", e.getMessage()); // } // } // return instance; // } // // private CilinDictionary() throws IOException { // InputStream inputStream = new GZIPInputStream(DicReader.getInputStream(path)); // TraverseEvent<String> event = line -> { // String[] items = line.split(" "); // Set<String> set = new HashSet<>(); // for (int i = 2; i < items.length; i++) { // String code = items[i].trim(); // if (StringUtil.isNotBlank(code)) { // set.add(code); // // add to codeIndex // Set<String> codeWords = codeIndex.get(code); // if (codeWords == null) { // codeWords = new HashSet<>(); // } // codeWords.add(items[0]); // codeIndex.put(code, codeWords); // } // } // wordIndex.put(items[0], set); // return false; // }; // logger.info("loading cilin dictionary..."); // long start = System.currentTimeMillis(); // FileUtil.traverseLines(inputStream, "UTF-8", event); // logger.info("loading ciling dictionary complete! time spend:{}", System.currentTimeMillis() - start + "ms"); // } // // /** // * 获取某词语的词林编码,一个词语可以对应多个编码,set表示 // * // * @param word // * @return // */ // public Set<String> getCilinCodes(String word) { // return wordIndex.get(word); // } // // public Set<String> getCilinWords(String code) { // return codeIndex.get(code); // } // // } // Path: src/test/java/org/xm/similarity/dictionary/CilinDictionaryTest.java import org.junit.Before; import org.junit.Test; import org.xm.similarity.word.clin.CilinDictionary; package org.xm.similarity.dictionary; /** * @author xuming */ public class CilinDictionaryTest { String code = "";
CilinDictionary dictionary;
shibing624/similarity
src/main/java/org/xm/word2vec/vec/Huffman.java
// Path: src/main/java/org/xm/word2vec/domain/HiddenNeuron.java // public class HiddenNeuron extends Neuron { // public double[] syn1;// 隐藏层 -> 输出层 // // public HiddenNeuron(int layerSize) { // syn1 = new double[layerSize]; // } // } // // Path: src/main/java/org/xm/word2vec/domain/Neuron.java // public abstract class Neuron implements Comparable<Neuron> { // public double freq; // public Neuron parent; // public int code; // public int category = -1; // // @Override // public int compareTo(Neuron o) { // if (this.category == o.category) { // if (this.freq > o.freq) { // return 1; // } else // return -1; // } else if (this.category > o.category) { // return 1; // } else { // return 0; // } // } // }
import org.xm.word2vec.domain.HiddenNeuron; import org.xm.word2vec.domain.Neuron; import java.util.Collection; import java.util.TreeSet;
package org.xm.word2vec.vec; /** * huffman编码 * * @author xuming */ public class Huffman { private int layerSize; public Huffman(int layerSize) { this.layerSize = layerSize; }
// Path: src/main/java/org/xm/word2vec/domain/HiddenNeuron.java // public class HiddenNeuron extends Neuron { // public double[] syn1;// 隐藏层 -> 输出层 // // public HiddenNeuron(int layerSize) { // syn1 = new double[layerSize]; // } // } // // Path: src/main/java/org/xm/word2vec/domain/Neuron.java // public abstract class Neuron implements Comparable<Neuron> { // public double freq; // public Neuron parent; // public int code; // public int category = -1; // // @Override // public int compareTo(Neuron o) { // if (this.category == o.category) { // if (this.freq > o.freq) { // return 1; // } else // return -1; // } else if (this.category > o.category) { // return 1; // } else { // return 0; // } // } // } // Path: src/main/java/org/xm/word2vec/vec/Huffman.java import org.xm.word2vec.domain.HiddenNeuron; import org.xm.word2vec.domain.Neuron; import java.util.Collection; import java.util.TreeSet; package org.xm.word2vec.vec; /** * huffman编码 * * @author xuming */ public class Huffman { private int layerSize; public Huffman(int layerSize) { this.layerSize = layerSize; }
private TreeSet<Neuron> set = new TreeSet<>();
shibing624/similarity
src/main/java/org/xm/word2vec/vec/Huffman.java
// Path: src/main/java/org/xm/word2vec/domain/HiddenNeuron.java // public class HiddenNeuron extends Neuron { // public double[] syn1;// 隐藏层 -> 输出层 // // public HiddenNeuron(int layerSize) { // syn1 = new double[layerSize]; // } // } // // Path: src/main/java/org/xm/word2vec/domain/Neuron.java // public abstract class Neuron implements Comparable<Neuron> { // public double freq; // public Neuron parent; // public int code; // public int category = -1; // // @Override // public int compareTo(Neuron o) { // if (this.category == o.category) { // if (this.freq > o.freq) { // return 1; // } else // return -1; // } else if (this.category > o.category) { // return 1; // } else { // return 0; // } // } // }
import org.xm.word2vec.domain.HiddenNeuron; import org.xm.word2vec.domain.Neuron; import java.util.Collection; import java.util.TreeSet;
package org.xm.word2vec.vec; /** * huffman编码 * * @author xuming */ public class Huffman { private int layerSize; public Huffman(int layerSize) { this.layerSize = layerSize; } private TreeSet<Neuron> set = new TreeSet<>(); public void buildTree(Collection<Neuron> neurons) { set.addAll(neurons); while (set.size() > 1) { merge(); } } private void merge() {
// Path: src/main/java/org/xm/word2vec/domain/HiddenNeuron.java // public class HiddenNeuron extends Neuron { // public double[] syn1;// 隐藏层 -> 输出层 // // public HiddenNeuron(int layerSize) { // syn1 = new double[layerSize]; // } // } // // Path: src/main/java/org/xm/word2vec/domain/Neuron.java // public abstract class Neuron implements Comparable<Neuron> { // public double freq; // public Neuron parent; // public int code; // public int category = -1; // // @Override // public int compareTo(Neuron o) { // if (this.category == o.category) { // if (this.freq > o.freq) { // return 1; // } else // return -1; // } else if (this.category > o.category) { // return 1; // } else { // return 0; // } // } // } // Path: src/main/java/org/xm/word2vec/vec/Huffman.java import org.xm.word2vec.domain.HiddenNeuron; import org.xm.word2vec.domain.Neuron; import java.util.Collection; import java.util.TreeSet; package org.xm.word2vec.vec; /** * huffman编码 * * @author xuming */ public class Huffman { private int layerSize; public Huffman(int layerSize) { this.layerSize = layerSize; } private TreeSet<Neuron> set = new TreeSet<>(); public void buildTree(Collection<Neuron> neurons) { set.addAll(neurons); while (set.size() > 1) { merge(); } } private void merge() {
HiddenNeuron hn = new HiddenNeuron(layerSize);
shibing624/similarity
src/main/java/org/xm/similarity/text/JaccardTextSimilarity.java
// Path: src/main/java/org/xm/tokenizer/Word.java // public class Word implements Comparable { // // 词名 // private String name; // // 词性 // private String pos; // // 权重,用于词向量分析 // private Float weight; // private int frequency; // // public Word(String name) { // this.name = name; // } // // public Word(String name, String pos) { // this.name = name; // this.pos = pos; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPos() { // return pos; // } // // public void setPos(String pos) { // this.pos = pos; // } // // public Float getWeight() { // return weight; // } // // public void setWeight(Float weight) { // this.weight = weight; // } // // public int getFrequency() { // return frequency; // } // // public void setFrequency(int frequency) { // this.frequency = frequency; // } // // @Override // public int hashCode() { // return Objects.hashCode(this.name); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final Word other = (Word) obj; // return Objects.equals(this.name, other.name); // } // // public String toString(String split) { // if (HanLP.Config.ShowTermNature) // return name + split + pos; // return name; // } // // @Override // public String toString() { // StringBuilder str = new StringBuilder(); // if (name != null) { // str.append(name); // } // if (pos != null) { // str.append("/").append(pos); // } // if (frequency > 0) { // str.append("/").append(frequency); // } // return str.toString(); // } // // @Override // public int compareTo(Object o) { // if (this == o) { // return 0; // } // if (this.name == null) { // return -1; // } // if (o == null) { // return 1; // } // if (!(o instanceof Word)) { // return 1; // } // String t = ((Word) o).getName(); // if (t == null) { // return 1; // } // return this.name.compareTo(t); // } // }
import org.xm.tokenizer.Word; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentSkipListSet;
/** * APDPlat - Application Product Development Platform * Copyright (c) 2013, 杨尚川, yang-shangchuan@qq.com * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p> * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.xm.similarity.text; /** * 文本相似度计算 * 判定方式:Jaccard相似性系数(Jaccard similarity coefficient) ,通过计算两个集合交集的大小除以并集的大小来评估他们的相似度 * 算法步骤描述: * 1、分词 * 2、求交集(去重),计算交集的不重复词的个数 intersectionSize * 3、求并集(去重),计算并集的不重复词的个数 unionSize * 4、2中的值除以3中的值 intersectionSize/(double)unionSize * 完整计算公式: * double score = intersectionSize/(double)unionSize; * @author 杨尚川 */ public class JaccardTextSimilarity extends TextSimilarity { /** * 判定相似度的方式:Jaccard相似性系数 * @param words1 词列表1 * @param words2 词列表2 * @return 相似度分值 */ @Override
// Path: src/main/java/org/xm/tokenizer/Word.java // public class Word implements Comparable { // // 词名 // private String name; // // 词性 // private String pos; // // 权重,用于词向量分析 // private Float weight; // private int frequency; // // public Word(String name) { // this.name = name; // } // // public Word(String name, String pos) { // this.name = name; // this.pos = pos; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPos() { // return pos; // } // // public void setPos(String pos) { // this.pos = pos; // } // // public Float getWeight() { // return weight; // } // // public void setWeight(Float weight) { // this.weight = weight; // } // // public int getFrequency() { // return frequency; // } // // public void setFrequency(int frequency) { // this.frequency = frequency; // } // // @Override // public int hashCode() { // return Objects.hashCode(this.name); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final Word other = (Word) obj; // return Objects.equals(this.name, other.name); // } // // public String toString(String split) { // if (HanLP.Config.ShowTermNature) // return name + split + pos; // return name; // } // // @Override // public String toString() { // StringBuilder str = new StringBuilder(); // if (name != null) { // str.append(name); // } // if (pos != null) { // str.append("/").append(pos); // } // if (frequency > 0) { // str.append("/").append(frequency); // } // return str.toString(); // } // // @Override // public int compareTo(Object o) { // if (this == o) { // return 0; // } // if (this.name == null) { // return -1; // } // if (o == null) { // return 1; // } // if (!(o instanceof Word)) { // return 1; // } // String t = ((Word) o).getName(); // if (t == null) { // return 1; // } // return this.name.compareTo(t); // } // } // Path: src/main/java/org/xm/similarity/text/JaccardTextSimilarity.java import org.xm.tokenizer.Word; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentSkipListSet; /** * APDPlat - Application Product Development Platform * Copyright (c) 2013, 杨尚川, yang-shangchuan@qq.com * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p> * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.xm.similarity.text; /** * 文本相似度计算 * 判定方式:Jaccard相似性系数(Jaccard similarity coefficient) ,通过计算两个集合交集的大小除以并集的大小来评估他们的相似度 * 算法步骤描述: * 1、分词 * 2、求交集(去重),计算交集的不重复词的个数 intersectionSize * 3、求并集(去重),计算并集的不重复词的个数 unionSize * 4、2中的值除以3中的值 intersectionSize/(double)unionSize * 完整计算公式: * double score = intersectionSize/(double)unionSize; * @author 杨尚川 */ public class JaccardTextSimilarity extends TextSimilarity { /** * 判定相似度的方式:Jaccard相似性系数 * @param words1 词列表1 * @param words2 词列表2 * @return 相似度分值 */ @Override
protected double getSimilarityImpl(List<Word> words1, List<Word> words2) {
shibing624/similarity
src/main/java/org/xm/similarity/text/ITextSimilarity.java
// Path: src/main/java/org/xm/similarity/ISimilarity.java // public interface ISimilarity { // /** // * 计算相似度 // * // * @param word1 词语1 // * @param word2 词语2 // * @return 相似度值 // */ // double getSimilarity(String word1, String word2); // } // // Path: src/main/java/org/xm/tokenizer/Word.java // public class Word implements Comparable { // // 词名 // private String name; // // 词性 // private String pos; // // 权重,用于词向量分析 // private Float weight; // private int frequency; // // public Word(String name) { // this.name = name; // } // // public Word(String name, String pos) { // this.name = name; // this.pos = pos; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPos() { // return pos; // } // // public void setPos(String pos) { // this.pos = pos; // } // // public Float getWeight() { // return weight; // } // // public void setWeight(Float weight) { // this.weight = weight; // } // // public int getFrequency() { // return frequency; // } // // public void setFrequency(int frequency) { // this.frequency = frequency; // } // // @Override // public int hashCode() { // return Objects.hashCode(this.name); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final Word other = (Word) obj; // return Objects.equals(this.name, other.name); // } // // public String toString(String split) { // if (HanLP.Config.ShowTermNature) // return name + split + pos; // return name; // } // // @Override // public String toString() { // StringBuilder str = new StringBuilder(); // if (name != null) { // str.append(name); // } // if (pos != null) { // str.append("/").append(pos); // } // if (frequency > 0) { // str.append("/").append(frequency); // } // return str.toString(); // } // // @Override // public int compareTo(Object o) { // if (this == o) { // return 0; // } // if (this.name == null) { // return -1; // } // if (o == null) { // return 1; // } // if (!(o instanceof Word)) { // return 1; // } // String t = ((Word) o).getName(); // if (t == null) { // return 1; // } // return this.name.compareTo(t); // } // }
import org.xm.similarity.ISimilarity; import org.xm.tokenizer.Word; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
package org.xm.similarity.text; /** * @author xuming */ public interface ITextSimilarity extends ISimilarity { // 阈值 float thresholdRate = 0.5f; /** * 词列表1和词列表2的相似度分值 * * @param words1 词列表1 * @param words2 词列表2 * @return 相似度分值 */
// Path: src/main/java/org/xm/similarity/ISimilarity.java // public interface ISimilarity { // /** // * 计算相似度 // * // * @param word1 词语1 // * @param word2 词语2 // * @return 相似度值 // */ // double getSimilarity(String word1, String word2); // } // // Path: src/main/java/org/xm/tokenizer/Word.java // public class Word implements Comparable { // // 词名 // private String name; // // 词性 // private String pos; // // 权重,用于词向量分析 // private Float weight; // private int frequency; // // public Word(String name) { // this.name = name; // } // // public Word(String name, String pos) { // this.name = name; // this.pos = pos; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPos() { // return pos; // } // // public void setPos(String pos) { // this.pos = pos; // } // // public Float getWeight() { // return weight; // } // // public void setWeight(Float weight) { // this.weight = weight; // } // // public int getFrequency() { // return frequency; // } // // public void setFrequency(int frequency) { // this.frequency = frequency; // } // // @Override // public int hashCode() { // return Objects.hashCode(this.name); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final Word other = (Word) obj; // return Objects.equals(this.name, other.name); // } // // public String toString(String split) { // if (HanLP.Config.ShowTermNature) // return name + split + pos; // return name; // } // // @Override // public String toString() { // StringBuilder str = new StringBuilder(); // if (name != null) { // str.append(name); // } // if (pos != null) { // str.append("/").append(pos); // } // if (frequency > 0) { // str.append("/").append(frequency); // } // return str.toString(); // } // // @Override // public int compareTo(Object o) { // if (this == o) { // return 0; // } // if (this.name == null) { // return -1; // } // if (o == null) { // return 1; // } // if (!(o instanceof Word)) { // return 1; // } // String t = ((Word) o).getName(); // if (t == null) { // return 1; // } // return this.name.compareTo(t); // } // } // Path: src/main/java/org/xm/similarity/text/ITextSimilarity.java import org.xm.similarity.ISimilarity; import org.xm.tokenizer.Word; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; package org.xm.similarity.text; /** * @author xuming */ public interface ITextSimilarity extends ISimilarity { // 阈值 float thresholdRate = 0.5f; /** * 词列表1和词列表2的相似度分值 * * @param words1 词列表1 * @param words2 词列表2 * @return 相似度分值 */
double getSimilarity(List<Word> words1, List<Word> words2);
shibing624/similarity
src/test/java/org/xm/word2vec/Word2vecTest.java
// Path: src/main/java/org/xm/tokenizer/Tokenizer.java // public class Tokenizer { // private static final Logger logger = LoggerFactory.getLogger(Tokenizer.class); // // public static List<Word> segment(String sentence) { // List<Word> results = new ArrayList<>(); // /*// ansj_seg // List<org.xm.ansj.domain.Term> termList = StandardSegmentation.parse(sentence).getTerms();//ansj // results.addAll(termList // .stream() // .map(term -> new Word(term.getName(), term.getNature().natureStr)) // .collect(Collectors.toList()) // );*/ // // /*//Xmnlp // List<org.xm.xmnlp.seg.domain.Term> termList = Xmnlp.segment(sentence); // results.addAll(termList // .stream() // .map(term -> new Word(term.word, term.getNature().name())) // .collect(Collectors.toList()) // );*/ // // // HanLP // List<Term> termList = HanLP.segment(sentence); // results.addAll(termList // .stream() // .map(term -> new Word(term.word, term.nature.name())) // .collect(Collectors.toList()) // ); // // return results; // } // // public static void fileSegment(String inputFilePath, String outputFilePath) { // fileSegment(HanLP.newSegment(), inputFilePath, outputFilePath); // } // // public static void fileSegment(Segment segment, String inputFilePath, String outputFilePath) { // try { // WordFreqStatistics.statistics(segment, inputFilePath); // BufferedReader reader = IOUtil.newBufferedReader(inputFilePath); // long allCount = 0; // long lexCount = 0; // long start = System.currentTimeMillis(); // String outPath = inputFilePath.replace(".txt", "") + "-Segment-Result.txt"; // if (outputFilePath != null && outputFilePath.trim().length() > 0) outPath = outputFilePath; // FileOutputStream fos = new FileOutputStream(new File(outPath)); // String temp; // while ((temp = reader.readLine()) != null) { // List<Term> parse = segment.seg(temp); // StringBuilder sb = new StringBuilder(); // for (Term term : parse) { // sb.append(term.toString() + "\t"); // if (term.word.trim().length() > 0) { // allCount += term.length(); // lexCount += 1; // } // } // fos.write(sb.toString().trim().getBytes()); // fos.write("\n".getBytes()); // } // // fos.flush(); // fos.close(); // reader.close(); // long end = System.currentTimeMillis(); // System.out.println("segment result save:" + outPath); // System.out.println("total " + allCount + " chars, " + lexCount + " words, spend" + (end - start) + "ms "); // } catch (IOException e) { // logger.error("IO error: " + e.getLocalizedMessage()); // } // } // }
import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.seg.Segment; import org.junit.Test; import org.xm.tokenizer.Tokenizer; import java.util.List;
package org.xm.word2vec; /** * @author xuming */ public class Word2vecTest { private static final Segment SEGMENT = HanLP.newSegment().enableAllNamedEntityRecognize(true) .enableCustomDictionary(false).enableMultithreading(4); private static final String RAW_CORPUS = "corpus/tianlongbabu.txt"; private static final String RAW_CORPUS_SPLIT = "corpus/tianlongbabu.split.txt"; private static final String RAW_CORPUS_SPLIT_MODEL = "corpus/tianlongbabu.split.txt.model"; @Test public void trainModel() throws Exception { HanLP.Config.ShowTermNature = false;// 关闭词性标注
// Path: src/main/java/org/xm/tokenizer/Tokenizer.java // public class Tokenizer { // private static final Logger logger = LoggerFactory.getLogger(Tokenizer.class); // // public static List<Word> segment(String sentence) { // List<Word> results = new ArrayList<>(); // /*// ansj_seg // List<org.xm.ansj.domain.Term> termList = StandardSegmentation.parse(sentence).getTerms();//ansj // results.addAll(termList // .stream() // .map(term -> new Word(term.getName(), term.getNature().natureStr)) // .collect(Collectors.toList()) // );*/ // // /*//Xmnlp // List<org.xm.xmnlp.seg.domain.Term> termList = Xmnlp.segment(sentence); // results.addAll(termList // .stream() // .map(term -> new Word(term.word, term.getNature().name())) // .collect(Collectors.toList()) // );*/ // // // HanLP // List<Term> termList = HanLP.segment(sentence); // results.addAll(termList // .stream() // .map(term -> new Word(term.word, term.nature.name())) // .collect(Collectors.toList()) // ); // // return results; // } // // public static void fileSegment(String inputFilePath, String outputFilePath) { // fileSegment(HanLP.newSegment(), inputFilePath, outputFilePath); // } // // public static void fileSegment(Segment segment, String inputFilePath, String outputFilePath) { // try { // WordFreqStatistics.statistics(segment, inputFilePath); // BufferedReader reader = IOUtil.newBufferedReader(inputFilePath); // long allCount = 0; // long lexCount = 0; // long start = System.currentTimeMillis(); // String outPath = inputFilePath.replace(".txt", "") + "-Segment-Result.txt"; // if (outputFilePath != null && outputFilePath.trim().length() > 0) outPath = outputFilePath; // FileOutputStream fos = new FileOutputStream(new File(outPath)); // String temp; // while ((temp = reader.readLine()) != null) { // List<Term> parse = segment.seg(temp); // StringBuilder sb = new StringBuilder(); // for (Term term : parse) { // sb.append(term.toString() + "\t"); // if (term.word.trim().length() > 0) { // allCount += term.length(); // lexCount += 1; // } // } // fos.write(sb.toString().trim().getBytes()); // fos.write("\n".getBytes()); // } // // fos.flush(); // fos.close(); // reader.close(); // long end = System.currentTimeMillis(); // System.out.println("segment result save:" + outPath); // System.out.println("total " + allCount + " chars, " + lexCount + " words, spend" + (end - start) + "ms "); // } catch (IOException e) { // logger.error("IO error: " + e.getLocalizedMessage()); // } // } // } // Path: src/test/java/org/xm/word2vec/Word2vecTest.java import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.seg.Segment; import org.junit.Test; import org.xm.tokenizer.Tokenizer; import java.util.List; package org.xm.word2vec; /** * @author xuming */ public class Word2vecTest { private static final Segment SEGMENT = HanLP.newSegment().enableAllNamedEntityRecognize(true) .enableCustomDictionary(false).enableMultithreading(4); private static final String RAW_CORPUS = "corpus/tianlongbabu.txt"; private static final String RAW_CORPUS_SPLIT = "corpus/tianlongbabu.split.txt"; private static final String RAW_CORPUS_SPLIT_MODEL = "corpus/tianlongbabu.split.txt.model"; @Test public void trainModel() throws Exception { HanLP.Config.ShowTermNature = false;// 关闭词性标注
Tokenizer.fileSegment(SEGMENT, RAW_CORPUS, RAW_CORPUS_SPLIT);
shibing624/similarity
src/main/java/org/xm/similarity/text/JaroWinklerDistanceTextSimilarity.java
// Path: src/main/java/org/xm/tokenizer/Word.java // public class Word implements Comparable { // // 词名 // private String name; // // 词性 // private String pos; // // 权重,用于词向量分析 // private Float weight; // private int frequency; // // public Word(String name) { // this.name = name; // } // // public Word(String name, String pos) { // this.name = name; // this.pos = pos; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPos() { // return pos; // } // // public void setPos(String pos) { // this.pos = pos; // } // // public Float getWeight() { // return weight; // } // // public void setWeight(Float weight) { // this.weight = weight; // } // // public int getFrequency() { // return frequency; // } // // public void setFrequency(int frequency) { // this.frequency = frequency; // } // // @Override // public int hashCode() { // return Objects.hashCode(this.name); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final Word other = (Word) obj; // return Objects.equals(this.name, other.name); // } // // public String toString(String split) { // if (HanLP.Config.ShowTermNature) // return name + split + pos; // return name; // } // // @Override // public String toString() { // StringBuilder str = new StringBuilder(); // if (name != null) { // str.append(name); // } // if (pos != null) { // str.append("/").append(pos); // } // if (frequency > 0) { // str.append("/").append(frequency); // } // return str.toString(); // } // // @Override // public int compareTo(Object o) { // if (this == o) { // return 0; // } // if (this.name == null) { // return -1; // } // if (o == null) { // return 1; // } // if (!(o instanceof Word)) { // return 1; // } // String t = ((Word) o).getName(); // if (t == null) { // return 1; // } // return this.name.compareTo(t); // } // }
import org.xm.tokenizer.Word; import java.util.List;
/** * APDPlat - Application Product Development Platform * Copyright (c) 2013, 杨尚川, yang-shangchuan@qq.com * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p> * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.xm.similarity.text; /** * 文本相似度计算 * 判定方式:Jaro–Winkler距离(Jaro–Winkler Distance),Jaro的扩展 * 由William E. Winkler提出,最适合计算短文本如人名的相似度 * 这里需要注意的是Jaro–Winkler距离也就是相似度分值 * @author 杨尚川 */ public class JaroWinklerDistanceTextSimilarity extends JaroDistanceTextSimilarity { private static final double DEFAULT_SCALING_FACTOR = 0.1; private static final int MAXIMUM_CHARACTERS = 4; private double scalingFactor; public JaroWinklerDistanceTextSimilarity() { this.scalingFactor = DEFAULT_SCALING_FACTOR; } /** * scalingFactor的值介于闭区间[0, 0.25] * @param scalingFactor */ public JaroWinklerDistanceTextSimilarity(double scalingFactor) { if (scalingFactor > 0.25) { scalingFactor = 0.25; } if (scalingFactor < 0) { scalingFactor = 0; } this.scalingFactor = scalingFactor; } /** * 计算相似度分值 * @param words1 词列表1 * @param words2 词列表2 * @return 相似度分值 */ @Override
// Path: src/main/java/org/xm/tokenizer/Word.java // public class Word implements Comparable { // // 词名 // private String name; // // 词性 // private String pos; // // 权重,用于词向量分析 // private Float weight; // private int frequency; // // public Word(String name) { // this.name = name; // } // // public Word(String name, String pos) { // this.name = name; // this.pos = pos; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPos() { // return pos; // } // // public void setPos(String pos) { // this.pos = pos; // } // // public Float getWeight() { // return weight; // } // // public void setWeight(Float weight) { // this.weight = weight; // } // // public int getFrequency() { // return frequency; // } // // public void setFrequency(int frequency) { // this.frequency = frequency; // } // // @Override // public int hashCode() { // return Objects.hashCode(this.name); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final Word other = (Word) obj; // return Objects.equals(this.name, other.name); // } // // public String toString(String split) { // if (HanLP.Config.ShowTermNature) // return name + split + pos; // return name; // } // // @Override // public String toString() { // StringBuilder str = new StringBuilder(); // if (name != null) { // str.append(name); // } // if (pos != null) { // str.append("/").append(pos); // } // if (frequency > 0) { // str.append("/").append(frequency); // } // return str.toString(); // } // // @Override // public int compareTo(Object o) { // if (this == o) { // return 0; // } // if (this.name == null) { // return -1; // } // if (o == null) { // return 1; // } // if (!(o instanceof Word)) { // return 1; // } // String t = ((Word) o).getName(); // if (t == null) { // return 1; // } // return this.name.compareTo(t); // } // } // Path: src/main/java/org/xm/similarity/text/JaroWinklerDistanceTextSimilarity.java import org.xm.tokenizer.Word; import java.util.List; /** * APDPlat - Application Product Development Platform * Copyright (c) 2013, 杨尚川, yang-shangchuan@qq.com * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p> * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.xm.similarity.text; /** * 文本相似度计算 * 判定方式:Jaro–Winkler距离(Jaro–Winkler Distance),Jaro的扩展 * 由William E. Winkler提出,最适合计算短文本如人名的相似度 * 这里需要注意的是Jaro–Winkler距离也就是相似度分值 * @author 杨尚川 */ public class JaroWinklerDistanceTextSimilarity extends JaroDistanceTextSimilarity { private static final double DEFAULT_SCALING_FACTOR = 0.1; private static final int MAXIMUM_CHARACTERS = 4; private double scalingFactor; public JaroWinklerDistanceTextSimilarity() { this.scalingFactor = DEFAULT_SCALING_FACTOR; } /** * scalingFactor的值介于闭区间[0, 0.25] * @param scalingFactor */ public JaroWinklerDistanceTextSimilarity(double scalingFactor) { if (scalingFactor > 0.25) { scalingFactor = 0.25; } if (scalingFactor < 0) { scalingFactor = 0; } this.scalingFactor = scalingFactor; } /** * 计算相似度分值 * @param words1 词列表1 * @param words2 词列表2 * @return 相似度分值 */ @Override
protected double getSimilarityImpl(List<Word> words1, List<Word> words2) {
shibing624/similarity
src/test/java/org/xm/similarity/dictionary/PinyinDictionaryTest.java
// Path: src/main/java/org/xm/similarity/word/pinyin/PinyinDictionary.java // public class PinyinDictionary { // private Map<Character, Set<String>> pinyinDict; // private static PinyinDictionary instance; // private static final String path = Similarity.Config.PinyinPath; // // private PinyinDictionary() throws IOException { // BufferedReader br = DicReader.getReader(path); // String line; // Event event = new Event(); // while ((line = br.readLine()) != null) { // event.visit(line); // } // br.close(); // this.pinyinDict = event.getPinyins(); // } // // public static PinyinDictionary getInstance() { // if (instance == null) { // try { // instance = new PinyinDictionary(); // } catch (IOException e) { // e.printStackTrace(); // } // } // return instance; // } // // /** // * 获取汉字的拼音, 由于汉字具有多音字,故返回一个集合 // * // * @param c // * @return // */ // public Set<String> getPinyin(Character c) { // Set<String> set = pinyinDict.get(c); // if (set == null || set.size() == 0) { // set = new HashSet<>(); // set.add(c.toString()); // } // return set; // } // // /** // * 获取词语的拼音, 一个词语可能对应多个拼音,把所有可能的组合放到集合中返回 // * // * @param word // * @return // */ // public Set<String> getPinyin(String word) { // Set<String> set = new HashSet<>(); // for (int i = 0; i < word.length(); i++) { // Set<String> pinyinSet = getPinyin(word.charAt(i)); // if (set == null || set.size() == 0) { // set.addAll(pinyinSet); // continue; // } // Set<String> tempSet = new HashSet<>(); // for (String s : set) { // tempSet.addAll(pinyinSet.stream().map(p -> s + p).collect(Collectors.toList())); // } // set = tempSet; // } // return set; // } // // /** // * 获取拼音字符串,多音字只取一个 // * // * @param word // * @return // */ // public String getPinyinSingle(String word) { // StringBuffer sb = new StringBuffer(); // for (int i = 0; i < word.length(); i++) { // sb.append(getPinyin(word.charAt(i)).iterator().next()); // } // return sb.toString(); // } // // /** // * 获取拼音串,对于多音字,给出所有拼音 // * // * @param word // * @return // */ // public String getPinyinString(String word) { // StringBuffer sb = new StringBuffer(); // for (int i = 0; i < word.length(); i++) { // Set<String> pinyin = getPinyin(word.charAt(i)); // sb.append(pinyin.toString()); // } // return sb.toString(); // } // // /** // * 获取拼音首字母 // * // * @param word // * @return // */ // public String getPinyinHead(String word) { // StringBuffer sb = new StringBuffer(); // for (int i = 0; i < word.length(); i++) { // sb.append(getPinyin(word.charAt(i)).iterator().next().charAt(0)); // } // return sb.toString(); // } // // private static class Event { // private Map<Character, Set<String>> pinyins; // // public Event() { // this.pinyins = new HashMap<>(); // } // // public Map<Character, Set<String>> getPinyins() { // return pinyins; // } // // public boolean visit(String str) { // if (str.startsWith("//")) { // return true; // } // char c = str.charAt(0); // String pinyin = str.substring(2, str.length()); // Set<String> set = pinyins.get(c); // if (set == null) { // set = new HashSet<>(); // } // set.add(pinyin); // pinyins.put(c, set); // return true; // } // } // }
import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.dictionary.py.Pinyin; import org.junit.Assert; import org.junit.Test; import org.xm.similarity.word.pinyin.PinyinDictionary; import java.util.List; import java.util.Set;
package org.xm.similarity.dictionary; /** * @author xuming */ public class PinyinDictionaryTest { @Test public void getPinyin() throws Exception {
// Path: src/main/java/org/xm/similarity/word/pinyin/PinyinDictionary.java // public class PinyinDictionary { // private Map<Character, Set<String>> pinyinDict; // private static PinyinDictionary instance; // private static final String path = Similarity.Config.PinyinPath; // // private PinyinDictionary() throws IOException { // BufferedReader br = DicReader.getReader(path); // String line; // Event event = new Event(); // while ((line = br.readLine()) != null) { // event.visit(line); // } // br.close(); // this.pinyinDict = event.getPinyins(); // } // // public static PinyinDictionary getInstance() { // if (instance == null) { // try { // instance = new PinyinDictionary(); // } catch (IOException e) { // e.printStackTrace(); // } // } // return instance; // } // // /** // * 获取汉字的拼音, 由于汉字具有多音字,故返回一个集合 // * // * @param c // * @return // */ // public Set<String> getPinyin(Character c) { // Set<String> set = pinyinDict.get(c); // if (set == null || set.size() == 0) { // set = new HashSet<>(); // set.add(c.toString()); // } // return set; // } // // /** // * 获取词语的拼音, 一个词语可能对应多个拼音,把所有可能的组合放到集合中返回 // * // * @param word // * @return // */ // public Set<String> getPinyin(String word) { // Set<String> set = new HashSet<>(); // for (int i = 0; i < word.length(); i++) { // Set<String> pinyinSet = getPinyin(word.charAt(i)); // if (set == null || set.size() == 0) { // set.addAll(pinyinSet); // continue; // } // Set<String> tempSet = new HashSet<>(); // for (String s : set) { // tempSet.addAll(pinyinSet.stream().map(p -> s + p).collect(Collectors.toList())); // } // set = tempSet; // } // return set; // } // // /** // * 获取拼音字符串,多音字只取一个 // * // * @param word // * @return // */ // public String getPinyinSingle(String word) { // StringBuffer sb = new StringBuffer(); // for (int i = 0; i < word.length(); i++) { // sb.append(getPinyin(word.charAt(i)).iterator().next()); // } // return sb.toString(); // } // // /** // * 获取拼音串,对于多音字,给出所有拼音 // * // * @param word // * @return // */ // public String getPinyinString(String word) { // StringBuffer sb = new StringBuffer(); // for (int i = 0; i < word.length(); i++) { // Set<String> pinyin = getPinyin(word.charAt(i)); // sb.append(pinyin.toString()); // } // return sb.toString(); // } // // /** // * 获取拼音首字母 // * // * @param word // * @return // */ // public String getPinyinHead(String word) { // StringBuffer sb = new StringBuffer(); // for (int i = 0; i < word.length(); i++) { // sb.append(getPinyin(word.charAt(i)).iterator().next().charAt(0)); // } // return sb.toString(); // } // // private static class Event { // private Map<Character, Set<String>> pinyins; // // public Event() { // this.pinyins = new HashMap<>(); // } // // public Map<Character, Set<String>> getPinyins() { // return pinyins; // } // // public boolean visit(String str) { // if (str.startsWith("//")) { // return true; // } // char c = str.charAt(0); // String pinyin = str.substring(2, str.length()); // Set<String> set = pinyins.get(c); // if (set == null) { // set = new HashSet<>(); // } // set.add(pinyin); // pinyins.put(c, set); // return true; // } // } // } // Path: src/test/java/org/xm/similarity/dictionary/PinyinDictionaryTest.java import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.dictionary.py.Pinyin; import org.junit.Assert; import org.junit.Test; import org.xm.similarity.word.pinyin.PinyinDictionary; import java.util.List; import java.util.Set; package org.xm.similarity.dictionary; /** * @author xuming */ public class PinyinDictionaryTest { @Test public void getPinyin() throws Exception {
Set<String> pinyinSet1 = PinyinDictionary.getInstance().getPinyin("教");
shibing624/similarity
src/main/java/org/xm/similarity/text/EditDistanceSimilarity.java
// Path: src/main/java/org/xm/tokenizer/Word.java // public class Word implements Comparable { // // 词名 // private String name; // // 词性 // private String pos; // // 权重,用于词向量分析 // private Float weight; // private int frequency; // // public Word(String name) { // this.name = name; // } // // public Word(String name, String pos) { // this.name = name; // this.pos = pos; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPos() { // return pos; // } // // public void setPos(String pos) { // this.pos = pos; // } // // public Float getWeight() { // return weight; // } // // public void setWeight(Float weight) { // this.weight = weight; // } // // public int getFrequency() { // return frequency; // } // // public void setFrequency(int frequency) { // this.frequency = frequency; // } // // @Override // public int hashCode() { // return Objects.hashCode(this.name); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final Word other = (Word) obj; // return Objects.equals(this.name, other.name); // } // // public String toString(String split) { // if (HanLP.Config.ShowTermNature) // return name + split + pos; // return name; // } // // @Override // public String toString() { // StringBuilder str = new StringBuilder(); // if (name != null) { // str.append(name); // } // if (pos != null) { // str.append("/").append(pos); // } // if (frequency > 0) { // str.append("/").append(frequency); // } // return str.toString(); // } // // @Override // public int compareTo(Object o) { // if (this == o) { // return 0; // } // if (this.name == null) { // return -1; // } // if (o == null) { // return 1; // } // if (!(o instanceof Word)) { // return 1; // } // String t = ((Word) o).getName(); // if (t == null) { // return 1; // } // return this.name.compareTo(t); // } // }
import org.xm.tokenizer.Word; import java.util.List;
package org.xm.similarity.text; /** * 编辑距离(Edit Distance)相似度计算 * 文本相似度计算 * 指两个字串之间,由一个转成另一个所需的最少编辑操作次数 * 允许的编辑操作包括将一个字符替换成另一个字符,增加一个字符,删除一个字符 * 例如将kitten一字转成sitting: * sitten (k→s)将一个字符k替换成另一个字符s * sittin (e→i)将一个字符e替换成另一个字符i * sitting (→g)增加一个字符g * 因为这个算法是俄罗斯科学家Vladimir Levenshtein在1965年提出 * 所以编辑距离(Edit Distance)又称Levenshtein距离 * * @author xuming */ public class EditDistanceSimilarity extends TextSimilarity { /** * 计算相似度分值 * * @param words1 词列表1 * @param words2 词列表2 * @return 相似度分值 */ @Override
// Path: src/main/java/org/xm/tokenizer/Word.java // public class Word implements Comparable { // // 词名 // private String name; // // 词性 // private String pos; // // 权重,用于词向量分析 // private Float weight; // private int frequency; // // public Word(String name) { // this.name = name; // } // // public Word(String name, String pos) { // this.name = name; // this.pos = pos; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPos() { // return pos; // } // // public void setPos(String pos) { // this.pos = pos; // } // // public Float getWeight() { // return weight; // } // // public void setWeight(Float weight) { // this.weight = weight; // } // // public int getFrequency() { // return frequency; // } // // public void setFrequency(int frequency) { // this.frequency = frequency; // } // // @Override // public int hashCode() { // return Objects.hashCode(this.name); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final Word other = (Word) obj; // return Objects.equals(this.name, other.name); // } // // public String toString(String split) { // if (HanLP.Config.ShowTermNature) // return name + split + pos; // return name; // } // // @Override // public String toString() { // StringBuilder str = new StringBuilder(); // if (name != null) { // str.append(name); // } // if (pos != null) { // str.append("/").append(pos); // } // if (frequency > 0) { // str.append("/").append(frequency); // } // return str.toString(); // } // // @Override // public int compareTo(Object o) { // if (this == o) { // return 0; // } // if (this.name == null) { // return -1; // } // if (o == null) { // return 1; // } // if (!(o instanceof Word)) { // return 1; // } // String t = ((Word) o).getName(); // if (t == null) { // return 1; // } // return this.name.compareTo(t); // } // } // Path: src/main/java/org/xm/similarity/text/EditDistanceSimilarity.java import org.xm.tokenizer.Word; import java.util.List; package org.xm.similarity.text; /** * 编辑距离(Edit Distance)相似度计算 * 文本相似度计算 * 指两个字串之间,由一个转成另一个所需的最少编辑操作次数 * 允许的编辑操作包括将一个字符替换成另一个字符,增加一个字符,删除一个字符 * 例如将kitten一字转成sitting: * sitten (k→s)将一个字符k替换成另一个字符s * sittin (e→i)将一个字符e替换成另一个字符i * sitting (→g)增加一个字符g * 因为这个算法是俄罗斯科学家Vladimir Levenshtein在1965年提出 * 所以编辑距离(Edit Distance)又称Levenshtein距离 * * @author xuming */ public class EditDistanceSimilarity extends TextSimilarity { /** * 计算相似度分值 * * @param words1 词列表1 * @param words2 词列表2 * @return 相似度分值 */ @Override
protected double getSimilarityImpl(List<Word> words1, List<Word> words2) {
shibing624/similarity
src/test/java/org/xm/FileSegmentStatisticsDemo.java
// Path: src/main/java/org/xm/tokenizer/Tokenizer.java // public class Tokenizer { // private static final Logger logger = LoggerFactory.getLogger(Tokenizer.class); // // public static List<Word> segment(String sentence) { // List<Word> results = new ArrayList<>(); // /*// ansj_seg // List<org.xm.ansj.domain.Term> termList = StandardSegmentation.parse(sentence).getTerms();//ansj // results.addAll(termList // .stream() // .map(term -> new Word(term.getName(), term.getNature().natureStr)) // .collect(Collectors.toList()) // );*/ // // /*//Xmnlp // List<org.xm.xmnlp.seg.domain.Term> termList = Xmnlp.segment(sentence); // results.addAll(termList // .stream() // .map(term -> new Word(term.word, term.getNature().name())) // .collect(Collectors.toList()) // );*/ // // // HanLP // List<Term> termList = HanLP.segment(sentence); // results.addAll(termList // .stream() // .map(term -> new Word(term.word, term.nature.name())) // .collect(Collectors.toList()) // ); // // return results; // } // // public static void fileSegment(String inputFilePath, String outputFilePath) { // fileSegment(HanLP.newSegment(), inputFilePath, outputFilePath); // } // // public static void fileSegment(Segment segment, String inputFilePath, String outputFilePath) { // try { // WordFreqStatistics.statistics(segment, inputFilePath); // BufferedReader reader = IOUtil.newBufferedReader(inputFilePath); // long allCount = 0; // long lexCount = 0; // long start = System.currentTimeMillis(); // String outPath = inputFilePath.replace(".txt", "") + "-Segment-Result.txt"; // if (outputFilePath != null && outputFilePath.trim().length() > 0) outPath = outputFilePath; // FileOutputStream fos = new FileOutputStream(new File(outPath)); // String temp; // while ((temp = reader.readLine()) != null) { // List<Term> parse = segment.seg(temp); // StringBuilder sb = new StringBuilder(); // for (Term term : parse) { // sb.append(term.toString() + "\t"); // if (term.word.trim().length() > 0) { // allCount += term.length(); // lexCount += 1; // } // } // fos.write(sb.toString().trim().getBytes()); // fos.write("\n".getBytes()); // } // // fos.flush(); // fos.close(); // reader.close(); // long end = System.currentTimeMillis(); // System.out.println("segment result save:" + outPath); // System.out.println("total " + allCount + " chars, " + lexCount + " words, spend" + (end - start) + "ms "); // } catch (IOException e) { // logger.error("IO error: " + e.getLocalizedMessage()); // } // } // }
import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.seg.Segment; import org.xm.tokenizer.Tokenizer; import java.io.IOException;
package org.xm; /** * 对文件分词并统计 * * @author xuming */ public class FileSegmentStatisticsDemo { private static final Segment SEGMENT = HanLP.newSegment().enableNameRecognize(true) .enablePlaceRecognize(true).enablePartOfSpeechTagging(true).enableMultithreading(4); public static void main(String[] args) throws IOException { String filePath = "corpus/tianlongbabu_head100.txt";
// Path: src/main/java/org/xm/tokenizer/Tokenizer.java // public class Tokenizer { // private static final Logger logger = LoggerFactory.getLogger(Tokenizer.class); // // public static List<Word> segment(String sentence) { // List<Word> results = new ArrayList<>(); // /*// ansj_seg // List<org.xm.ansj.domain.Term> termList = StandardSegmentation.parse(sentence).getTerms();//ansj // results.addAll(termList // .stream() // .map(term -> new Word(term.getName(), term.getNature().natureStr)) // .collect(Collectors.toList()) // );*/ // // /*//Xmnlp // List<org.xm.xmnlp.seg.domain.Term> termList = Xmnlp.segment(sentence); // results.addAll(termList // .stream() // .map(term -> new Word(term.word, term.getNature().name())) // .collect(Collectors.toList()) // );*/ // // // HanLP // List<Term> termList = HanLP.segment(sentence); // results.addAll(termList // .stream() // .map(term -> new Word(term.word, term.nature.name())) // .collect(Collectors.toList()) // ); // // return results; // } // // public static void fileSegment(String inputFilePath, String outputFilePath) { // fileSegment(HanLP.newSegment(), inputFilePath, outputFilePath); // } // // public static void fileSegment(Segment segment, String inputFilePath, String outputFilePath) { // try { // WordFreqStatistics.statistics(segment, inputFilePath); // BufferedReader reader = IOUtil.newBufferedReader(inputFilePath); // long allCount = 0; // long lexCount = 0; // long start = System.currentTimeMillis(); // String outPath = inputFilePath.replace(".txt", "") + "-Segment-Result.txt"; // if (outputFilePath != null && outputFilePath.trim().length() > 0) outPath = outputFilePath; // FileOutputStream fos = new FileOutputStream(new File(outPath)); // String temp; // while ((temp = reader.readLine()) != null) { // List<Term> parse = segment.seg(temp); // StringBuilder sb = new StringBuilder(); // for (Term term : parse) { // sb.append(term.toString() + "\t"); // if (term.word.trim().length() > 0) { // allCount += term.length(); // lexCount += 1; // } // } // fos.write(sb.toString().trim().getBytes()); // fos.write("\n".getBytes()); // } // // fos.flush(); // fos.close(); // reader.close(); // long end = System.currentTimeMillis(); // System.out.println("segment result save:" + outPath); // System.out.println("total " + allCount + " chars, " + lexCount + " words, spend" + (end - start) + "ms "); // } catch (IOException e) { // logger.error("IO error: " + e.getLocalizedMessage()); // } // } // } // Path: src/test/java/org/xm/FileSegmentStatisticsDemo.java import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.seg.Segment; import org.xm.tokenizer.Tokenizer; import java.io.IOException; package org.xm; /** * 对文件分词并统计 * * @author xuming */ public class FileSegmentStatisticsDemo { private static final Segment SEGMENT = HanLP.newSegment().enableNameRecognize(true) .enablePlaceRecognize(true).enablePartOfSpeechTagging(true).enableMultithreading(4); public static void main(String[] args) throws IOException { String filePath = "corpus/tianlongbabu_head100.txt";
Tokenizer.fileSegment(SEGMENT, filePath, null);
shibing624/similarity
src/main/java/org/xm/similarity/text/DiceTextSimilarity.java
// Path: src/main/java/org/xm/tokenizer/Word.java // public class Word implements Comparable { // // 词名 // private String name; // // 词性 // private String pos; // // 权重,用于词向量分析 // private Float weight; // private int frequency; // // public Word(String name) { // this.name = name; // } // // public Word(String name, String pos) { // this.name = name; // this.pos = pos; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPos() { // return pos; // } // // public void setPos(String pos) { // this.pos = pos; // } // // public Float getWeight() { // return weight; // } // // public void setWeight(Float weight) { // this.weight = weight; // } // // public int getFrequency() { // return frequency; // } // // public void setFrequency(int frequency) { // this.frequency = frequency; // } // // @Override // public int hashCode() { // return Objects.hashCode(this.name); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final Word other = (Word) obj; // return Objects.equals(this.name, other.name); // } // // public String toString(String split) { // if (HanLP.Config.ShowTermNature) // return name + split + pos; // return name; // } // // @Override // public String toString() { // StringBuilder str = new StringBuilder(); // if (name != null) { // str.append(name); // } // if (pos != null) { // str.append("/").append(pos); // } // if (frequency > 0) { // str.append("/").append(frequency); // } // return str.toString(); // } // // @Override // public int compareTo(Object o) { // if (this == o) { // return 0; // } // if (this.name == null) { // return -1; // } // if (o == null) { // return 1; // } // if (!(o instanceof Word)) { // return 1; // } // String t = ((Word) o).getName(); // if (t == null) { // return 1; // } // return this.name.compareTo(t); // } // }
import org.xm.tokenizer.Word; import java.util.HashSet; import java.util.List; import java.util.Set;
package org.xm.similarity.text; /** * 文本相似度计算 * 判定方式:Sorensen–Dice系数(Sorensen–Dice coefficient),通过计算两个集合交集的大小的2倍除以两个集合的大小之和来评估他们的相似度 * 算法步骤描述: * 1、分词 * 2、求交集(去重),计算交集的不重复词的个数 intersectionSize * 3、两个集合的大小分别为 set1Size 和 set2Size * 4、相似度分值 = 2*intersectionSize/(set1Size+set2Size) * 完整计算公式: * double score = 2*intersectionSize/(set1Size+set2Size); * * @author 杨尚川 */ public class DiceTextSimilarity extends TextSimilarity { /** * 计算相似度分值 * * @param words1 词列表1 * @param words2 词列表2 * @return 相似度分值 */ @Override
// Path: src/main/java/org/xm/tokenizer/Word.java // public class Word implements Comparable { // // 词名 // private String name; // // 词性 // private String pos; // // 权重,用于词向量分析 // private Float weight; // private int frequency; // // public Word(String name) { // this.name = name; // } // // public Word(String name, String pos) { // this.name = name; // this.pos = pos; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPos() { // return pos; // } // // public void setPos(String pos) { // this.pos = pos; // } // // public Float getWeight() { // return weight; // } // // public void setWeight(Float weight) { // this.weight = weight; // } // // public int getFrequency() { // return frequency; // } // // public void setFrequency(int frequency) { // this.frequency = frequency; // } // // @Override // public int hashCode() { // return Objects.hashCode(this.name); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final Word other = (Word) obj; // return Objects.equals(this.name, other.name); // } // // public String toString(String split) { // if (HanLP.Config.ShowTermNature) // return name + split + pos; // return name; // } // // @Override // public String toString() { // StringBuilder str = new StringBuilder(); // if (name != null) { // str.append(name); // } // if (pos != null) { // str.append("/").append(pos); // } // if (frequency > 0) { // str.append("/").append(frequency); // } // return str.toString(); // } // // @Override // public int compareTo(Object o) { // if (this == o) { // return 0; // } // if (this.name == null) { // return -1; // } // if (o == null) { // return 1; // } // if (!(o instanceof Word)) { // return 1; // } // String t = ((Word) o).getName(); // if (t == null) { // return 1; // } // return this.name.compareTo(t); // } // } // Path: src/main/java/org/xm/similarity/text/DiceTextSimilarity.java import org.xm.tokenizer.Word; import java.util.HashSet; import java.util.List; import java.util.Set; package org.xm.similarity.text; /** * 文本相似度计算 * 判定方式:Sorensen–Dice系数(Sorensen–Dice coefficient),通过计算两个集合交集的大小的2倍除以两个集合的大小之和来评估他们的相似度 * 算法步骤描述: * 1、分词 * 2、求交集(去重),计算交集的不重复词的个数 intersectionSize * 3、两个集合的大小分别为 set1Size 和 set2Size * 4、相似度分值 = 2*intersectionSize/(set1Size+set2Size) * 完整计算公式: * double score = 2*intersectionSize/(set1Size+set2Size); * * @author 杨尚川 */ public class DiceTextSimilarity extends TextSimilarity { /** * 计算相似度分值 * * @param words1 词列表1 * @param words2 词列表2 * @return 相似度分值 */ @Override
protected double getSimilarityImpl(List<Word> words1, List<Word> words2) {
shibing624/similarity
src/main/java/org/xm/word2vec/vec/ModelParser.java
// Path: src/main/java/org/xm/word2vec/domain/WordEntry.java // public class WordEntry implements Comparable<WordEntry> { // public String name; // public float score; // // public WordEntry(String name, float score) { // this.name = name; // this.score = score; // } // // public String toString() { // return "name:" + this.name + "\tscore:" + this.score; // } // // @Override // public int compareTo(WordEntry o) { // if (this.score < o.score) { // return 1; // } else // return -1; // } // }
import org.xm.word2vec.domain.WordEntry; import java.io.*; import java.util.*;
private static final int MAX_SIZE = 50; public void loadModel(String path) throws IOException { try (DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(path)))) { words = dis.readInt(); size = dis.readInt(); float vector; String key; float[] value; for (int i = 0; i < words; i++) { double len = 0.0; key = dis.readUTF(); value = new float[size]; for (int j = 0; j < size; j++) { vector = dis.readFloat(); len += vector * vector; value[j] = vector; } len = Math.sqrt(len); for (int j = 0; j < size; j++) { value[j] /= len; } wordMap.put(key, value); } } } /** * 近义词 */
// Path: src/main/java/org/xm/word2vec/domain/WordEntry.java // public class WordEntry implements Comparable<WordEntry> { // public String name; // public float score; // // public WordEntry(String name, float score) { // this.name = name; // this.score = score; // } // // public String toString() { // return "name:" + this.name + "\tscore:" + this.score; // } // // @Override // public int compareTo(WordEntry o) { // if (this.score < o.score) { // return 1; // } else // return -1; // } // } // Path: src/main/java/org/xm/word2vec/vec/ModelParser.java import org.xm.word2vec.domain.WordEntry; import java.io.*; import java.util.*; private static final int MAX_SIZE = 50; public void loadModel(String path) throws IOException { try (DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(path)))) { words = dis.readInt(); size = dis.readInt(); float vector; String key; float[] value; for (int i = 0; i < words; i++) { double len = 0.0; key = dis.readUTF(); value = new float[size]; for (int j = 0; j < size; j++) { vector = dis.readFloat(); len += vector * vector; value[j] = vector; } len = Math.sqrt(len); for (int j = 0; j < size; j++) { value[j] /= len; } wordMap.put(key, value); } } } /** * 近义词 */
public TreeSet<WordEntry> analogy(String word0, String word1, String word2) {
shibing624/similarity
src/test/java/org/xm/TendencyDemo.java
// Path: src/main/java/org/xm/tendency/word/HownetWordTendency.java // public class HownetWordTendency implements IWordTendency { // private static final Logger logger = LoggerFactory.getLogger(HownetWordTendency.class); // private ConceptParser conceptParser; // private SememeParser sememeParser; // public static String[] POSITIVE_SEMEMES = new String[]{"良", "喜悦", "夸奖", "满意", "期望", "注意", "致敬", "喜欢", // "专", "敬佩", "同意", "爱惜", "愿意", "思念", "拥护", "祝贺", "福", "需求", "奖励", "致谢", "欢迎", "羡慕", // "感激", "爱恋"}; // // public static String[] NEGATIVE_SEMEMES = new String[]{"莠", "谴责", "害怕", "生气", "悲哀", "着急", "轻视", "羞愧", // "烦恼", "灰心", "犹豫", "为难", "懊悔", "厌恶", "怀疑", "怜悯", "忧愁", "示怒", "不满", "仇恨", "埋怨", // "失望", "坏"}; // // public HownetWordTendency() { // this.conceptParser = ConceptSimilarity.getInstance(); // try { // this.sememeParser = new SememeSimilarity(); // } catch (IOException e) { // logger.error("exception:{}", e.getMessage()); // } // } // // @Override // public double getTendency(String word) { // double positive = getSentiment(word, POSITIVE_SEMEMES); // double negative = getSentiment(word, NEGATIVE_SEMEMES); // return positive - negative; // } // // private double getSentiment(String word, String[] candidateSememes) { // Collection<Concept> concepts = conceptParser.getConcepts(word); // Set<String> sememes = new HashSet<>(); // for (Concept concept : concepts) sememes.addAll(concept.getAllSememeNames()); // // double max = 0.0; // for (String item : sememes) { // double total = 0.0; // for (String positiveSememe : candidateSememes) { // double value = sememeParser.getSimilarity(item, positiveSememe); // // 如果有特别接近的义原,直接返回该相似值 // if (value > 0.9) { // return value; // } // total += value; // } // double sim = total / candidateSememes.length; // if (sim > max) { // max = sim; // } // } // return max; // } // }
import org.xm.tendency.word.HownetWordTendency;
package org.xm; /** * @author xuming */ public class TendencyDemo { public static void main(String[] args) { String word = "混蛋";
// Path: src/main/java/org/xm/tendency/word/HownetWordTendency.java // public class HownetWordTendency implements IWordTendency { // private static final Logger logger = LoggerFactory.getLogger(HownetWordTendency.class); // private ConceptParser conceptParser; // private SememeParser sememeParser; // public static String[] POSITIVE_SEMEMES = new String[]{"良", "喜悦", "夸奖", "满意", "期望", "注意", "致敬", "喜欢", // "专", "敬佩", "同意", "爱惜", "愿意", "思念", "拥护", "祝贺", "福", "需求", "奖励", "致谢", "欢迎", "羡慕", // "感激", "爱恋"}; // // public static String[] NEGATIVE_SEMEMES = new String[]{"莠", "谴责", "害怕", "生气", "悲哀", "着急", "轻视", "羞愧", // "烦恼", "灰心", "犹豫", "为难", "懊悔", "厌恶", "怀疑", "怜悯", "忧愁", "示怒", "不满", "仇恨", "埋怨", // "失望", "坏"}; // // public HownetWordTendency() { // this.conceptParser = ConceptSimilarity.getInstance(); // try { // this.sememeParser = new SememeSimilarity(); // } catch (IOException e) { // logger.error("exception:{}", e.getMessage()); // } // } // // @Override // public double getTendency(String word) { // double positive = getSentiment(word, POSITIVE_SEMEMES); // double negative = getSentiment(word, NEGATIVE_SEMEMES); // return positive - negative; // } // // private double getSentiment(String word, String[] candidateSememes) { // Collection<Concept> concepts = conceptParser.getConcepts(word); // Set<String> sememes = new HashSet<>(); // for (Concept concept : concepts) sememes.addAll(concept.getAllSememeNames()); // // double max = 0.0; // for (String item : sememes) { // double total = 0.0; // for (String positiveSememe : candidateSememes) { // double value = sememeParser.getSimilarity(item, positiveSememe); // // 如果有特别接近的义原,直接返回该相似值 // if (value > 0.9) { // return value; // } // total += value; // } // double sim = total / candidateSememes.length; // if (sim > max) { // max = sim; // } // } // return max; // } // } // Path: src/test/java/org/xm/TendencyDemo.java import org.xm.tendency.word.HownetWordTendency; package org.xm; /** * @author xuming */ public class TendencyDemo { public static void main(String[] args) { String word = "混蛋";
HownetWordTendency hownetWordTendency = new HownetWordTendency();
shibing624/similarity
src/main/java/org/xm/similarity/text/JaroDistanceTextSimilarity.java
// Path: src/main/java/org/xm/tokenizer/Word.java // public class Word implements Comparable { // // 词名 // private String name; // // 词性 // private String pos; // // 权重,用于词向量分析 // private Float weight; // private int frequency; // // public Word(String name) { // this.name = name; // } // // public Word(String name, String pos) { // this.name = name; // this.pos = pos; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPos() { // return pos; // } // // public void setPos(String pos) { // this.pos = pos; // } // // public Float getWeight() { // return weight; // } // // public void setWeight(Float weight) { // this.weight = weight; // } // // public int getFrequency() { // return frequency; // } // // public void setFrequency(int frequency) { // this.frequency = frequency; // } // // @Override // public int hashCode() { // return Objects.hashCode(this.name); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final Word other = (Word) obj; // return Objects.equals(this.name, other.name); // } // // public String toString(String split) { // if (HanLP.Config.ShowTermNature) // return name + split + pos; // return name; // } // // @Override // public String toString() { // StringBuilder str = new StringBuilder(); // if (name != null) { // str.append(name); // } // if (pos != null) { // str.append("/").append(pos); // } // if (frequency > 0) { // str.append("/").append(frequency); // } // return str.toString(); // } // // @Override // public int compareTo(Object o) { // if (this == o) { // return 0; // } // if (this.name == null) { // return -1; // } // if (o == null) { // return 1; // } // if (!(o instanceof Word)) { // return 1; // } // String t = ((Word) o).getName(); // if (t == null) { // return 1; // } // return this.name.compareTo(t); // } // }
import org.xm.tokenizer.Word; import java.util.List;
/** * APDPlat - Application Product Development Platform * Copyright (c) 2013, 杨尚川, yang-shangchuan@qq.com * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p> * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.xm.similarity.text; /** * 文本相似度计算 * 判定方式:Jaro距离(Jaro Distance),编辑距离的一种类型 * 这里需要注意的是Jaro距离也就是相似度分值 * * @author 杨尚川 */ public class JaroDistanceTextSimilarity extends TextSimilarity { protected String shorterText = null; protected String longerText = null; /** * 计算相似度分值 * * @param words1 词列表1 * @param words2 词列表2 * @return 相似度分值 */ @Override
// Path: src/main/java/org/xm/tokenizer/Word.java // public class Word implements Comparable { // // 词名 // private String name; // // 词性 // private String pos; // // 权重,用于词向量分析 // private Float weight; // private int frequency; // // public Word(String name) { // this.name = name; // } // // public Word(String name, String pos) { // this.name = name; // this.pos = pos; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPos() { // return pos; // } // // public void setPos(String pos) { // this.pos = pos; // } // // public Float getWeight() { // return weight; // } // // public void setWeight(Float weight) { // this.weight = weight; // } // // public int getFrequency() { // return frequency; // } // // public void setFrequency(int frequency) { // this.frequency = frequency; // } // // @Override // public int hashCode() { // return Objects.hashCode(this.name); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final Word other = (Word) obj; // return Objects.equals(this.name, other.name); // } // // public String toString(String split) { // if (HanLP.Config.ShowTermNature) // return name + split + pos; // return name; // } // // @Override // public String toString() { // StringBuilder str = new StringBuilder(); // if (name != null) { // str.append(name); // } // if (pos != null) { // str.append("/").append(pos); // } // if (frequency > 0) { // str.append("/").append(frequency); // } // return str.toString(); // } // // @Override // public int compareTo(Object o) { // if (this == o) { // return 0; // } // if (this.name == null) { // return -1; // } // if (o == null) { // return 1; // } // if (!(o instanceof Word)) { // return 1; // } // String t = ((Word) o).getName(); // if (t == null) { // return 1; // } // return this.name.compareTo(t); // } // } // Path: src/main/java/org/xm/similarity/text/JaroDistanceTextSimilarity.java import org.xm.tokenizer.Word; import java.util.List; /** * APDPlat - Application Product Development Platform * Copyright (c) 2013, 杨尚川, yang-shangchuan@qq.com * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p> * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.xm.similarity.text; /** * 文本相似度计算 * 判定方式:Jaro距离(Jaro Distance),编辑距离的一种类型 * 这里需要注意的是Jaro距离也就是相似度分值 * * @author 杨尚川 */ public class JaroDistanceTextSimilarity extends TextSimilarity { protected String shorterText = null; protected String longerText = null; /** * 计算相似度分值 * * @param words1 词列表1 * @param words2 词列表2 * @return 相似度分值 */ @Override
protected double getSimilarityImpl(List<Word> words1, List<Word> words2) {
shibing624/similarity
src/main/java/org/xm/similarity/word/pinyin/PinyinSimilarity.java
// Path: src/main/java/org/xm/similarity/ISimilarity.java // public interface ISimilarity { // /** // * 计算相似度 // * // * @param word1 词语1 // * @param word2 词语2 // * @return 相似度值 // */ // double getSimilarity(String word1, String word2); // } // // Path: src/main/java/org/xm/similarity/util/EditDistance.java // public class EditDistance { // // /** // * 获取删除代价 // * // * @return // */ // public int getDeletionCost() { // return 1; // } // // /** // * 获取插入代价 // * // * @return // */ // public int getInsertionCost() { // return 1; // } // // /** // * 获取替换代价 // * // * @return // */ // public int getSubstitutionCost(char a, char b) { // return (a == b) ? 0 : 1; // } // // public int getEditDistance(String S, String T) { // int[][] D = null; // if (S == null) // S = ""; // if (T == null) // T = ""; // // char[] a = S.toCharArray(); // char[] b = T.toCharArray(); // // int n = a.length; // 字符串S的长度 // int m = b.length; // 字符串T的长度 // // if (a.length == 0) { // return b.length; // } else if (b.length == 0) { // return a.length; // } // // D = new int[a.length + 1][b.length + 1]; // // /** 初始化D[i][0] */ // for (int i = 1; i <= n; i++) { // D[i][0] = D[i - 1][0] + getDeletionCost(); // } // // /** 初始化D[0][j] */ // for (int j = 1; j <= m; j++) { // D[0][j] = D[0][j - 1] + getInsertionCost(); // } // // for (int i = 1; i <= n; i++) { // for (int j = 1; j <= m; j++) { // D[i][j] = MathUtil.min(D[i - 1][j] + getDeletionCost(), D[i][j - 1] + getInsertionCost(), // D[i - 1][j - 1] + getSubstitutionCost(a[i - 1], b[j - 1])); // } // } // // return D[n][m]; // } // // /** // * 应与getEditDistance(S, T)等同 // * // * @param s // * @param t // * @return // */ // public static int getLevenshteinDistance(String s, String t) { // if (s == null || t == null) { // throw new IllegalArgumentException("Strings must not be null"); // } // int d[][]; // matrix // int n; // length of s // int m; // length of t // int i; // iterates through s // int j; // iterates through t // char s_i; // ith character of s // char t_j; // jth character of t // int cost; // cost // // // Step 1 // n = s.length(); // m = t.length(); // if (n == 0) { // return m; // } // if (m == 0) { // return n; // } // d = new int[n + 1][m + 1]; // // // Step 2 // for (i = 0; i <= n; i++) { // d[i][0] = i; // } // for (j = 0; j <= m; j++) { // d[0][j] = j; // } // // // Step 3 // for (i = 1; i <= n; i++) { // s_i = s.charAt(i - 1); // // // Step 4 // for (j = 1; j <= m; j++) { // t_j = t.charAt(j - 1); // // // Step 5 // if (s_i == t_j) { // cost = 0; // } else { // cost = 1; // } // // // Step 6 // d[i][j] = MathUtil.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); // } // } // // // Step 7 // return d[n][m]; // } // // } // // Path: src/main/java/org/xm/similarity/util/MathUtil.java // public class MathUtil { // // public static int min(int... values) { // int min = Integer.MAX_VALUE; // for (int v : values) { // min = (v < min) ? v : min; // } // return min; // } // // public static int max(int a, int b) { // return a > b ? a : b; // } // // }
import org.xm.similarity.ISimilarity; import org.xm.similarity.util.EditDistance; import org.xm.similarity.util.MathUtil; import java.util.Set;
package org.xm.similarity.word.pinyin; /** * 拼音计算两个词相似度,拼音用编辑距离表示相似程度 * * @author xuming */ public class PinyinSimilarity implements ISimilarity { @Override public double getSimilarity(String word1, String word2) { double max = 0.0; Set<String> pinyinSet1 = PinyinDictionary.getInstance().getPinyin(word1); Set<String> pinyinSet2 = PinyinDictionary.getInstance().getPinyin(word2); for (String pinyin1 : pinyinSet1) { for (String pinyin2 : pinyinSet2) {
// Path: src/main/java/org/xm/similarity/ISimilarity.java // public interface ISimilarity { // /** // * 计算相似度 // * // * @param word1 词语1 // * @param word2 词语2 // * @return 相似度值 // */ // double getSimilarity(String word1, String word2); // } // // Path: src/main/java/org/xm/similarity/util/EditDistance.java // public class EditDistance { // // /** // * 获取删除代价 // * // * @return // */ // public int getDeletionCost() { // return 1; // } // // /** // * 获取插入代价 // * // * @return // */ // public int getInsertionCost() { // return 1; // } // // /** // * 获取替换代价 // * // * @return // */ // public int getSubstitutionCost(char a, char b) { // return (a == b) ? 0 : 1; // } // // public int getEditDistance(String S, String T) { // int[][] D = null; // if (S == null) // S = ""; // if (T == null) // T = ""; // // char[] a = S.toCharArray(); // char[] b = T.toCharArray(); // // int n = a.length; // 字符串S的长度 // int m = b.length; // 字符串T的长度 // // if (a.length == 0) { // return b.length; // } else if (b.length == 0) { // return a.length; // } // // D = new int[a.length + 1][b.length + 1]; // // /** 初始化D[i][0] */ // for (int i = 1; i <= n; i++) { // D[i][0] = D[i - 1][0] + getDeletionCost(); // } // // /** 初始化D[0][j] */ // for (int j = 1; j <= m; j++) { // D[0][j] = D[0][j - 1] + getInsertionCost(); // } // // for (int i = 1; i <= n; i++) { // for (int j = 1; j <= m; j++) { // D[i][j] = MathUtil.min(D[i - 1][j] + getDeletionCost(), D[i][j - 1] + getInsertionCost(), // D[i - 1][j - 1] + getSubstitutionCost(a[i - 1], b[j - 1])); // } // } // // return D[n][m]; // } // // /** // * 应与getEditDistance(S, T)等同 // * // * @param s // * @param t // * @return // */ // public static int getLevenshteinDistance(String s, String t) { // if (s == null || t == null) { // throw new IllegalArgumentException("Strings must not be null"); // } // int d[][]; // matrix // int n; // length of s // int m; // length of t // int i; // iterates through s // int j; // iterates through t // char s_i; // ith character of s // char t_j; // jth character of t // int cost; // cost // // // Step 1 // n = s.length(); // m = t.length(); // if (n == 0) { // return m; // } // if (m == 0) { // return n; // } // d = new int[n + 1][m + 1]; // // // Step 2 // for (i = 0; i <= n; i++) { // d[i][0] = i; // } // for (j = 0; j <= m; j++) { // d[0][j] = j; // } // // // Step 3 // for (i = 1; i <= n; i++) { // s_i = s.charAt(i - 1); // // // Step 4 // for (j = 1; j <= m; j++) { // t_j = t.charAt(j - 1); // // // Step 5 // if (s_i == t_j) { // cost = 0; // } else { // cost = 1; // } // // // Step 6 // d[i][j] = MathUtil.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); // } // } // // // Step 7 // return d[n][m]; // } // // } // // Path: src/main/java/org/xm/similarity/util/MathUtil.java // public class MathUtil { // // public static int min(int... values) { // int min = Integer.MAX_VALUE; // for (int v : values) { // min = (v < min) ? v : min; // } // return min; // } // // public static int max(int a, int b) { // return a > b ? a : b; // } // // } // Path: src/main/java/org/xm/similarity/word/pinyin/PinyinSimilarity.java import org.xm.similarity.ISimilarity; import org.xm.similarity.util.EditDistance; import org.xm.similarity.util.MathUtil; import java.util.Set; package org.xm.similarity.word.pinyin; /** * 拼音计算两个词相似度,拼音用编辑距离表示相似程度 * * @author xuming */ public class PinyinSimilarity implements ISimilarity { @Override public double getSimilarity(String word1, String word2) { double max = 0.0; Set<String> pinyinSet1 = PinyinDictionary.getInstance().getPinyin(word1); Set<String> pinyinSet2 = PinyinDictionary.getInstance().getPinyin(word2); for (String pinyin1 : pinyinSet1) { for (String pinyin2 : pinyinSet2) {
double distance = new EditDistance().getEditDistance(pinyin1, pinyin2);
shibing624/similarity
src/main/java/org/xm/similarity/word/pinyin/PinyinSimilarity.java
// Path: src/main/java/org/xm/similarity/ISimilarity.java // public interface ISimilarity { // /** // * 计算相似度 // * // * @param word1 词语1 // * @param word2 词语2 // * @return 相似度值 // */ // double getSimilarity(String word1, String word2); // } // // Path: src/main/java/org/xm/similarity/util/EditDistance.java // public class EditDistance { // // /** // * 获取删除代价 // * // * @return // */ // public int getDeletionCost() { // return 1; // } // // /** // * 获取插入代价 // * // * @return // */ // public int getInsertionCost() { // return 1; // } // // /** // * 获取替换代价 // * // * @return // */ // public int getSubstitutionCost(char a, char b) { // return (a == b) ? 0 : 1; // } // // public int getEditDistance(String S, String T) { // int[][] D = null; // if (S == null) // S = ""; // if (T == null) // T = ""; // // char[] a = S.toCharArray(); // char[] b = T.toCharArray(); // // int n = a.length; // 字符串S的长度 // int m = b.length; // 字符串T的长度 // // if (a.length == 0) { // return b.length; // } else if (b.length == 0) { // return a.length; // } // // D = new int[a.length + 1][b.length + 1]; // // /** 初始化D[i][0] */ // for (int i = 1; i <= n; i++) { // D[i][0] = D[i - 1][0] + getDeletionCost(); // } // // /** 初始化D[0][j] */ // for (int j = 1; j <= m; j++) { // D[0][j] = D[0][j - 1] + getInsertionCost(); // } // // for (int i = 1; i <= n; i++) { // for (int j = 1; j <= m; j++) { // D[i][j] = MathUtil.min(D[i - 1][j] + getDeletionCost(), D[i][j - 1] + getInsertionCost(), // D[i - 1][j - 1] + getSubstitutionCost(a[i - 1], b[j - 1])); // } // } // // return D[n][m]; // } // // /** // * 应与getEditDistance(S, T)等同 // * // * @param s // * @param t // * @return // */ // public static int getLevenshteinDistance(String s, String t) { // if (s == null || t == null) { // throw new IllegalArgumentException("Strings must not be null"); // } // int d[][]; // matrix // int n; // length of s // int m; // length of t // int i; // iterates through s // int j; // iterates through t // char s_i; // ith character of s // char t_j; // jth character of t // int cost; // cost // // // Step 1 // n = s.length(); // m = t.length(); // if (n == 0) { // return m; // } // if (m == 0) { // return n; // } // d = new int[n + 1][m + 1]; // // // Step 2 // for (i = 0; i <= n; i++) { // d[i][0] = i; // } // for (j = 0; j <= m; j++) { // d[0][j] = j; // } // // // Step 3 // for (i = 1; i <= n; i++) { // s_i = s.charAt(i - 1); // // // Step 4 // for (j = 1; j <= m; j++) { // t_j = t.charAt(j - 1); // // // Step 5 // if (s_i == t_j) { // cost = 0; // } else { // cost = 1; // } // // // Step 6 // d[i][j] = MathUtil.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); // } // } // // // Step 7 // return d[n][m]; // } // // } // // Path: src/main/java/org/xm/similarity/util/MathUtil.java // public class MathUtil { // // public static int min(int... values) { // int min = Integer.MAX_VALUE; // for (int v : values) { // min = (v < min) ? v : min; // } // return min; // } // // public static int max(int a, int b) { // return a > b ? a : b; // } // // }
import org.xm.similarity.ISimilarity; import org.xm.similarity.util.EditDistance; import org.xm.similarity.util.MathUtil; import java.util.Set;
package org.xm.similarity.word.pinyin; /** * 拼音计算两个词相似度,拼音用编辑距离表示相似程度 * * @author xuming */ public class PinyinSimilarity implements ISimilarity { @Override public double getSimilarity(String word1, String word2) { double max = 0.0; Set<String> pinyinSet1 = PinyinDictionary.getInstance().getPinyin(word1); Set<String> pinyinSet2 = PinyinDictionary.getInstance().getPinyin(word2); for (String pinyin1 : pinyinSet1) { for (String pinyin2 : pinyinSet2) { double distance = new EditDistance().getEditDistance(pinyin1, pinyin2);
// Path: src/main/java/org/xm/similarity/ISimilarity.java // public interface ISimilarity { // /** // * 计算相似度 // * // * @param word1 词语1 // * @param word2 词语2 // * @return 相似度值 // */ // double getSimilarity(String word1, String word2); // } // // Path: src/main/java/org/xm/similarity/util/EditDistance.java // public class EditDistance { // // /** // * 获取删除代价 // * // * @return // */ // public int getDeletionCost() { // return 1; // } // // /** // * 获取插入代价 // * // * @return // */ // public int getInsertionCost() { // return 1; // } // // /** // * 获取替换代价 // * // * @return // */ // public int getSubstitutionCost(char a, char b) { // return (a == b) ? 0 : 1; // } // // public int getEditDistance(String S, String T) { // int[][] D = null; // if (S == null) // S = ""; // if (T == null) // T = ""; // // char[] a = S.toCharArray(); // char[] b = T.toCharArray(); // // int n = a.length; // 字符串S的长度 // int m = b.length; // 字符串T的长度 // // if (a.length == 0) { // return b.length; // } else if (b.length == 0) { // return a.length; // } // // D = new int[a.length + 1][b.length + 1]; // // /** 初始化D[i][0] */ // for (int i = 1; i <= n; i++) { // D[i][0] = D[i - 1][0] + getDeletionCost(); // } // // /** 初始化D[0][j] */ // for (int j = 1; j <= m; j++) { // D[0][j] = D[0][j - 1] + getInsertionCost(); // } // // for (int i = 1; i <= n; i++) { // for (int j = 1; j <= m; j++) { // D[i][j] = MathUtil.min(D[i - 1][j] + getDeletionCost(), D[i][j - 1] + getInsertionCost(), // D[i - 1][j - 1] + getSubstitutionCost(a[i - 1], b[j - 1])); // } // } // // return D[n][m]; // } // // /** // * 应与getEditDistance(S, T)等同 // * // * @param s // * @param t // * @return // */ // public static int getLevenshteinDistance(String s, String t) { // if (s == null || t == null) { // throw new IllegalArgumentException("Strings must not be null"); // } // int d[][]; // matrix // int n; // length of s // int m; // length of t // int i; // iterates through s // int j; // iterates through t // char s_i; // ith character of s // char t_j; // jth character of t // int cost; // cost // // // Step 1 // n = s.length(); // m = t.length(); // if (n == 0) { // return m; // } // if (m == 0) { // return n; // } // d = new int[n + 1][m + 1]; // // // Step 2 // for (i = 0; i <= n; i++) { // d[i][0] = i; // } // for (j = 0; j <= m; j++) { // d[0][j] = j; // } // // // Step 3 // for (i = 1; i <= n; i++) { // s_i = s.charAt(i - 1); // // // Step 4 // for (j = 1; j <= m; j++) { // t_j = t.charAt(j - 1); // // // Step 5 // if (s_i == t_j) { // cost = 0; // } else { // cost = 1; // } // // // Step 6 // d[i][j] = MathUtil.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); // } // } // // // Step 7 // return d[n][m]; // } // // } // // Path: src/main/java/org/xm/similarity/util/MathUtil.java // public class MathUtil { // // public static int min(int... values) { // int min = Integer.MAX_VALUE; // for (int v : values) { // min = (v < min) ? v : min; // } // return min; // } // // public static int max(int a, int b) { // return a > b ? a : b; // } // // } // Path: src/main/java/org/xm/similarity/word/pinyin/PinyinSimilarity.java import org.xm.similarity.ISimilarity; import org.xm.similarity.util.EditDistance; import org.xm.similarity.util.MathUtil; import java.util.Set; package org.xm.similarity.word.pinyin; /** * 拼音计算两个词相似度,拼音用编辑距离表示相似程度 * * @author xuming */ public class PinyinSimilarity implements ISimilarity { @Override public double getSimilarity(String word1, String word2) { double max = 0.0; Set<String> pinyinSet1 = PinyinDictionary.getInstance().getPinyin(word1); Set<String> pinyinSet2 = PinyinDictionary.getInstance().getPinyin(word2); for (String pinyin1 : pinyinSet1) { for (String pinyin2 : pinyinSet2) { double distance = new EditDistance().getEditDistance(pinyin1, pinyin2);
double similarity = 1 - distance / (MathUtil.max(pinyin1.length(), pinyin2.length()));
shibing624/similarity
src/main/java/org/xm/word2vec/vec/Learn.java
// Path: src/main/java/org/xm/word2vec/domain/HiddenNeuron.java // public class HiddenNeuron extends Neuron { // public double[] syn1;// 隐藏层 -> 输出层 // // public HiddenNeuron(int layerSize) { // syn1 = new double[layerSize]; // } // } // // Path: src/main/java/org/xm/word2vec/domain/Neuron.java // public abstract class Neuron implements Comparable<Neuron> { // public double freq; // public Neuron parent; // public int code; // public int category = -1; // // @Override // public int compareTo(Neuron o) { // if (this.category == o.category) { // if (this.freq > o.freq) { // return 1; // } else // return -1; // } else if (this.category > o.category) { // return 1; // } else { // return 0; // } // } // } // // Path: src/main/java/org/xm/word2vec/domain/WordNeuron.java // public class WordNeuron extends Neuron { // public String name; // public double[] syn0; // public List<Neuron> neurons;// 路径 // public int[] codeArray; // // public List<Neuron> makeNeurons() { // if (neurons != null) return neurons; // Neuron neuron = this; // neurons = new LinkedList<>(); // while ((neuron = neuron.parent) != null) { // neurons.add(neuron); // } // Collections.reverse(neurons); // codeArray = new int[neurons.size()]; // for (int i = 1; i < neurons.size(); i++) { // codeArray[i - 1] = neurons.get(i).code; // } // // codeArray[codeArray.length - 1] = this.code; // return neurons; // } // // public WordNeuron(String name, double freq, int layerSize) { // this.name = name; // this.freq = freq; // this.syn0 = new double[layerSize]; // Random random = new Random(); // for (int i = 0; i < syn0.length; i++) { // syn0[i] = (random.nextDouble() - 0.5) / layerSize; // } // } // // /** // * huffman tree // * // * @param name // * @param freq // * @param category // * @param layerSize // */ // public WordNeuron(String name, double freq, int category, int layerSize) { // this.name = name; // this.freq = freq; // this.syn0 = new double[layerSize]; // this.category = category; // Random random = new Random(); // for (int i = 0; i < syn0.length; i++) { // syn0[i] = (random.nextDouble() - 0.5) / layerSize; // } // } // }
import org.xm.word2vec.domain.HiddenNeuron; import org.xm.word2vec.domain.Neuron; import org.xm.word2vec.domain.WordNeuron; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
expTable[i] = expTable[i] / (expTable[i] + 1); } } /** * 训练模型 * * @param file * @throws IOException */ private void trainModel(File file) throws IOException { try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) { String temp; long nextRandom = 5; int wordCount = 0; int lastWordCount = 0; int wordCountActual = 0; while ((temp = br.readLine()) != null) { if (wordCount - lastWordCount > 10000) { System.out.println("alpha:" + alpha + "\tProgress: " + (int) (wordCountActual / (double) (trainWordsCount + 1) * 100) + "%"); wordCountActual += wordCount - lastWordCount; lastWordCount = wordCount; alpha = startingAlpha * (1 - wordCountActual / (double) (trainWordsCount + 1)); if (alpha < startingAlpha * 0.0001) { alpha = startingAlpha * 0.0001; } } String[] strs = temp.split("[\t ]+"); wordCount += strs.length;
// Path: src/main/java/org/xm/word2vec/domain/HiddenNeuron.java // public class HiddenNeuron extends Neuron { // public double[] syn1;// 隐藏层 -> 输出层 // // public HiddenNeuron(int layerSize) { // syn1 = new double[layerSize]; // } // } // // Path: src/main/java/org/xm/word2vec/domain/Neuron.java // public abstract class Neuron implements Comparable<Neuron> { // public double freq; // public Neuron parent; // public int code; // public int category = -1; // // @Override // public int compareTo(Neuron o) { // if (this.category == o.category) { // if (this.freq > o.freq) { // return 1; // } else // return -1; // } else if (this.category > o.category) { // return 1; // } else { // return 0; // } // } // } // // Path: src/main/java/org/xm/word2vec/domain/WordNeuron.java // public class WordNeuron extends Neuron { // public String name; // public double[] syn0; // public List<Neuron> neurons;// 路径 // public int[] codeArray; // // public List<Neuron> makeNeurons() { // if (neurons != null) return neurons; // Neuron neuron = this; // neurons = new LinkedList<>(); // while ((neuron = neuron.parent) != null) { // neurons.add(neuron); // } // Collections.reverse(neurons); // codeArray = new int[neurons.size()]; // for (int i = 1; i < neurons.size(); i++) { // codeArray[i - 1] = neurons.get(i).code; // } // // codeArray[codeArray.length - 1] = this.code; // return neurons; // } // // public WordNeuron(String name, double freq, int layerSize) { // this.name = name; // this.freq = freq; // this.syn0 = new double[layerSize]; // Random random = new Random(); // for (int i = 0; i < syn0.length; i++) { // syn0[i] = (random.nextDouble() - 0.5) / layerSize; // } // } // // /** // * huffman tree // * // * @param name // * @param freq // * @param category // * @param layerSize // */ // public WordNeuron(String name, double freq, int category, int layerSize) { // this.name = name; // this.freq = freq; // this.syn0 = new double[layerSize]; // this.category = category; // Random random = new Random(); // for (int i = 0; i < syn0.length; i++) { // syn0[i] = (random.nextDouble() - 0.5) / layerSize; // } // } // } // Path: src/main/java/org/xm/word2vec/vec/Learn.java import org.xm.word2vec.domain.HiddenNeuron; import org.xm.word2vec.domain.Neuron; import org.xm.word2vec.domain.WordNeuron; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; expTable[i] = expTable[i] / (expTable[i] + 1); } } /** * 训练模型 * * @param file * @throws IOException */ private void trainModel(File file) throws IOException { try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) { String temp; long nextRandom = 5; int wordCount = 0; int lastWordCount = 0; int wordCountActual = 0; while ((temp = br.readLine()) != null) { if (wordCount - lastWordCount > 10000) { System.out.println("alpha:" + alpha + "\tProgress: " + (int) (wordCountActual / (double) (trainWordsCount + 1) * 100) + "%"); wordCountActual += wordCount - lastWordCount; lastWordCount = wordCount; alpha = startingAlpha * (1 - wordCountActual / (double) (trainWordsCount + 1)); if (alpha < startingAlpha * 0.0001) { alpha = startingAlpha * 0.0001; } } String[] strs = temp.split("[\t ]+"); wordCount += strs.length;
List<WordNeuron> sentence = new ArrayList<WordNeuron>();
shibing624/similarity
src/main/java/org/xm/word2vec/vec/Learn.java
// Path: src/main/java/org/xm/word2vec/domain/HiddenNeuron.java // public class HiddenNeuron extends Neuron { // public double[] syn1;// 隐藏层 -> 输出层 // // public HiddenNeuron(int layerSize) { // syn1 = new double[layerSize]; // } // } // // Path: src/main/java/org/xm/word2vec/domain/Neuron.java // public abstract class Neuron implements Comparable<Neuron> { // public double freq; // public Neuron parent; // public int code; // public int category = -1; // // @Override // public int compareTo(Neuron o) { // if (this.category == o.category) { // if (this.freq > o.freq) { // return 1; // } else // return -1; // } else if (this.category > o.category) { // return 1; // } else { // return 0; // } // } // } // // Path: src/main/java/org/xm/word2vec/domain/WordNeuron.java // public class WordNeuron extends Neuron { // public String name; // public double[] syn0; // public List<Neuron> neurons;// 路径 // public int[] codeArray; // // public List<Neuron> makeNeurons() { // if (neurons != null) return neurons; // Neuron neuron = this; // neurons = new LinkedList<>(); // while ((neuron = neuron.parent) != null) { // neurons.add(neuron); // } // Collections.reverse(neurons); // codeArray = new int[neurons.size()]; // for (int i = 1; i < neurons.size(); i++) { // codeArray[i - 1] = neurons.get(i).code; // } // // codeArray[codeArray.length - 1] = this.code; // return neurons; // } // // public WordNeuron(String name, double freq, int layerSize) { // this.name = name; // this.freq = freq; // this.syn0 = new double[layerSize]; // Random random = new Random(); // for (int i = 0; i < syn0.length; i++) { // syn0[i] = (random.nextDouble() - 0.5) / layerSize; // } // } // // /** // * huffman tree // * // * @param name // * @param freq // * @param category // * @param layerSize // */ // public WordNeuron(String name, double freq, int category, int layerSize) { // this.name = name; // this.freq = freq; // this.syn0 = new double[layerSize]; // this.category = category; // Random random = new Random(); // for (int i = 0; i < syn0.length; i++) { // syn0[i] = (random.nextDouble() - 0.5) / layerSize; // } // } // }
import org.xm.word2vec.domain.HiddenNeuron; import org.xm.word2vec.domain.Neuron; import org.xm.word2vec.domain.WordNeuron; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
} } } System.out.println("Vocab size: " + wordMap.size()); System.out.println("Words in train file: " + trainWordsCount); System.out.println("sucess train over!"); } } /** * skip gram 模型训练 */ private void skipGram(int index, List<WordNeuron> sentence, int b) { WordNeuron word = sentence.get(index); int a, c = 0; for (a = b; a < window * 2 + 1 - b; a++) { if (a == window) { continue; } c = index - window + a; if (c < 0 || c >= sentence.size()) { continue; } double[] neu1e = new double[layerSize];// 误差项 // HIERARCHICAL SOFTMAX List<Neuron> neurons = word.neurons; WordNeuron we = sentence.get(c); for (int i = 0; i < neurons.size(); i++) {
// Path: src/main/java/org/xm/word2vec/domain/HiddenNeuron.java // public class HiddenNeuron extends Neuron { // public double[] syn1;// 隐藏层 -> 输出层 // // public HiddenNeuron(int layerSize) { // syn1 = new double[layerSize]; // } // } // // Path: src/main/java/org/xm/word2vec/domain/Neuron.java // public abstract class Neuron implements Comparable<Neuron> { // public double freq; // public Neuron parent; // public int code; // public int category = -1; // // @Override // public int compareTo(Neuron o) { // if (this.category == o.category) { // if (this.freq > o.freq) { // return 1; // } else // return -1; // } else if (this.category > o.category) { // return 1; // } else { // return 0; // } // } // } // // Path: src/main/java/org/xm/word2vec/domain/WordNeuron.java // public class WordNeuron extends Neuron { // public String name; // public double[] syn0; // public List<Neuron> neurons;// 路径 // public int[] codeArray; // // public List<Neuron> makeNeurons() { // if (neurons != null) return neurons; // Neuron neuron = this; // neurons = new LinkedList<>(); // while ((neuron = neuron.parent) != null) { // neurons.add(neuron); // } // Collections.reverse(neurons); // codeArray = new int[neurons.size()]; // for (int i = 1; i < neurons.size(); i++) { // codeArray[i - 1] = neurons.get(i).code; // } // // codeArray[codeArray.length - 1] = this.code; // return neurons; // } // // public WordNeuron(String name, double freq, int layerSize) { // this.name = name; // this.freq = freq; // this.syn0 = new double[layerSize]; // Random random = new Random(); // for (int i = 0; i < syn0.length; i++) { // syn0[i] = (random.nextDouble() - 0.5) / layerSize; // } // } // // /** // * huffman tree // * // * @param name // * @param freq // * @param category // * @param layerSize // */ // public WordNeuron(String name, double freq, int category, int layerSize) { // this.name = name; // this.freq = freq; // this.syn0 = new double[layerSize]; // this.category = category; // Random random = new Random(); // for (int i = 0; i < syn0.length; i++) { // syn0[i] = (random.nextDouble() - 0.5) / layerSize; // } // } // } // Path: src/main/java/org/xm/word2vec/vec/Learn.java import org.xm.word2vec.domain.HiddenNeuron; import org.xm.word2vec.domain.Neuron; import org.xm.word2vec.domain.WordNeuron; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; } } } System.out.println("Vocab size: " + wordMap.size()); System.out.println("Words in train file: " + trainWordsCount); System.out.println("sucess train over!"); } } /** * skip gram 模型训练 */ private void skipGram(int index, List<WordNeuron> sentence, int b) { WordNeuron word = sentence.get(index); int a, c = 0; for (a = b; a < window * 2 + 1 - b; a++) { if (a == window) { continue; } c = index - window + a; if (c < 0 || c >= sentence.size()) { continue; } double[] neu1e = new double[layerSize];// 误差项 // HIERARCHICAL SOFTMAX List<Neuron> neurons = word.neurons; WordNeuron we = sentence.get(c); for (int i = 0; i < neurons.size(); i++) {
HiddenNeuron out = (HiddenNeuron) neurons.get(i);
shibing624/similarity
src/main/java/org/xm/tokenizer/WordFreqStatistics.java
// Path: src/main/java/org/xm/Similarity.java // public class Similarity { // // public static final class Config { // /** // * 词林编码路径 // */ // public static String CilinPath = "cilin.db.gz"; // /** // * 拼音词典路径 // */ // public static String PinyinPath = "F02-GB2312-to-PuTongHua-PinYin.txt"; // /** // * concept路径 // */ // public static String ConceptPath = "concept.dat"; // /** // * concept.xml.gz路径 // */ // public static String ConceptXmlPath = "concept.xml.gz"; // /** // * 义原关系的路径 // */ // public static String SememePath = "sememe.dat"; // /** // * 义原数据路径 // */ // public static String SememeXmlPath = "sememe.xml.gz"; // /** // * 词频统计输出路径 // */ // public static String StatisticsResultPath = "data/WordFrequencyStatistics-Result.txt"; // // } // // private Similarity() { // } // // // /** // * 词语相似度 // * 计算词林编码相似度 // * // * @param word1 word // * @param word2 word // * @return float // */ // public static double cilinSimilarity(String word1, String word2) { // return CilinSimilarity.getInstance().getSimilarity(word1, word2); // } // // /** // * 词语相似度 // * 计算拼音相似度 // * // * @param word1 word // * @param word2 word // * @return float // */ // public static double pinyinSimilarity(String word1, String word2) { // return PhraseSimilarity.getInstance().getSimilarity(word1, word2); // } // // /** // * 词语相似度 // * 计算字面相似度 // * // * @param word1 word // * @param word2 word // * @return float // */ // public static double charBasedSimilarity(String word1, String word2) { // return CharBasedSimilarity.getInstance().getSimilarity(word1, word2); // } // // /** // * 词语相似度 // * 计算语义概念相似度 // * // * @param word1 // * @param word2 // * @return // */ // public static double conceptSimilarity(String word1, String word2) { // return ConceptSimilarity.getInstance().getSimilarity(word1, word2); // } // // /** // * 短语相似度 // * // * @param pharse1 // * @param pharse2 // * @return // */ // public static double phraseSimilarity(String pharse1, String pharse2) { // return PhraseSimilarity.getInstance().getSimilarity(pharse1, pharse2); // } // // /** // * 句子相似度 // * 词形和词序结合法 // * // * @param sentence1 // * @param sentence2 // * @return // */ // public static double morphoSimilarity(String sentence1, String sentence2) { // return MorphoSimilarity.getInstance().getSimilarity(sentence1, sentence2); // } // // /** // * 句子相似度 // * 夏天编辑距离法 // * // * @param sentence1 // * @param sentence2 // * @return // */ // public static double editDistanceSimilarity(String sentence1, String sentence2) { // EditDistance ed = new NewEditDistanceSimilarity(); // return ed.getSimilarity(sentence1, sentence2); // } // // /** // * 句子相似度 // * Gregor编辑距离算法 // * // * @param sentence1 // * @param sentence2 // * @return // */ // public static double gregorEditDistanceSimilarity(String sentence1, String sentence2) { // EditDistance ed = new GregorEditDistanceSimilarity(); // return ed.getSimilarity(sentence1, sentence2); // } // // /** // * 句子相似度 // * 标准编辑距离算法 // * // * @param sentence1 // * @param sentence2 // * @return // */ // public static double standardEditDistanceSimilarity(String sentence1, String sentence2) { // EditDistance ed = new StandardEditDistanceSimilarity(); // return ed.getSimilarity(sentence1, sentence2); // } // // /** // * 词语情感分析 // * // * @param word // * @return // */ // public static double tendency(String word) { // HownetWordTendency hownetWordTendency = new HownetWordTendency(); // return hownetWordTendency.getTendency(word); // } // // }
import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.corpus.io.IOUtil; import com.hankcs.hanlp.seg.Segment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xm.Similarity; import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors;
package org.xm.tokenizer; /** * 词频统计工具 * * @author xuming */ public class WordFreqStatistics { protected static final Logger logger = LoggerFactory.getLogger(WordFreqStatistics.class);
// Path: src/main/java/org/xm/Similarity.java // public class Similarity { // // public static final class Config { // /** // * 词林编码路径 // */ // public static String CilinPath = "cilin.db.gz"; // /** // * 拼音词典路径 // */ // public static String PinyinPath = "F02-GB2312-to-PuTongHua-PinYin.txt"; // /** // * concept路径 // */ // public static String ConceptPath = "concept.dat"; // /** // * concept.xml.gz路径 // */ // public static String ConceptXmlPath = "concept.xml.gz"; // /** // * 义原关系的路径 // */ // public static String SememePath = "sememe.dat"; // /** // * 义原数据路径 // */ // public static String SememeXmlPath = "sememe.xml.gz"; // /** // * 词频统计输出路径 // */ // public static String StatisticsResultPath = "data/WordFrequencyStatistics-Result.txt"; // // } // // private Similarity() { // } // // // /** // * 词语相似度 // * 计算词林编码相似度 // * // * @param word1 word // * @param word2 word // * @return float // */ // public static double cilinSimilarity(String word1, String word2) { // return CilinSimilarity.getInstance().getSimilarity(word1, word2); // } // // /** // * 词语相似度 // * 计算拼音相似度 // * // * @param word1 word // * @param word2 word // * @return float // */ // public static double pinyinSimilarity(String word1, String word2) { // return PhraseSimilarity.getInstance().getSimilarity(word1, word2); // } // // /** // * 词语相似度 // * 计算字面相似度 // * // * @param word1 word // * @param word2 word // * @return float // */ // public static double charBasedSimilarity(String word1, String word2) { // return CharBasedSimilarity.getInstance().getSimilarity(word1, word2); // } // // /** // * 词语相似度 // * 计算语义概念相似度 // * // * @param word1 // * @param word2 // * @return // */ // public static double conceptSimilarity(String word1, String word2) { // return ConceptSimilarity.getInstance().getSimilarity(word1, word2); // } // // /** // * 短语相似度 // * // * @param pharse1 // * @param pharse2 // * @return // */ // public static double phraseSimilarity(String pharse1, String pharse2) { // return PhraseSimilarity.getInstance().getSimilarity(pharse1, pharse2); // } // // /** // * 句子相似度 // * 词形和词序结合法 // * // * @param sentence1 // * @param sentence2 // * @return // */ // public static double morphoSimilarity(String sentence1, String sentence2) { // return MorphoSimilarity.getInstance().getSimilarity(sentence1, sentence2); // } // // /** // * 句子相似度 // * 夏天编辑距离法 // * // * @param sentence1 // * @param sentence2 // * @return // */ // public static double editDistanceSimilarity(String sentence1, String sentence2) { // EditDistance ed = new NewEditDistanceSimilarity(); // return ed.getSimilarity(sentence1, sentence2); // } // // /** // * 句子相似度 // * Gregor编辑距离算法 // * // * @param sentence1 // * @param sentence2 // * @return // */ // public static double gregorEditDistanceSimilarity(String sentence1, String sentence2) { // EditDistance ed = new GregorEditDistanceSimilarity(); // return ed.getSimilarity(sentence1, sentence2); // } // // /** // * 句子相似度 // * 标准编辑距离算法 // * // * @param sentence1 // * @param sentence2 // * @return // */ // public static double standardEditDistanceSimilarity(String sentence1, String sentence2) { // EditDistance ed = new StandardEditDistanceSimilarity(); // return ed.getSimilarity(sentence1, sentence2); // } // // /** // * 词语情感分析 // * // * @param word // * @return // */ // public static double tendency(String word) { // HownetWordTendency hownetWordTendency = new HownetWordTendency(); // return hownetWordTendency.getTendency(word); // } // // } // Path: src/main/java/org/xm/tokenizer/WordFreqStatistics.java import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.corpus.io.IOUtil; import com.hankcs.hanlp.seg.Segment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xm.Similarity; import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; package org.xm.tokenizer; /** * 词频统计工具 * * @author xuming */ public class WordFreqStatistics { protected static final Logger logger = LoggerFactory.getLogger(WordFreqStatistics.class);
private String resultPath = Similarity.Config.StatisticsResultPath;
gmcnew/pax
src/com/gregmcnew/android/pax/AI.java
// Path: src/com/gregmcnew/android/pax/Player.java // public enum BuildTarget { FIGHTER, BOMBER, FRIGATE, UPGRADE, NONE }
import com.gregmcnew.android.pax.Player.BuildTarget;
mWeights.w[1] = -0.0924f; mWeights.w[2] = 0.5419f; mWeights.w[3] = 0.6610f; mWeights.w[4] = 0.6736f; mWeights.w[5] = 0.3347f; mWeights.w[6] = -0.3005f; mWeights.w[7] = -0.0161f; mWeights.w[8] = 0.6163f; for (int i = 0; i < AIWeights.NUM_WEIGHTS - 1; i++) { mWeights.w[i] = 0; } mWeights.w[1] = 9; } */ } public AIWeights getWeights() { return mWeights.clone(); } public void randomizeWeights() { mWeights.randomize(); } public void setWeights(AIWeights weights) { mWeights = weights; } public void buildFinished() {
// Path: src/com/gregmcnew/android/pax/Player.java // public enum BuildTarget { FIGHTER, BOMBER, FRIGATE, UPGRADE, NONE } // Path: src/com/gregmcnew/android/pax/AI.java import com.gregmcnew.android.pax.Player.BuildTarget; mWeights.w[1] = -0.0924f; mWeights.w[2] = 0.5419f; mWeights.w[3] = 0.6610f; mWeights.w[4] = 0.6736f; mWeights.w[5] = 0.3347f; mWeights.w[6] = -0.3005f; mWeights.w[7] = -0.0161f; mWeights.w[8] = 0.6163f; for (int i = 0; i < AIWeights.NUM_WEIGHTS - 1; i++) { mWeights.w[i] = 0; } mWeights.w[1] = 9; } */ } public AIWeights getWeights() { return mWeights.clone(); } public void randomizeWeights() { mWeights.randomize(); } public void setWeights(AIWeights weights) { mWeights = weights; } public void buildFinished() {
mPlayer.mBuildTarget = Player.BuildTarget.NONE;
gen2brain/bukanir
android/src/main/java/com/bukanir/android/application/Favorites.java
// Path: android/src/main/java/com/bukanir/android/entities/Movie.java // public class Movie implements Comparable<Movie>, Serializable { // // public String id; // public String title; // public String year; // public String posterSmall; // public String posterMedium; // public String posterLarge; // public String posterXLarge; // public String size; // public String sizeHuman; // public String seeders; // public String magnetLink; // public String release; // public String category; // public String season; // public String episode; // public String quality; // // @Override // public int compareTo(@NonNull Movie m) { // return Integer.valueOf(m.seeders) - Integer.valueOf(this.seeders); // } // // @Override // public boolean equals(Object obj) { // if(obj == null) return false; // if(obj == this) return true; // if(!(obj instanceof Movie)) return false; // Movie movie = (Movie) obj; // return movie.id.equals(this.id); // } // // @Override // public String toString() { // StringBuilder result = new StringBuilder(); // String NL = System.getProperty("line.separator"); // // result.append(((Object)this).getClass().getName() + " {" + NL); // result.append(" title: " + this.title + NL); // result.append(" id: " + this.id + NL); // result.append(" year: " + this.year + NL); // result.append(" posterSmall: " + this.posterSmall + NL); // result.append(" posterMedium: " + this.posterMedium + NL); // result.append(" posterLarge: " + this.posterLarge + NL); // result.append(" posterXLarge: " + this.posterXLarge + NL); // result.append(" size: " + this.size + NL); // result.append(" sizeHuman: " + this.sizeHuman + NL); // result.append(" seeders: " + this.seeders + NL); // result.append(" magnetLink: " + this.magnetLink + NL); // result.append(" release: " + this.release + NL); // result.append(" category: " + this.category + NL); // result.append(" season: " + this.season + NL); // result.append(" episode: " + this.episode + NL); // result.append(" quality: " + this.quality + NL); // result.append("}" + NL); // // return result.toString(); // } // // }
import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.bukanir.android.entities.Movie; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections;
package com.bukanir.android.application; public class Favorites { private Context context; private SharedPreferences preferences; public Favorites(Context context) { this.context = context.getApplicationContext(); preferences = PreferenceManager.getDefaultSharedPreferences(this.context); }
// Path: android/src/main/java/com/bukanir/android/entities/Movie.java // public class Movie implements Comparable<Movie>, Serializable { // // public String id; // public String title; // public String year; // public String posterSmall; // public String posterMedium; // public String posterLarge; // public String posterXLarge; // public String size; // public String sizeHuman; // public String seeders; // public String magnetLink; // public String release; // public String category; // public String season; // public String episode; // public String quality; // // @Override // public int compareTo(@NonNull Movie m) { // return Integer.valueOf(m.seeders) - Integer.valueOf(this.seeders); // } // // @Override // public boolean equals(Object obj) { // if(obj == null) return false; // if(obj == this) return true; // if(!(obj instanceof Movie)) return false; // Movie movie = (Movie) obj; // return movie.id.equals(this.id); // } // // @Override // public String toString() { // StringBuilder result = new StringBuilder(); // String NL = System.getProperty("line.separator"); // // result.append(((Object)this).getClass().getName() + " {" + NL); // result.append(" title: " + this.title + NL); // result.append(" id: " + this.id + NL); // result.append(" year: " + this.year + NL); // result.append(" posterSmall: " + this.posterSmall + NL); // result.append(" posterMedium: " + this.posterMedium + NL); // result.append(" posterLarge: " + this.posterLarge + NL); // result.append(" posterXLarge: " + this.posterXLarge + NL); // result.append(" size: " + this.size + NL); // result.append(" sizeHuman: " + this.sizeHuman + NL); // result.append(" seeders: " + this.seeders + NL); // result.append(" magnetLink: " + this.magnetLink + NL); // result.append(" release: " + this.release + NL); // result.append(" category: " + this.category + NL); // result.append(" season: " + this.season + NL); // result.append(" episode: " + this.episode + NL); // result.append(" quality: " + this.quality + NL); // result.append("}" + NL); // // return result.toString(); // } // // } // Path: android/src/main/java/com/bukanir/android/application/Favorites.java import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.bukanir.android.entities.Movie; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; package com.bukanir.android.application; public class Favorites { private Context context; private SharedPreferences preferences; public Favorites(Context context) { this.context = context.getApplicationContext(); preferences = PreferenceManager.getDefaultSharedPreferences(this.context); }
public ArrayList<Movie> getFavorites() {
gen2brain/bukanir
android/src/main/java/com/bukanir/android/clients/Torrent2HttpClient.java
// Path: android/src/main/java/com/bukanir/android/entities/TorrentFile.java // public class TorrentFile implements Comparable<TorrentFile>, Serializable { // // public String name; // public String save_path; // public String url; // public String size; // public String offset; // public String download; // public String progress; // // @Override // public int compareTo(TorrentFile f) { // return (int) (Long.valueOf(f.size) - Long.valueOf(this.size)); // } // // @Override // public String toString() { // StringBuilder result = new StringBuilder(); // String NL = System.getProperty("line.separator"); // // result.append(((Object)this).getClass().getName() + " {" + NL); // result.append(" name: " + this.name + NL); // result.append(" save_path: " + this.save_path + NL); // result.append(" url: " + this.url + NL); // result.append(" size: " + this.size + NL); // result.append(" offset: " + this.offset + NL); // result.append(" download: " + this.download + NL); // result.append(" progress: " + this.progress + NL); // result.append("}" + NL); // // return result.toString(); // } // // } // // Path: android/src/main/java/com/bukanir/android/entities/TorrentFiles.java // public class TorrentFiles { // public List<TorrentFile> files = new ArrayList<TorrentFile>(); // } // // Path: android/src/main/java/com/bukanir/android/entities/TorrentStatus.java // public class TorrentStatus { // // public String name; // public String state; // public String state_str; // public String error; // public String progress; // public String download_rate; // public String upload_rate; // public String total_download; // public String total_upload; // public String num_peers; // public String num_seeds; // public String total_seeds; // public String total_peers; // // @Override // public String toString() { // StringBuilder result = new StringBuilder(); // String NL = System.getProperty("line.separator"); // // result.append(((Object)this).getClass().getName() + " {" + NL); // result.append(" name: " + this.name + NL); // result.append(" state: " + this.state + NL); // result.append(" state_str: " + this.state_str + NL); // result.append(" error: " + this.error + NL); // result.append(" progress: " + this.progress + NL); // result.append(" download_rate: " + this.download_rate + NL); // result.append(" upload_rate: " + this.upload_rate + NL); // result.append(" total_download: " + this.total_download + NL); // result.append(" total_upload: " + this.total_upload + NL); // result.append(" num_peers: " + this.num_peers + NL); // result.append(" num_seeds: " + this.num_seeds + NL); // result.append(" total_seeds: " + this.total_seeds + NL); // result.append(" total_peers: " + this.total_peers + NL); // result.append("}" + NL); // // return result.toString(); // } // }
import com.google.gson.Gson; import com.bukanir.android.entities.TorrentFile; import com.bukanir.android.entities.TorrentFiles; import com.bukanir.android.entities.TorrentStatus; import java.util.Collections; import go.bukanir.Bukanir;
package com.bukanir.android.clients; public class Torrent2HttpClient { public boolean waitStartup() { return Bukanir.torrentWaitStartup(); }
// Path: android/src/main/java/com/bukanir/android/entities/TorrentFile.java // public class TorrentFile implements Comparable<TorrentFile>, Serializable { // // public String name; // public String save_path; // public String url; // public String size; // public String offset; // public String download; // public String progress; // // @Override // public int compareTo(TorrentFile f) { // return (int) (Long.valueOf(f.size) - Long.valueOf(this.size)); // } // // @Override // public String toString() { // StringBuilder result = new StringBuilder(); // String NL = System.getProperty("line.separator"); // // result.append(((Object)this).getClass().getName() + " {" + NL); // result.append(" name: " + this.name + NL); // result.append(" save_path: " + this.save_path + NL); // result.append(" url: " + this.url + NL); // result.append(" size: " + this.size + NL); // result.append(" offset: " + this.offset + NL); // result.append(" download: " + this.download + NL); // result.append(" progress: " + this.progress + NL); // result.append("}" + NL); // // return result.toString(); // } // // } // // Path: android/src/main/java/com/bukanir/android/entities/TorrentFiles.java // public class TorrentFiles { // public List<TorrentFile> files = new ArrayList<TorrentFile>(); // } // // Path: android/src/main/java/com/bukanir/android/entities/TorrentStatus.java // public class TorrentStatus { // // public String name; // public String state; // public String state_str; // public String error; // public String progress; // public String download_rate; // public String upload_rate; // public String total_download; // public String total_upload; // public String num_peers; // public String num_seeds; // public String total_seeds; // public String total_peers; // // @Override // public String toString() { // StringBuilder result = new StringBuilder(); // String NL = System.getProperty("line.separator"); // // result.append(((Object)this).getClass().getName() + " {" + NL); // result.append(" name: " + this.name + NL); // result.append(" state: " + this.state + NL); // result.append(" state_str: " + this.state_str + NL); // result.append(" error: " + this.error + NL); // result.append(" progress: " + this.progress + NL); // result.append(" download_rate: " + this.download_rate + NL); // result.append(" upload_rate: " + this.upload_rate + NL); // result.append(" total_download: " + this.total_download + NL); // result.append(" total_upload: " + this.total_upload + NL); // result.append(" num_peers: " + this.num_peers + NL); // result.append(" num_seeds: " + this.num_seeds + NL); // result.append(" total_seeds: " + this.total_seeds + NL); // result.append(" total_peers: " + this.total_peers + NL); // result.append("}" + NL); // // return result.toString(); // } // } // Path: android/src/main/java/com/bukanir/android/clients/Torrent2HttpClient.java import com.google.gson.Gson; import com.bukanir.android.entities.TorrentFile; import com.bukanir.android.entities.TorrentFiles; import com.bukanir.android.entities.TorrentStatus; import java.util.Collections; import go.bukanir.Bukanir; package com.bukanir.android.clients; public class Torrent2HttpClient { public boolean waitStartup() { return Bukanir.torrentWaitStartup(); }
public TorrentStatus getStatus() {
gen2brain/bukanir
android/src/main/java/com/bukanir/android/clients/Torrent2HttpClient.java
// Path: android/src/main/java/com/bukanir/android/entities/TorrentFile.java // public class TorrentFile implements Comparable<TorrentFile>, Serializable { // // public String name; // public String save_path; // public String url; // public String size; // public String offset; // public String download; // public String progress; // // @Override // public int compareTo(TorrentFile f) { // return (int) (Long.valueOf(f.size) - Long.valueOf(this.size)); // } // // @Override // public String toString() { // StringBuilder result = new StringBuilder(); // String NL = System.getProperty("line.separator"); // // result.append(((Object)this).getClass().getName() + " {" + NL); // result.append(" name: " + this.name + NL); // result.append(" save_path: " + this.save_path + NL); // result.append(" url: " + this.url + NL); // result.append(" size: " + this.size + NL); // result.append(" offset: " + this.offset + NL); // result.append(" download: " + this.download + NL); // result.append(" progress: " + this.progress + NL); // result.append("}" + NL); // // return result.toString(); // } // // } // // Path: android/src/main/java/com/bukanir/android/entities/TorrentFiles.java // public class TorrentFiles { // public List<TorrentFile> files = new ArrayList<TorrentFile>(); // } // // Path: android/src/main/java/com/bukanir/android/entities/TorrentStatus.java // public class TorrentStatus { // // public String name; // public String state; // public String state_str; // public String error; // public String progress; // public String download_rate; // public String upload_rate; // public String total_download; // public String total_upload; // public String num_peers; // public String num_seeds; // public String total_seeds; // public String total_peers; // // @Override // public String toString() { // StringBuilder result = new StringBuilder(); // String NL = System.getProperty("line.separator"); // // result.append(((Object)this).getClass().getName() + " {" + NL); // result.append(" name: " + this.name + NL); // result.append(" state: " + this.state + NL); // result.append(" state_str: " + this.state_str + NL); // result.append(" error: " + this.error + NL); // result.append(" progress: " + this.progress + NL); // result.append(" download_rate: " + this.download_rate + NL); // result.append(" upload_rate: " + this.upload_rate + NL); // result.append(" total_download: " + this.total_download + NL); // result.append(" total_upload: " + this.total_upload + NL); // result.append(" num_peers: " + this.num_peers + NL); // result.append(" num_seeds: " + this.num_seeds + NL); // result.append(" total_seeds: " + this.total_seeds + NL); // result.append(" total_peers: " + this.total_peers + NL); // result.append("}" + NL); // // return result.toString(); // } // }
import com.google.gson.Gson; import com.bukanir.android.entities.TorrentFile; import com.bukanir.android.entities.TorrentFiles; import com.bukanir.android.entities.TorrentStatus; import java.util.Collections; import go.bukanir.Bukanir;
package com.bukanir.android.clients; public class Torrent2HttpClient { public boolean waitStartup() { return Bukanir.torrentWaitStartup(); } public TorrentStatus getStatus() { String s = ""; try { s = Bukanir.torrentStatus(); } catch(Exception e) { e.printStackTrace(); } try { Gson gson = new Gson(); return gson.fromJson(s, TorrentStatus.class); } catch(Exception e) { return null; } }
// Path: android/src/main/java/com/bukanir/android/entities/TorrentFile.java // public class TorrentFile implements Comparable<TorrentFile>, Serializable { // // public String name; // public String save_path; // public String url; // public String size; // public String offset; // public String download; // public String progress; // // @Override // public int compareTo(TorrentFile f) { // return (int) (Long.valueOf(f.size) - Long.valueOf(this.size)); // } // // @Override // public String toString() { // StringBuilder result = new StringBuilder(); // String NL = System.getProperty("line.separator"); // // result.append(((Object)this).getClass().getName() + " {" + NL); // result.append(" name: " + this.name + NL); // result.append(" save_path: " + this.save_path + NL); // result.append(" url: " + this.url + NL); // result.append(" size: " + this.size + NL); // result.append(" offset: " + this.offset + NL); // result.append(" download: " + this.download + NL); // result.append(" progress: " + this.progress + NL); // result.append("}" + NL); // // return result.toString(); // } // // } // // Path: android/src/main/java/com/bukanir/android/entities/TorrentFiles.java // public class TorrentFiles { // public List<TorrentFile> files = new ArrayList<TorrentFile>(); // } // // Path: android/src/main/java/com/bukanir/android/entities/TorrentStatus.java // public class TorrentStatus { // // public String name; // public String state; // public String state_str; // public String error; // public String progress; // public String download_rate; // public String upload_rate; // public String total_download; // public String total_upload; // public String num_peers; // public String num_seeds; // public String total_seeds; // public String total_peers; // // @Override // public String toString() { // StringBuilder result = new StringBuilder(); // String NL = System.getProperty("line.separator"); // // result.append(((Object)this).getClass().getName() + " {" + NL); // result.append(" name: " + this.name + NL); // result.append(" state: " + this.state + NL); // result.append(" state_str: " + this.state_str + NL); // result.append(" error: " + this.error + NL); // result.append(" progress: " + this.progress + NL); // result.append(" download_rate: " + this.download_rate + NL); // result.append(" upload_rate: " + this.upload_rate + NL); // result.append(" total_download: " + this.total_download + NL); // result.append(" total_upload: " + this.total_upload + NL); // result.append(" num_peers: " + this.num_peers + NL); // result.append(" num_seeds: " + this.num_seeds + NL); // result.append(" total_seeds: " + this.total_seeds + NL); // result.append(" total_peers: " + this.total_peers + NL); // result.append("}" + NL); // // return result.toString(); // } // } // Path: android/src/main/java/com/bukanir/android/clients/Torrent2HttpClient.java import com.google.gson.Gson; import com.bukanir.android.entities.TorrentFile; import com.bukanir.android.entities.TorrentFiles; import com.bukanir.android.entities.TorrentStatus; import java.util.Collections; import go.bukanir.Bukanir; package com.bukanir.android.clients; public class Torrent2HttpClient { public boolean waitStartup() { return Bukanir.torrentWaitStartup(); } public TorrentStatus getStatus() { String s = ""; try { s = Bukanir.torrentStatus(); } catch(Exception e) { e.printStackTrace(); } try { Gson gson = new Gson(); return gson.fromJson(s, TorrentStatus.class); } catch(Exception e) { return null; } }
private TorrentFiles getFiles() {
gen2brain/bukanir
android/src/main/java/com/bukanir/android/clients/Torrent2HttpClient.java
// Path: android/src/main/java/com/bukanir/android/entities/TorrentFile.java // public class TorrentFile implements Comparable<TorrentFile>, Serializable { // // public String name; // public String save_path; // public String url; // public String size; // public String offset; // public String download; // public String progress; // // @Override // public int compareTo(TorrentFile f) { // return (int) (Long.valueOf(f.size) - Long.valueOf(this.size)); // } // // @Override // public String toString() { // StringBuilder result = new StringBuilder(); // String NL = System.getProperty("line.separator"); // // result.append(((Object)this).getClass().getName() + " {" + NL); // result.append(" name: " + this.name + NL); // result.append(" save_path: " + this.save_path + NL); // result.append(" url: " + this.url + NL); // result.append(" size: " + this.size + NL); // result.append(" offset: " + this.offset + NL); // result.append(" download: " + this.download + NL); // result.append(" progress: " + this.progress + NL); // result.append("}" + NL); // // return result.toString(); // } // // } // // Path: android/src/main/java/com/bukanir/android/entities/TorrentFiles.java // public class TorrentFiles { // public List<TorrentFile> files = new ArrayList<TorrentFile>(); // } // // Path: android/src/main/java/com/bukanir/android/entities/TorrentStatus.java // public class TorrentStatus { // // public String name; // public String state; // public String state_str; // public String error; // public String progress; // public String download_rate; // public String upload_rate; // public String total_download; // public String total_upload; // public String num_peers; // public String num_seeds; // public String total_seeds; // public String total_peers; // // @Override // public String toString() { // StringBuilder result = new StringBuilder(); // String NL = System.getProperty("line.separator"); // // result.append(((Object)this).getClass().getName() + " {" + NL); // result.append(" name: " + this.name + NL); // result.append(" state: " + this.state + NL); // result.append(" state_str: " + this.state_str + NL); // result.append(" error: " + this.error + NL); // result.append(" progress: " + this.progress + NL); // result.append(" download_rate: " + this.download_rate + NL); // result.append(" upload_rate: " + this.upload_rate + NL); // result.append(" total_download: " + this.total_download + NL); // result.append(" total_upload: " + this.total_upload + NL); // result.append(" num_peers: " + this.num_peers + NL); // result.append(" num_seeds: " + this.num_seeds + NL); // result.append(" total_seeds: " + this.total_seeds + NL); // result.append(" total_peers: " + this.total_peers + NL); // result.append("}" + NL); // // return result.toString(); // } // }
import com.google.gson.Gson; import com.bukanir.android.entities.TorrentFile; import com.bukanir.android.entities.TorrentFiles; import com.bukanir.android.entities.TorrentStatus; import java.util.Collections; import go.bukanir.Bukanir;
String s = ""; try { s = Bukanir.torrentStatus(); } catch(Exception e) { e.printStackTrace(); } try { Gson gson = new Gson(); return gson.fromJson(s, TorrentStatus.class); } catch(Exception e) { return null; } } private TorrentFiles getFiles() { String s = ""; try { s = Bukanir.torrentFiles(); } catch(Exception e) { e.printStackTrace(); } try { Gson gson = new Gson(); return gson.fromJson(s, TorrentFiles.class); } catch(Exception e) { return null; } }
// Path: android/src/main/java/com/bukanir/android/entities/TorrentFile.java // public class TorrentFile implements Comparable<TorrentFile>, Serializable { // // public String name; // public String save_path; // public String url; // public String size; // public String offset; // public String download; // public String progress; // // @Override // public int compareTo(TorrentFile f) { // return (int) (Long.valueOf(f.size) - Long.valueOf(this.size)); // } // // @Override // public String toString() { // StringBuilder result = new StringBuilder(); // String NL = System.getProperty("line.separator"); // // result.append(((Object)this).getClass().getName() + " {" + NL); // result.append(" name: " + this.name + NL); // result.append(" save_path: " + this.save_path + NL); // result.append(" url: " + this.url + NL); // result.append(" size: " + this.size + NL); // result.append(" offset: " + this.offset + NL); // result.append(" download: " + this.download + NL); // result.append(" progress: " + this.progress + NL); // result.append("}" + NL); // // return result.toString(); // } // // } // // Path: android/src/main/java/com/bukanir/android/entities/TorrentFiles.java // public class TorrentFiles { // public List<TorrentFile> files = new ArrayList<TorrentFile>(); // } // // Path: android/src/main/java/com/bukanir/android/entities/TorrentStatus.java // public class TorrentStatus { // // public String name; // public String state; // public String state_str; // public String error; // public String progress; // public String download_rate; // public String upload_rate; // public String total_download; // public String total_upload; // public String num_peers; // public String num_seeds; // public String total_seeds; // public String total_peers; // // @Override // public String toString() { // StringBuilder result = new StringBuilder(); // String NL = System.getProperty("line.separator"); // // result.append(((Object)this).getClass().getName() + " {" + NL); // result.append(" name: " + this.name + NL); // result.append(" state: " + this.state + NL); // result.append(" state_str: " + this.state_str + NL); // result.append(" error: " + this.error + NL); // result.append(" progress: " + this.progress + NL); // result.append(" download_rate: " + this.download_rate + NL); // result.append(" upload_rate: " + this.upload_rate + NL); // result.append(" total_download: " + this.total_download + NL); // result.append(" total_upload: " + this.total_upload + NL); // result.append(" num_peers: " + this.num_peers + NL); // result.append(" num_seeds: " + this.num_seeds + NL); // result.append(" total_seeds: " + this.total_seeds + NL); // result.append(" total_peers: " + this.total_peers + NL); // result.append("}" + NL); // // return result.toString(); // } // } // Path: android/src/main/java/com/bukanir/android/clients/Torrent2HttpClient.java import com.google.gson.Gson; import com.bukanir.android.entities.TorrentFile; import com.bukanir.android.entities.TorrentFiles; import com.bukanir.android.entities.TorrentStatus; import java.util.Collections; import go.bukanir.Bukanir; String s = ""; try { s = Bukanir.torrentStatus(); } catch(Exception e) { e.printStackTrace(); } try { Gson gson = new Gson(); return gson.fromJson(s, TorrentStatus.class); } catch(Exception e) { return null; } } private TorrentFiles getFiles() { String s = ""; try { s = Bukanir.torrentFiles(); } catch(Exception e) { e.printStackTrace(); } try { Gson gson = new Gson(); return gson.fromJson(s, TorrentFiles.class); } catch(Exception e) { return null; } }
public TorrentFile getLargestFile() {
gen2brain/bukanir
android/src/main/java/com/bukanir/android/widget/media/IjkVideoView.java
// Path: android/src/main/java/com/bukanir/android/application/Settings.java // public class Settings { // // private SharedPreferences preferences; // // public Settings(Context context) { // Context context1 = context.getApplicationContext(); // preferences = PreferenceManager.getDefaultSharedPreferences(context1); // } // // public int listCount() { // return Integer.valueOf(preferences.getString("list_count", "30")); // } // // public int cacheDays() { // return Integer.valueOf(preferences.getString("cache_days", "7")); // } // // public boolean eulaAccepted() { // return preferences.getBoolean("eula_accepted", false); // } // // public boolean hwDecode() { // return preferences.getBoolean("hw_decode", false); // } // // public boolean openSLES() { // return preferences.getBoolean("open_sles", false); // } // // public boolean seek() { // return preferences.getBoolean("seek", true); // } // // public String pixelFormat() { // return preferences.getString("pixel_format", ""); // } // // public boolean wifiHigh() { // return preferences.getBoolean("wifi_high", false); // } // // public boolean subtitles() { // return preferences.getBoolean("subtitles", true); // } // // public String subtitleLanguage() { // return preferences.getString("sub_lang", "English"); // } // // public String subtitleSize() { // return preferences.getString("sub_size", "14"); // } // // public boolean keepFiles() { // return preferences.getBoolean("keep_files", false); // } // // public boolean encryption() { // return preferences.getBoolean("encryption", true); // } // // public String downloadRate() { // return preferences.getString("download_rate", "-1"); // } // // public String uploadRate() { // return preferences.getString("upload_rate", "-1"); // } // // public String listenPort() { // return String.valueOf(preferences.getInt("listen_port", 6881)); // } // // public String tpbHost() { // return String.valueOf(preferences.getString("tpb_host", "thepiratebay.org")); // } // // public String eztvHost() { // return String.valueOf(preferences.getString("eztv_host", "eztv.ag")); // } // // }
import android.annotation.TargetApi; import android.content.Context; import android.content.res.Resources; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Build; import android.support.annotation.NonNull; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import android.widget.MediaController; import android.widget.Toast; import com.bukanir.android.BuildConfig; import com.bukanir.android.R; import com.bukanir.android.application.Settings; import java.io.IOException; import java.util.Map; import tv.danmaku.ijk.media.player.IMediaPlayer; import tv.danmaku.ijk.media.player.IjkMediaPlayer;
// mCurrentState is a VideoView object's current state. // mTargetState is the state that a method caller intends to reach. // For instance, regardless the VideoView object's current state, // calling pause() intends to bring the object to a target state // of STATE_PAUSED. private int mCurrentState = STATE_IDLE; private int mTargetState = STATE_IDLE; // All the stuff we need for playing and showing a video private IRenderView.ISurfaceHolder mSurfaceHolder = null; private IMediaPlayer mMediaPlayer = null; private int mVideoWidth; private int mVideoHeight; private int mSurfaceWidth; private int mSurfaceHeight; private int mVideoRotationDegree; private IMediaController mMediaController; private IMediaPlayer.OnCompletionListener mOnCompletionListener; private IMediaPlayer.OnPreparedListener mOnPreparedListener; private int mCurrentBufferPercentage; private IMediaPlayer.OnErrorListener mOnErrorListener; private IMediaPlayer.OnInfoListener mOnInfoListener; private int mSeekWhenPrepared; // recording the seek position while preparing private boolean mCanPause = true; private boolean mCanSeekBack; private boolean mCanSeekForward; private SurfaceRenderView mSurfaceRenderView; private Context mAppContext;
// Path: android/src/main/java/com/bukanir/android/application/Settings.java // public class Settings { // // private SharedPreferences preferences; // // public Settings(Context context) { // Context context1 = context.getApplicationContext(); // preferences = PreferenceManager.getDefaultSharedPreferences(context1); // } // // public int listCount() { // return Integer.valueOf(preferences.getString("list_count", "30")); // } // // public int cacheDays() { // return Integer.valueOf(preferences.getString("cache_days", "7")); // } // // public boolean eulaAccepted() { // return preferences.getBoolean("eula_accepted", false); // } // // public boolean hwDecode() { // return preferences.getBoolean("hw_decode", false); // } // // public boolean openSLES() { // return preferences.getBoolean("open_sles", false); // } // // public boolean seek() { // return preferences.getBoolean("seek", true); // } // // public String pixelFormat() { // return preferences.getString("pixel_format", ""); // } // // public boolean wifiHigh() { // return preferences.getBoolean("wifi_high", false); // } // // public boolean subtitles() { // return preferences.getBoolean("subtitles", true); // } // // public String subtitleLanguage() { // return preferences.getString("sub_lang", "English"); // } // // public String subtitleSize() { // return preferences.getString("sub_size", "14"); // } // // public boolean keepFiles() { // return preferences.getBoolean("keep_files", false); // } // // public boolean encryption() { // return preferences.getBoolean("encryption", true); // } // // public String downloadRate() { // return preferences.getString("download_rate", "-1"); // } // // public String uploadRate() { // return preferences.getString("upload_rate", "-1"); // } // // public String listenPort() { // return String.valueOf(preferences.getInt("listen_port", 6881)); // } // // public String tpbHost() { // return String.valueOf(preferences.getString("tpb_host", "thepiratebay.org")); // } // // public String eztvHost() { // return String.valueOf(preferences.getString("eztv_host", "eztv.ag")); // } // // } // Path: android/src/main/java/com/bukanir/android/widget/media/IjkVideoView.java import android.annotation.TargetApi; import android.content.Context; import android.content.res.Resources; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Build; import android.support.annotation.NonNull; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import android.widget.MediaController; import android.widget.Toast; import com.bukanir.android.BuildConfig; import com.bukanir.android.R; import com.bukanir.android.application.Settings; import java.io.IOException; import java.util.Map; import tv.danmaku.ijk.media.player.IMediaPlayer; import tv.danmaku.ijk.media.player.IjkMediaPlayer; // mCurrentState is a VideoView object's current state. // mTargetState is the state that a method caller intends to reach. // For instance, regardless the VideoView object's current state, // calling pause() intends to bring the object to a target state // of STATE_PAUSED. private int mCurrentState = STATE_IDLE; private int mTargetState = STATE_IDLE; // All the stuff we need for playing and showing a video private IRenderView.ISurfaceHolder mSurfaceHolder = null; private IMediaPlayer mMediaPlayer = null; private int mVideoWidth; private int mVideoHeight; private int mSurfaceWidth; private int mSurfaceHeight; private int mVideoRotationDegree; private IMediaController mMediaController; private IMediaPlayer.OnCompletionListener mOnCompletionListener; private IMediaPlayer.OnPreparedListener mOnPreparedListener; private int mCurrentBufferPercentage; private IMediaPlayer.OnErrorListener mOnErrorListener; private IMediaPlayer.OnInfoListener mOnInfoListener; private int mSeekWhenPrepared; // recording the seek position while preparing private boolean mCanPause = true; private boolean mCanSeekBack; private boolean mCanSeekForward; private SurfaceRenderView mSurfaceRenderView; private Context mAppContext;
private Settings mSettings;
gen2brain/bukanir
android/src/main/java/com/bukanir/android/activities/SettingsActivity.java
// Path: android/src/main/java/com/quietlycoding/android/picker/NumberPickerPreference.java // public class NumberPickerPreference extends DialogPreference { // private NumberPicker mPicker; // private int mStartRange; // private int mEndRange; // private int mDefault; // // public NumberPickerPreference(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // // if(attrs == null) { // return; // } // // TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.numberpicker); // mStartRange = arr.getInteger(R.styleable.numberpicker_startRange, 0); // mEndRange = arr.getInteger(R.styleable.numberpicker_endRange, 200); // mDefault = arr.getInteger(R.styleable.numberpicker_defaultValue, 0); // // arr.recycle(); // // setDialogLayoutResource(R.layout.number_picker_pref); // } // // public NumberPickerPreference(Context context, AttributeSet attrs) { // this(context, attrs, android.R.attr.dialogPreferenceStyle); // } // // public NumberPickerPreference(Context context) { // this(context, null); // } // // @Override // protected void onBindDialogView(View view) { // super.onBindDialogView(view); // mPicker = (NumberPicker) view.findViewById(R.id.pref_num_picker); // mPicker.setRange(mStartRange, mEndRange); // mPicker.setCurrent(getValue()); // } // // public void onClick(DialogInterface dialog, int which) { // switch (which) { // case DialogInterface.BUTTON_POSITIVE: // saveValue(mPicker.getCurrent()); // break; // default: // break; // } // } // // public void setRange(int start, int end) { // mPicker.setRange(start, end); // } // // private void saveValue(int val) { // getEditor().putInt(getKey(), val).commit(); // callChangeListener(getValue()); // } // // public int getValue() { // return getSharedPreferences().getInt(getKey(), mDefault); // } // }
import android.content.Context; import android.os.Build; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.support.v7.widget.Toolbar; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.ListView; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.AppCompatCheckedTextView; import android.support.v7.widget.AppCompatEditText; import android.support.v7.widget.AppCompatRadioButton; import android.support.v7.widget.AppCompatSpinner; import com.bukanir.android.R; import com.quietlycoding.android.picker.NumberPickerPreference; import java.util.List;
} toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } @Override public void onBuildHeaders(List<Header> target) { loadHeadersFromResource(R.xml.pref_headers, target); } @Override protected boolean isValidFragment(String fragmentName) { return true; } private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object value) { Log.d(TAG, "onPreferenceChange"); String stringValue = value.toString(); if(preference instanceof ListPreference) { ListPreference listPreference = (ListPreference) preference; int index = listPreference.findIndexOfValue(stringValue); preference.setSummary(index >= 0 ? listPreference.getEntries()[index] : null);
// Path: android/src/main/java/com/quietlycoding/android/picker/NumberPickerPreference.java // public class NumberPickerPreference extends DialogPreference { // private NumberPicker mPicker; // private int mStartRange; // private int mEndRange; // private int mDefault; // // public NumberPickerPreference(Context context, AttributeSet attrs, int defStyle) { // super(context, attrs, defStyle); // // if(attrs == null) { // return; // } // // TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.numberpicker); // mStartRange = arr.getInteger(R.styleable.numberpicker_startRange, 0); // mEndRange = arr.getInteger(R.styleable.numberpicker_endRange, 200); // mDefault = arr.getInteger(R.styleable.numberpicker_defaultValue, 0); // // arr.recycle(); // // setDialogLayoutResource(R.layout.number_picker_pref); // } // // public NumberPickerPreference(Context context, AttributeSet attrs) { // this(context, attrs, android.R.attr.dialogPreferenceStyle); // } // // public NumberPickerPreference(Context context) { // this(context, null); // } // // @Override // protected void onBindDialogView(View view) { // super.onBindDialogView(view); // mPicker = (NumberPicker) view.findViewById(R.id.pref_num_picker); // mPicker.setRange(mStartRange, mEndRange); // mPicker.setCurrent(getValue()); // } // // public void onClick(DialogInterface dialog, int which) { // switch (which) { // case DialogInterface.BUTTON_POSITIVE: // saveValue(mPicker.getCurrent()); // break; // default: // break; // } // } // // public void setRange(int start, int end) { // mPicker.setRange(start, end); // } // // private void saveValue(int val) { // getEditor().putInt(getKey(), val).commit(); // callChangeListener(getValue()); // } // // public int getValue() { // return getSharedPreferences().getInt(getKey(), mDefault); // } // } // Path: android/src/main/java/com/bukanir/android/activities/SettingsActivity.java import android.content.Context; import android.os.Build; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.support.v7.widget.Toolbar; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.ListView; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.AppCompatCheckedTextView; import android.support.v7.widget.AppCompatEditText; import android.support.v7.widget.AppCompatRadioButton; import android.support.v7.widget.AppCompatSpinner; import com.bukanir.android.R; import com.quietlycoding.android.picker.NumberPickerPreference; import java.util.List; } toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } @Override public void onBuildHeaders(List<Header> target) { loadHeadersFromResource(R.xml.pref_headers, target); } @Override protected boolean isValidFragment(String fragmentName) { return true; } private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object value) { Log.d(TAG, "onPreferenceChange"); String stringValue = value.toString(); if(preference instanceof ListPreference) { ListPreference listPreference = (ListPreference) preference; int index = listPreference.findIndexOfValue(stringValue); preference.setSummary(index >= 0 ? listPreference.getEntries()[index] : null);
} else if(preference instanceof NumberPickerPreference) {
gen2brain/bukanir
android/src/main/java/com/bukanir/android/helpers/Utils.java
// Path: android/src/main/java/com/bukanir/android/services/Torrent2HttpService.java // public class Torrent2HttpService extends Service { // // public static final String TAG = "Torrent2HttpService"; // // int id = 313; // // String magnetLink; // // File movieDir; // File subtitlesDir; // // private Settings settings; // private TorrentConfig config; // // @Override // public IBinder onBind(Intent intent) { // return null; // } // // @Override // public void onCreate() { // settings = new Settings(this); // config = new TorrentConfig(); // // String storageDir = Storage.getStorage(this) + File.separator + "bukanir"; // movieDir = new File(storageDir + File.separator + "movies"); // subtitlesDir = new File(storageDir + File.separator + "subtitles"); // // movieDir.mkdirs(); // subtitlesDir.mkdirs(); // } // // @Override // public void onDestroy() { // Log.d(TAG, "onDestroy"); // super.onDestroy(); // // (new Thread() { public void run() { // Bukanir.torrentStop(); // // if(!settings.keepFiles()) { // Log.d(TAG, "Removing files"); // if(movieDir != null && movieDir.exists()) { // Utils.deleteDir(movieDir); // } // if(subtitlesDir != null && subtitlesDir.exists()) { // Utils.deleteDir(subtitlesDir); // } // } // }}).start(); // // Toast.makeText(getApplicationContext(), getString(R.string.torrent_stopped), Toast.LENGTH_SHORT).show(); // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // Log.d(TAG, "onStartCommand"); // // magnetLink = intent.getExtras().getString("magnet"); // // new Torrent2HttpThread().start(); // // startNotification(); // Toast.makeText(this, getString(R.string.torrent_started), Toast.LENGTH_SHORT).show(); // // return START_NOT_STICKY; // } // // public void startNotification() { // Intent i = new Intent(this, MovieActivity.class); // i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); // PendingIntent pendIntent = PendingIntent.getActivity(this, 0, i, 0); // // NotificationCompat.Builder builder = new NotificationCompat.Builder(this); // builder.setTicker(getString(R.string.torrent_started)).setContentTitle(getString(R.string.app_name)) // .setWhen(System.currentTimeMillis()).setAutoCancel(false) // .setOngoing(true) // .setContentIntent(pendIntent); // Notification notification = builder.build(); // // notification.flags |= Notification.FLAG_NO_CLEAR; // startForeground(id, notification); // } // // private class Torrent2HttpThread extends Thread { // // @Override // public void run() { // super.run(); // try { // config.uri = magnetLink; // config.download_path = movieDir.toString(); // config.listen_port = Integer.valueOf(settings.listenPort()); // config.max_download_rate = Integer.valueOf(settings.downloadRate()); // config.max_upload_rate = Integer.valueOf(settings.uploadRate()); // config.encryption = settings.encryption() ? 1 : 2; // config.keep_files = true; // // config.no_sparse_file = !settings.seek(); // // if(BuildConfig.DEBUG) { // config.verbose = true; // } // // Gson gson = new Gson(); // Bukanir.torrentStartup(gson.toJson(config)); // } catch(Exception e){ // e.getMessage(); // } // } // // } // // }
import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import com.bukanir.android.services.Torrent2HttpService; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.Tracker; import java.io.File;
package com.bukanir.android.helpers; public class Utils { public static boolean isTorrentServiceRunning(Context context) { ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for(ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
// Path: android/src/main/java/com/bukanir/android/services/Torrent2HttpService.java // public class Torrent2HttpService extends Service { // // public static final String TAG = "Torrent2HttpService"; // // int id = 313; // // String magnetLink; // // File movieDir; // File subtitlesDir; // // private Settings settings; // private TorrentConfig config; // // @Override // public IBinder onBind(Intent intent) { // return null; // } // // @Override // public void onCreate() { // settings = new Settings(this); // config = new TorrentConfig(); // // String storageDir = Storage.getStorage(this) + File.separator + "bukanir"; // movieDir = new File(storageDir + File.separator + "movies"); // subtitlesDir = new File(storageDir + File.separator + "subtitles"); // // movieDir.mkdirs(); // subtitlesDir.mkdirs(); // } // // @Override // public void onDestroy() { // Log.d(TAG, "onDestroy"); // super.onDestroy(); // // (new Thread() { public void run() { // Bukanir.torrentStop(); // // if(!settings.keepFiles()) { // Log.d(TAG, "Removing files"); // if(movieDir != null && movieDir.exists()) { // Utils.deleteDir(movieDir); // } // if(subtitlesDir != null && subtitlesDir.exists()) { // Utils.deleteDir(subtitlesDir); // } // } // }}).start(); // // Toast.makeText(getApplicationContext(), getString(R.string.torrent_stopped), Toast.LENGTH_SHORT).show(); // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // Log.d(TAG, "onStartCommand"); // // magnetLink = intent.getExtras().getString("magnet"); // // new Torrent2HttpThread().start(); // // startNotification(); // Toast.makeText(this, getString(R.string.torrent_started), Toast.LENGTH_SHORT).show(); // // return START_NOT_STICKY; // } // // public void startNotification() { // Intent i = new Intent(this, MovieActivity.class); // i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); // PendingIntent pendIntent = PendingIntent.getActivity(this, 0, i, 0); // // NotificationCompat.Builder builder = new NotificationCompat.Builder(this); // builder.setTicker(getString(R.string.torrent_started)).setContentTitle(getString(R.string.app_name)) // .setWhen(System.currentTimeMillis()).setAutoCancel(false) // .setOngoing(true) // .setContentIntent(pendIntent); // Notification notification = builder.build(); // // notification.flags |= Notification.FLAG_NO_CLEAR; // startForeground(id, notification); // } // // private class Torrent2HttpThread extends Thread { // // @Override // public void run() { // super.run(); // try { // config.uri = magnetLink; // config.download_path = movieDir.toString(); // config.listen_port = Integer.valueOf(settings.listenPort()); // config.max_download_rate = Integer.valueOf(settings.downloadRate()); // config.max_upload_rate = Integer.valueOf(settings.uploadRate()); // config.encryption = settings.encryption() ? 1 : 2; // config.keep_files = true; // // config.no_sparse_file = !settings.seek(); // // if(BuildConfig.DEBUG) { // config.verbose = true; // } // // Gson gson = new Gson(); // Bukanir.torrentStartup(gson.toJson(config)); // } catch(Exception e){ // e.getMessage(); // } // } // // } // // } // Path: android/src/main/java/com/bukanir/android/helpers/Utils.java import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import com.bukanir.android.services.Torrent2HttpService; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.Tracker; import java.io.File; package com.bukanir.android.helpers; public class Utils { public static boolean isTorrentServiceRunning(Context context) { ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for(ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if(Torrent2HttpService.class.getName().equals(service.service.getClassName())) {
struts-community-plugins/struts2-jquery
struts2-jquery-plugin/src/main/java/com/jgeppert/struts2/jquery/views/velocity/components/DivDirective.java
// Path: struts2-jquery-plugin/src/main/java/com/jgeppert/struts2/jquery/components/Div.java // @StrutsTag(name = "div", tldTagClass = "com.jgeppert.struts2.jquery.views.jsp.ui.DivTag", description = "Render HTML div providing content from remote call via AJAX", allowDynamicAttributes = true) // public class Div extends AbstractContainer implements ResizableBean, // DroppableBean, DraggableBean, SelectableBean { // // public static final String TEMPLATE = "div"; // public static final String TEMPLATE_CLOSE = "div-close"; // public static final String COMPONENT_NAME = Div.class.getName(); // public static final String JQUERYACTION = "container"; // // private static final String PARAM_UPDATE_FREQ = "updateFreq"; // private static final String PARAM_DELAY = "delay"; // // private static final String ID_PREFIX_DIV = "div_"; // // protected String updateFreq; // protected String delay; // // public Div(ValueStack stack, HttpServletRequest request, HttpServletResponse response) { // super(stack, request, response); // } // // public String getDefaultOpenTemplate() { // return TEMPLATE; // } // // protected String getDefaultTemplate() { // return TEMPLATE_CLOSE; // } // // public void evaluateExtraParams() { // super.evaluateExtraParams(); // addParameter(PARAM_JQUERY_ACTION, JQUERYACTION); // // addParameterIfPresent(PARAM_UPDATE_FREQ, this.updateFreq, Number.class); // addParameterIfPresent(PARAM_DELAY, this.delay, Number.class); // // addGeneratedIdParam(ID_PREFIX_DIV); // } // // @Override // @StrutsTagSkipInheritance // public void setTheme(String theme) { // super.setTheme(theme); // } // // @Override // public String getTheme() { // return "jquery"; // } // // @StrutsTagAttribute(description = "How often to reload the content (in milliseconds). e.g. 5000", type = "Number") // public void setUpdateFreq(String updateFreq) { // this.updateFreq = updateFreq; // } // // @StrutsTagAttribute(description = "How long to wait before fetching the content (in milliseconds). e.g. 2000", type = "Number") // public void setDelay(String delay) { // this.delay = delay; // } // }
import com.jgeppert.struts2.jquery.components.Div; import com.opensymphony.xwork2.util.ValueStack; import org.apache.struts2.components.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.jgeppert.struts2.jquery.views.velocity.components; /** * @author <a href="http://www.jgeppert.com">Johannes Geppert</a> * @see Div */ public class DivDirective extends JqueryAbstractDirective { public String getBeanName() { return "div"; } protected Component getBean(ValueStack stack, HttpServletRequest req, HttpServletResponse res) {
// Path: struts2-jquery-plugin/src/main/java/com/jgeppert/struts2/jquery/components/Div.java // @StrutsTag(name = "div", tldTagClass = "com.jgeppert.struts2.jquery.views.jsp.ui.DivTag", description = "Render HTML div providing content from remote call via AJAX", allowDynamicAttributes = true) // public class Div extends AbstractContainer implements ResizableBean, // DroppableBean, DraggableBean, SelectableBean { // // public static final String TEMPLATE = "div"; // public static final String TEMPLATE_CLOSE = "div-close"; // public static final String COMPONENT_NAME = Div.class.getName(); // public static final String JQUERYACTION = "container"; // // private static final String PARAM_UPDATE_FREQ = "updateFreq"; // private static final String PARAM_DELAY = "delay"; // // private static final String ID_PREFIX_DIV = "div_"; // // protected String updateFreq; // protected String delay; // // public Div(ValueStack stack, HttpServletRequest request, HttpServletResponse response) { // super(stack, request, response); // } // // public String getDefaultOpenTemplate() { // return TEMPLATE; // } // // protected String getDefaultTemplate() { // return TEMPLATE_CLOSE; // } // // public void evaluateExtraParams() { // super.evaluateExtraParams(); // addParameter(PARAM_JQUERY_ACTION, JQUERYACTION); // // addParameterIfPresent(PARAM_UPDATE_FREQ, this.updateFreq, Number.class); // addParameterIfPresent(PARAM_DELAY, this.delay, Number.class); // // addGeneratedIdParam(ID_PREFIX_DIV); // } // // @Override // @StrutsTagSkipInheritance // public void setTheme(String theme) { // super.setTheme(theme); // } // // @Override // public String getTheme() { // return "jquery"; // } // // @StrutsTagAttribute(description = "How often to reload the content (in milliseconds). e.g. 5000", type = "Number") // public void setUpdateFreq(String updateFreq) { // this.updateFreq = updateFreq; // } // // @StrutsTagAttribute(description = "How long to wait before fetching the content (in milliseconds). e.g. 2000", type = "Number") // public void setDelay(String delay) { // this.delay = delay; // } // } // Path: struts2-jquery-plugin/src/main/java/com/jgeppert/struts2/jquery/views/velocity/components/DivDirective.java import com.jgeppert.struts2.jquery.components.Div; import com.opensymphony.xwork2.util.ValueStack; import org.apache.struts2.components.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.jgeppert.struts2.jquery.views.velocity.components; /** * @author <a href="http://www.jgeppert.com">Johannes Geppert</a> * @see Div */ public class DivDirective extends JqueryAbstractDirective { public String getBeanName() { return "div"; } protected Component getBean(ValueStack stack, HttpServletRequest req, HttpServletResponse res) {
return new Div(stack, req, res);