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
abstratt/eclipsegraphviz
plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/SaveToFileAction.java
// Path: plugins/com.abstratt.content/src/com/abstratt/content/IContentProviderRegistry.java // public interface IProviderDescription { // public IContentProvider getProvider(); // // /** // * Converts the given source object (using one of the contributed // * readers) to the format expected by the content provider. // * // * @param source // * object to convert // * @return the converted contents that are consumable by the content // * provider // */ // public Object read(Object source); // } // // Path: plugins/com.abstratt.content/src/com/abstratt/content/PlaceholderProviderDescription.java // public class PlaceholderProviderDescription implements IProviderDescription { // // private Object input; // private IContentProvider contentProvider; // // public PlaceholderProviderDescription(Object input, IContentProvider contentProvider) { // this.input = input; // this.contentProvider = contentProvider; // } // // @Override // public IContentProvider getProvider() { // return contentProvider; // } // // @Override // public Object read(Object source) { // return input; // } // // } // // Path: plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/IGraphicalContentProvider.java // enum GraphicFileFormat { // JPEG("jpg"), PNG("png"), GIF("gif"), TIFF("tif"), BITMAP("bmp"), SVG("svg"), DOT("dot"); // String extension; // GraphicFileFormat(String extension) { // this.extension = extension; // } // public static GraphicFileFormat byExtension(String toMatch) { // return Arrays.stream(values()).filter(it -> it.extension.equals(toMatch)).findAny().orElse(null); // } // public String getExtension() { // return extension; // } // }
import java.io.File; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.ui.IViewActionDelegate; import org.eclipse.ui.IViewPart; import com.abstratt.content.IContentProviderRegistry.IProviderDescription; import com.abstratt.content.PlaceholderProviderDescription; import com.abstratt.imageviewer.IGraphicalContentProvider.GraphicFileFormat;
package com.abstratt.imageviewer; public class SaveToFileAction implements IViewActionDelegate { private GraphicalView view; public void init(IViewPart view) { this.view = (GraphicalView) view; } public void run(IAction action) { IProviderDescription providerDefinition = view.getContentProviderDescription(); IGraphicalContentProvider contentProvider = view.getContentProvider(); if (providerDefinition == null) providerDefinition = new PlaceholderProviderDescription(view.getInput(), contentProvider); IFile selectedFile = view.getSelectedFile(); String suggestedName; if (selectedFile == null) suggestedName = "image"; else suggestedName = selectedFile.getLocation().removeFileExtension().lastSegment(); boolean pathIsValid = false; IPath path = null;
// Path: plugins/com.abstratt.content/src/com/abstratt/content/IContentProviderRegistry.java // public interface IProviderDescription { // public IContentProvider getProvider(); // // /** // * Converts the given source object (using one of the contributed // * readers) to the format expected by the content provider. // * // * @param source // * object to convert // * @return the converted contents that are consumable by the content // * provider // */ // public Object read(Object source); // } // // Path: plugins/com.abstratt.content/src/com/abstratt/content/PlaceholderProviderDescription.java // public class PlaceholderProviderDescription implements IProviderDescription { // // private Object input; // private IContentProvider contentProvider; // // public PlaceholderProviderDescription(Object input, IContentProvider contentProvider) { // this.input = input; // this.contentProvider = contentProvider; // } // // @Override // public IContentProvider getProvider() { // return contentProvider; // } // // @Override // public Object read(Object source) { // return input; // } // // } // // Path: plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/IGraphicalContentProvider.java // enum GraphicFileFormat { // JPEG("jpg"), PNG("png"), GIF("gif"), TIFF("tif"), BITMAP("bmp"), SVG("svg"), DOT("dot"); // String extension; // GraphicFileFormat(String extension) { // this.extension = extension; // } // public static GraphicFileFormat byExtension(String toMatch) { // return Arrays.stream(values()).filter(it -> it.extension.equals(toMatch)).findAny().orElse(null); // } // public String getExtension() { // return extension; // } // } // Path: plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/SaveToFileAction.java import java.io.File; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.ui.IViewActionDelegate; import org.eclipse.ui.IViewPart; import com.abstratt.content.IContentProviderRegistry.IProviderDescription; import com.abstratt.content.PlaceholderProviderDescription; import com.abstratt.imageviewer.IGraphicalContentProvider.GraphicFileFormat; package com.abstratt.imageviewer; public class SaveToFileAction implements IViewActionDelegate { private GraphicalView view; public void init(IViewPart view) { this.view = (GraphicalView) view; } public void run(IAction action) { IProviderDescription providerDefinition = view.getContentProviderDescription(); IGraphicalContentProvider contentProvider = view.getContentProvider(); if (providerDefinition == null) providerDefinition = new PlaceholderProviderDescription(view.getInput(), contentProvider); IFile selectedFile = view.getSelectedFile(); String suggestedName; if (selectedFile == null) suggestedName = "image"; else suggestedName = selectedFile.getLocation().removeFileExtension().lastSegment(); boolean pathIsValid = false; IPath path = null;
GraphicFileFormat fileFormat = null;
abstratt/eclipsegraphviz
plugins/com.abstratt.content/src/com/abstratt/internal/content/Activator.java
// Path: plugins/com.abstratt.content/src/com/abstratt/content/ContentSupport.java // public class ContentSupport { // public static final String PLUGIN_ID = ContentSupport.class.getPackage().getName(); // // private static IContentProviderRegistry registry = new ContentProviderRegistry(); // // public static IContentProviderRegistry getContentProviderRegistry() { // return registry; // } // } // // Path: plugins/com.abstratt.pluginutils/src/com/abstratt/pluginutils/LogUtils.java // public class LogUtils { // public static void log(int severity, String pluginId, Supplier<String> message, Throwable exception) { // log(() -> new Status(severity, pluginId, message.get(), exception)); // } // // public static void log(int severity, String pluginId, String message, Throwable exception) { // log(() -> new Status(severity, pluginId, message, exception)); // } // // public static void log(IStatus status) { // log(() -> status); // } // public static void log(Supplier<IStatus> statusSupplier) { // IStatus status = statusSupplier.get(); // if (!Platform.isRunning()) { // System.err.println(status.getMessage()); // if (status.getException() != null) // status.getException().printStackTrace(); // if (status.isMultiStatus()) // for (IStatus child : status.getChildren()) // log(child); // return; // } // Bundle bundle = Platform.getBundle(status.getPlugin()); // if (bundle == null) { // String thisPluginId = LogUtils.class.getPackage().getName(); // bundle = Platform.getBundle(thisPluginId); // Platform.getLog(bundle).log( // new Status(IStatus.WARNING, thisPluginId, "Could not find a plugin " + status.getPlugin() // + " for logging as")); // } // Platform.getLog(bundle).log(status); // } // // public static void logError(String pluginId, String message, Throwable e) { // log(IStatus.ERROR, pluginId, message, e); // } // // public static void logWarning(String pluginId, String message, Throwable e) { // log(IStatus.WARNING, pluginId, message, e); // } // // public static void logInfo(String pluginId, String message, Throwable e) { // log(IStatus.INFO, pluginId, message, e); // } // // public static void debug(String pluginId, String message) { // debug(pluginId, () -> message); // } // // public static void debug(String pluginId, Supplier<String> message) { // if (Boolean.getBoolean(pluginId + ".debug")) // log(IStatus.INFO, pluginId, message.get(), null); // } // // public static void logError(Class pluginClass, String message, Throwable e) { // logError(pluginClass.getPackage().getName(), message, e); // } // // public static void logWarning(Class pluginClass, String message, Throwable e) { // logWarning(pluginClass.getPackage().getName(), message, e); // } // // public static void logInfo(Class pluginClass, String message, Throwable e) { // logInfo(pluginClass.getPackage().getName(), message, e); // } // // public static void debug(Class pluginClass, String message) { // debug(pluginClass.getName(), () -> message); // } // // public static void debug(Class pluginClass, Supplier<String> message) { // debug(pluginClass.getName(), message); // } // // public static void log(int severity, Class pluginClass, Supplier<String> message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // public static void log(int severity, Class pluginClass, String message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // // }
import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import com.abstratt.content.ContentSupport; import com.abstratt.pluginutils.LogUtils;
package com.abstratt.internal.content; /** * The activator class controls the plug-in life cycle */ public class Activator implements BundleActivator { public static void logUnexpected(String message, Exception e) {
// Path: plugins/com.abstratt.content/src/com/abstratt/content/ContentSupport.java // public class ContentSupport { // public static final String PLUGIN_ID = ContentSupport.class.getPackage().getName(); // // private static IContentProviderRegistry registry = new ContentProviderRegistry(); // // public static IContentProviderRegistry getContentProviderRegistry() { // return registry; // } // } // // Path: plugins/com.abstratt.pluginutils/src/com/abstratt/pluginutils/LogUtils.java // public class LogUtils { // public static void log(int severity, String pluginId, Supplier<String> message, Throwable exception) { // log(() -> new Status(severity, pluginId, message.get(), exception)); // } // // public static void log(int severity, String pluginId, String message, Throwable exception) { // log(() -> new Status(severity, pluginId, message, exception)); // } // // public static void log(IStatus status) { // log(() -> status); // } // public static void log(Supplier<IStatus> statusSupplier) { // IStatus status = statusSupplier.get(); // if (!Platform.isRunning()) { // System.err.println(status.getMessage()); // if (status.getException() != null) // status.getException().printStackTrace(); // if (status.isMultiStatus()) // for (IStatus child : status.getChildren()) // log(child); // return; // } // Bundle bundle = Platform.getBundle(status.getPlugin()); // if (bundle == null) { // String thisPluginId = LogUtils.class.getPackage().getName(); // bundle = Platform.getBundle(thisPluginId); // Platform.getLog(bundle).log( // new Status(IStatus.WARNING, thisPluginId, "Could not find a plugin " + status.getPlugin() // + " for logging as")); // } // Platform.getLog(bundle).log(status); // } // // public static void logError(String pluginId, String message, Throwable e) { // log(IStatus.ERROR, pluginId, message, e); // } // // public static void logWarning(String pluginId, String message, Throwable e) { // log(IStatus.WARNING, pluginId, message, e); // } // // public static void logInfo(String pluginId, String message, Throwable e) { // log(IStatus.INFO, pluginId, message, e); // } // // public static void debug(String pluginId, String message) { // debug(pluginId, () -> message); // } // // public static void debug(String pluginId, Supplier<String> message) { // if (Boolean.getBoolean(pluginId + ".debug")) // log(IStatus.INFO, pluginId, message.get(), null); // } // // public static void logError(Class pluginClass, String message, Throwable e) { // logError(pluginClass.getPackage().getName(), message, e); // } // // public static void logWarning(Class pluginClass, String message, Throwable e) { // logWarning(pluginClass.getPackage().getName(), message, e); // } // // public static void logInfo(Class pluginClass, String message, Throwable e) { // logInfo(pluginClass.getPackage().getName(), message, e); // } // // public static void debug(Class pluginClass, String message) { // debug(pluginClass.getName(), () -> message); // } // // public static void debug(Class pluginClass, Supplier<String> message) { // debug(pluginClass.getName(), message); // } // // public static void log(int severity, Class pluginClass, Supplier<String> message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // public static void log(int severity, Class pluginClass, String message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // // } // Path: plugins/com.abstratt.content/src/com/abstratt/internal/content/Activator.java import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import com.abstratt.content.ContentSupport; import com.abstratt.pluginutils.LogUtils; package com.abstratt.internal.content; /** * The activator class controls the plug-in life cycle */ public class Activator implements BundleActivator { public static void logUnexpected(String message, Exception e) {
LogUtils.logError(ContentSupport.PLUGIN_ID, message, e);
abstratt/eclipsegraphviz
plugins/com.abstratt.content/src/com/abstratt/internal/content/Activator.java
// Path: plugins/com.abstratt.content/src/com/abstratt/content/ContentSupport.java // public class ContentSupport { // public static final String PLUGIN_ID = ContentSupport.class.getPackage().getName(); // // private static IContentProviderRegistry registry = new ContentProviderRegistry(); // // public static IContentProviderRegistry getContentProviderRegistry() { // return registry; // } // } // // Path: plugins/com.abstratt.pluginutils/src/com/abstratt/pluginutils/LogUtils.java // public class LogUtils { // public static void log(int severity, String pluginId, Supplier<String> message, Throwable exception) { // log(() -> new Status(severity, pluginId, message.get(), exception)); // } // // public static void log(int severity, String pluginId, String message, Throwable exception) { // log(() -> new Status(severity, pluginId, message, exception)); // } // // public static void log(IStatus status) { // log(() -> status); // } // public static void log(Supplier<IStatus> statusSupplier) { // IStatus status = statusSupplier.get(); // if (!Platform.isRunning()) { // System.err.println(status.getMessage()); // if (status.getException() != null) // status.getException().printStackTrace(); // if (status.isMultiStatus()) // for (IStatus child : status.getChildren()) // log(child); // return; // } // Bundle bundle = Platform.getBundle(status.getPlugin()); // if (bundle == null) { // String thisPluginId = LogUtils.class.getPackage().getName(); // bundle = Platform.getBundle(thisPluginId); // Platform.getLog(bundle).log( // new Status(IStatus.WARNING, thisPluginId, "Could not find a plugin " + status.getPlugin() // + " for logging as")); // } // Platform.getLog(bundle).log(status); // } // // public static void logError(String pluginId, String message, Throwable e) { // log(IStatus.ERROR, pluginId, message, e); // } // // public static void logWarning(String pluginId, String message, Throwable e) { // log(IStatus.WARNING, pluginId, message, e); // } // // public static void logInfo(String pluginId, String message, Throwable e) { // log(IStatus.INFO, pluginId, message, e); // } // // public static void debug(String pluginId, String message) { // debug(pluginId, () -> message); // } // // public static void debug(String pluginId, Supplier<String> message) { // if (Boolean.getBoolean(pluginId + ".debug")) // log(IStatus.INFO, pluginId, message.get(), null); // } // // public static void logError(Class pluginClass, String message, Throwable e) { // logError(pluginClass.getPackage().getName(), message, e); // } // // public static void logWarning(Class pluginClass, String message, Throwable e) { // logWarning(pluginClass.getPackage().getName(), message, e); // } // // public static void logInfo(Class pluginClass, String message, Throwable e) { // logInfo(pluginClass.getPackage().getName(), message, e); // } // // public static void debug(Class pluginClass, String message) { // debug(pluginClass.getName(), () -> message); // } // // public static void debug(Class pluginClass, Supplier<String> message) { // debug(pluginClass.getName(), message); // } // // public static void log(int severity, Class pluginClass, Supplier<String> message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // public static void log(int severity, Class pluginClass, String message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // // }
import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import com.abstratt.content.ContentSupport; import com.abstratt.pluginutils.LogUtils;
package com.abstratt.internal.content; /** * The activator class controls the plug-in life cycle */ public class Activator implements BundleActivator { public static void logUnexpected(String message, Exception e) {
// Path: plugins/com.abstratt.content/src/com/abstratt/content/ContentSupport.java // public class ContentSupport { // public static final String PLUGIN_ID = ContentSupport.class.getPackage().getName(); // // private static IContentProviderRegistry registry = new ContentProviderRegistry(); // // public static IContentProviderRegistry getContentProviderRegistry() { // return registry; // } // } // // Path: plugins/com.abstratt.pluginutils/src/com/abstratt/pluginutils/LogUtils.java // public class LogUtils { // public static void log(int severity, String pluginId, Supplier<String> message, Throwable exception) { // log(() -> new Status(severity, pluginId, message.get(), exception)); // } // // public static void log(int severity, String pluginId, String message, Throwable exception) { // log(() -> new Status(severity, pluginId, message, exception)); // } // // public static void log(IStatus status) { // log(() -> status); // } // public static void log(Supplier<IStatus> statusSupplier) { // IStatus status = statusSupplier.get(); // if (!Platform.isRunning()) { // System.err.println(status.getMessage()); // if (status.getException() != null) // status.getException().printStackTrace(); // if (status.isMultiStatus()) // for (IStatus child : status.getChildren()) // log(child); // return; // } // Bundle bundle = Platform.getBundle(status.getPlugin()); // if (bundle == null) { // String thisPluginId = LogUtils.class.getPackage().getName(); // bundle = Platform.getBundle(thisPluginId); // Platform.getLog(bundle).log( // new Status(IStatus.WARNING, thisPluginId, "Could not find a plugin " + status.getPlugin() // + " for logging as")); // } // Platform.getLog(bundle).log(status); // } // // public static void logError(String pluginId, String message, Throwable e) { // log(IStatus.ERROR, pluginId, message, e); // } // // public static void logWarning(String pluginId, String message, Throwable e) { // log(IStatus.WARNING, pluginId, message, e); // } // // public static void logInfo(String pluginId, String message, Throwable e) { // log(IStatus.INFO, pluginId, message, e); // } // // public static void debug(String pluginId, String message) { // debug(pluginId, () -> message); // } // // public static void debug(String pluginId, Supplier<String> message) { // if (Boolean.getBoolean(pluginId + ".debug")) // log(IStatus.INFO, pluginId, message.get(), null); // } // // public static void logError(Class pluginClass, String message, Throwable e) { // logError(pluginClass.getPackage().getName(), message, e); // } // // public static void logWarning(Class pluginClass, String message, Throwable e) { // logWarning(pluginClass.getPackage().getName(), message, e); // } // // public static void logInfo(Class pluginClass, String message, Throwable e) { // logInfo(pluginClass.getPackage().getName(), message, e); // } // // public static void debug(Class pluginClass, String message) { // debug(pluginClass.getName(), () -> message); // } // // public static void debug(Class pluginClass, Supplier<String> message) { // debug(pluginClass.getName(), message); // } // // public static void log(int severity, Class pluginClass, Supplier<String> message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // public static void log(int severity, Class pluginClass, String message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // // } // Path: plugins/com.abstratt.content/src/com/abstratt/internal/content/Activator.java import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import com.abstratt.content.ContentSupport; import com.abstratt.pluginutils.LogUtils; package com.abstratt.internal.content; /** * The activator class controls the plug-in life cycle */ public class Activator implements BundleActivator { public static void logUnexpected(String message, Exception e) {
LogUtils.logError(ContentSupport.PLUGIN_ID, message, e);
TU-Berlin-SNET/JCPABE
src/test/java/cpabe/tests/ConversionTest.java
// Path: src/main/java/cpabe/policy/Util.java // public class Util { // // public static final String FLEXINT_TYPE = "flexint"; // public static final int FLEXINT_MAXBITS = 64; // // public static final BigInteger MIN_FLEXINT_VALUE = BigInteger.ZERO; // public static final BigInteger MAX_FLEXINT_VALUE = BigInteger.ONE.shiftLeft(FLEXINT_MAXBITS).subtract(BigInteger.ONE); // private static final BigDecimal MAX_FLEXINT_VALUE_DECIMAL = new BigDecimal(MAX_FLEXINT_VALUE); // // public static final BigDecimal NINETY = BigDecimal.valueOf(90); // public static final BigDecimal ONEHUNDREDEIGHTY = BigDecimal.valueOf(180); // public static final BigDecimal THREEHUNDRESIXTY = BigDecimal.valueOf(360); // // private static final BigInteger BI_2_64 = BigInteger.ONE.shiftLeft(64); // only use once in long to biginteger conversion // public static BigInteger unsignedToBigInteger(long l) { // final BigInteger bi = BigInteger.valueOf(l); // return l >= 0 ? bi : bi.add(BI_2_64); // } // // public static String bit_marker_flexint(String attribute, int bit, boolean on) { // return bit_marker(attribute, FLEXINT_TYPE, FLEXINT_MAXBITS, bit, on); // } // // private static String bit_marker(String attribute, String type, int maxBits, int bit, boolean on) { // if (bit >= maxBits) throw new RuntimeException("bit is greater than maxbits"); // StringBuilder result = new StringBuilder(attribute.length() + maxBits + type.length() + 2); // StringBuilder bitmarks = new StringBuilder(maxBits + 1); // result.append(attribute).append('_').append(type).append('_'); // for (int i = 0; i < maxBits; i++) { // bitmarks.append('x'); // } // bitmarks.setCharAt(maxBits - bit - 1, on ? '1' : '0'); // return result.append(bitmarks).toString(); // } // // public static boolean isLessThanUnsigned(long n1, long n2) { // boolean comp = (n1 < n2); // if ((n1 < 0) != (n2 < 0)) { // comp = !comp; // } // return comp; // } // // public static BigInteger convertLatitudeToLong(double lat) { // if (Math.abs(lat) > 90) throw new IllegalArgumentException("Latitude can only be between -90 and 90"); // BigDecimal decimal = BigDecimal.valueOf(lat); // //truncating ok, since number is always positive and would ne to be rounded down anyway // return decimal.add(NINETY).divide(ONEHUNDREDEIGHTY, MathContext.DECIMAL128).multiply(MAX_FLEXINT_VALUE_DECIMAL).toBigInteger(); // } // // public static double convertLongToLatitude(long lat) { // only used for previewing the resulting value, and unit tests // BigDecimal latitude = new BigDecimal(unsignedToBigInteger(lat)); // return latitude.divide(MAX_FLEXINT_VALUE_DECIMAL, MathContext.DECIMAL128).multiply(ONEHUNDREDEIGHTY).subtract(NINETY).doubleValue(); // } // // public static BigInteger convertLongitudeToLong(double lng) { // if (Math.abs(lng) > 180) throw new IllegalArgumentException("Longitude can only be between -180 and 180"); // BigDecimal decimal = BigDecimal.valueOf(lng); // return decimal.add(ONEHUNDREDEIGHTY).divide(THREEHUNDRESIXTY, MathContext.DECIMAL128).multiply(MAX_FLEXINT_VALUE_DECIMAL).toBigInteger(); // } // // public static double convertLongToLongitude(long lng) { // BigDecimal latitude = new BigDecimal(unsignedToBigInteger(lng)); // return latitude.divide(MAX_FLEXINT_VALUE_DECIMAL, MathContext.DECIMAL128).multiply(THREEHUNDRESIXTY).subtract(ONEHUNDREDEIGHTY).doubleValue(); // } // } // // Path: src/test/java/cpabe/tests/rules/RepeatRule.java // public class RepeatRule implements TestRule { // // @Override // public Statement apply(Statement statement, Description description) { // Statement result = statement; // Repeat repeat = description.getAnnotation(Repeat.class); // if (repeat != null) { // int times = repeat.value(); // result = new RepeatStatement(times, statement); // } // return result; // } // // private static class RepeatStatement extends Statement { // private final int times; // private final Statement statement; // // private RepeatStatement(int times, Statement statement) { // this.times = times; // this.statement = statement; // } // // @Override // public void evaluate() throws Throwable { // for (int i = 0; i < times; i++) { // statement.evaluate(); // } // } // } // }
import cpabe.policy.Util; import cpabe.tests.rules.Repeat; import cpabe.tests.rules.RepeatRule; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import java.math.BigInteger; import java.security.SecureRandom; import static org.junit.Assert.assertTrue;
package cpabe.tests; public class ConversionTest { public static BigInteger MAX_SIGNED_LONG = BigInteger.valueOf(Long.MAX_VALUE); private static SecureRandom random;
// Path: src/main/java/cpabe/policy/Util.java // public class Util { // // public static final String FLEXINT_TYPE = "flexint"; // public static final int FLEXINT_MAXBITS = 64; // // public static final BigInteger MIN_FLEXINT_VALUE = BigInteger.ZERO; // public static final BigInteger MAX_FLEXINT_VALUE = BigInteger.ONE.shiftLeft(FLEXINT_MAXBITS).subtract(BigInteger.ONE); // private static final BigDecimal MAX_FLEXINT_VALUE_DECIMAL = new BigDecimal(MAX_FLEXINT_VALUE); // // public static final BigDecimal NINETY = BigDecimal.valueOf(90); // public static final BigDecimal ONEHUNDREDEIGHTY = BigDecimal.valueOf(180); // public static final BigDecimal THREEHUNDRESIXTY = BigDecimal.valueOf(360); // // private static final BigInteger BI_2_64 = BigInteger.ONE.shiftLeft(64); // only use once in long to biginteger conversion // public static BigInteger unsignedToBigInteger(long l) { // final BigInteger bi = BigInteger.valueOf(l); // return l >= 0 ? bi : bi.add(BI_2_64); // } // // public static String bit_marker_flexint(String attribute, int bit, boolean on) { // return bit_marker(attribute, FLEXINT_TYPE, FLEXINT_MAXBITS, bit, on); // } // // private static String bit_marker(String attribute, String type, int maxBits, int bit, boolean on) { // if (bit >= maxBits) throw new RuntimeException("bit is greater than maxbits"); // StringBuilder result = new StringBuilder(attribute.length() + maxBits + type.length() + 2); // StringBuilder bitmarks = new StringBuilder(maxBits + 1); // result.append(attribute).append('_').append(type).append('_'); // for (int i = 0; i < maxBits; i++) { // bitmarks.append('x'); // } // bitmarks.setCharAt(maxBits - bit - 1, on ? '1' : '0'); // return result.append(bitmarks).toString(); // } // // public static boolean isLessThanUnsigned(long n1, long n2) { // boolean comp = (n1 < n2); // if ((n1 < 0) != (n2 < 0)) { // comp = !comp; // } // return comp; // } // // public static BigInteger convertLatitudeToLong(double lat) { // if (Math.abs(lat) > 90) throw new IllegalArgumentException("Latitude can only be between -90 and 90"); // BigDecimal decimal = BigDecimal.valueOf(lat); // //truncating ok, since number is always positive and would ne to be rounded down anyway // return decimal.add(NINETY).divide(ONEHUNDREDEIGHTY, MathContext.DECIMAL128).multiply(MAX_FLEXINT_VALUE_DECIMAL).toBigInteger(); // } // // public static double convertLongToLatitude(long lat) { // only used for previewing the resulting value, and unit tests // BigDecimal latitude = new BigDecimal(unsignedToBigInteger(lat)); // return latitude.divide(MAX_FLEXINT_VALUE_DECIMAL, MathContext.DECIMAL128).multiply(ONEHUNDREDEIGHTY).subtract(NINETY).doubleValue(); // } // // public static BigInteger convertLongitudeToLong(double lng) { // if (Math.abs(lng) > 180) throw new IllegalArgumentException("Longitude can only be between -180 and 180"); // BigDecimal decimal = BigDecimal.valueOf(lng); // return decimal.add(ONEHUNDREDEIGHTY).divide(THREEHUNDRESIXTY, MathContext.DECIMAL128).multiply(MAX_FLEXINT_VALUE_DECIMAL).toBigInteger(); // } // // public static double convertLongToLongitude(long lng) { // BigDecimal latitude = new BigDecimal(unsignedToBigInteger(lng)); // return latitude.divide(MAX_FLEXINT_VALUE_DECIMAL, MathContext.DECIMAL128).multiply(THREEHUNDRESIXTY).subtract(ONEHUNDREDEIGHTY).doubleValue(); // } // } // // Path: src/test/java/cpabe/tests/rules/RepeatRule.java // public class RepeatRule implements TestRule { // // @Override // public Statement apply(Statement statement, Description description) { // Statement result = statement; // Repeat repeat = description.getAnnotation(Repeat.class); // if (repeat != null) { // int times = repeat.value(); // result = new RepeatStatement(times, statement); // } // return result; // } // // private static class RepeatStatement extends Statement { // private final int times; // private final Statement statement; // // private RepeatStatement(int times, Statement statement) { // this.times = times; // this.statement = statement; // } // // @Override // public void evaluate() throws Throwable { // for (int i = 0; i < times; i++) { // statement.evaluate(); // } // } // } // } // Path: src/test/java/cpabe/tests/ConversionTest.java import cpabe.policy.Util; import cpabe.tests.rules.Repeat; import cpabe.tests.rules.RepeatRule; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import java.math.BigInteger; import java.security.SecureRandom; import static org.junit.Assert.assertTrue; package cpabe.tests; public class ConversionTest { public static BigInteger MAX_SIGNED_LONG = BigInteger.valueOf(Long.MAX_VALUE); private static SecureRandom random;
private final double epsilon = Util.FLEXINT_MAXBITS == 64 ? 1E-10 : (Util.FLEXINT_MAXBITS == 32 ? 1E-7 : 1E-2); //TODO calculate bound for 16 bits
TU-Berlin-SNET/JCPABE
src/test/java/cpabe/tests/ConversionTest.java
// Path: src/main/java/cpabe/policy/Util.java // public class Util { // // public static final String FLEXINT_TYPE = "flexint"; // public static final int FLEXINT_MAXBITS = 64; // // public static final BigInteger MIN_FLEXINT_VALUE = BigInteger.ZERO; // public static final BigInteger MAX_FLEXINT_VALUE = BigInteger.ONE.shiftLeft(FLEXINT_MAXBITS).subtract(BigInteger.ONE); // private static final BigDecimal MAX_FLEXINT_VALUE_DECIMAL = new BigDecimal(MAX_FLEXINT_VALUE); // // public static final BigDecimal NINETY = BigDecimal.valueOf(90); // public static final BigDecimal ONEHUNDREDEIGHTY = BigDecimal.valueOf(180); // public static final BigDecimal THREEHUNDRESIXTY = BigDecimal.valueOf(360); // // private static final BigInteger BI_2_64 = BigInteger.ONE.shiftLeft(64); // only use once in long to biginteger conversion // public static BigInteger unsignedToBigInteger(long l) { // final BigInteger bi = BigInteger.valueOf(l); // return l >= 0 ? bi : bi.add(BI_2_64); // } // // public static String bit_marker_flexint(String attribute, int bit, boolean on) { // return bit_marker(attribute, FLEXINT_TYPE, FLEXINT_MAXBITS, bit, on); // } // // private static String bit_marker(String attribute, String type, int maxBits, int bit, boolean on) { // if (bit >= maxBits) throw new RuntimeException("bit is greater than maxbits"); // StringBuilder result = new StringBuilder(attribute.length() + maxBits + type.length() + 2); // StringBuilder bitmarks = new StringBuilder(maxBits + 1); // result.append(attribute).append('_').append(type).append('_'); // for (int i = 0; i < maxBits; i++) { // bitmarks.append('x'); // } // bitmarks.setCharAt(maxBits - bit - 1, on ? '1' : '0'); // return result.append(bitmarks).toString(); // } // // public static boolean isLessThanUnsigned(long n1, long n2) { // boolean comp = (n1 < n2); // if ((n1 < 0) != (n2 < 0)) { // comp = !comp; // } // return comp; // } // // public static BigInteger convertLatitudeToLong(double lat) { // if (Math.abs(lat) > 90) throw new IllegalArgumentException("Latitude can only be between -90 and 90"); // BigDecimal decimal = BigDecimal.valueOf(lat); // //truncating ok, since number is always positive and would ne to be rounded down anyway // return decimal.add(NINETY).divide(ONEHUNDREDEIGHTY, MathContext.DECIMAL128).multiply(MAX_FLEXINT_VALUE_DECIMAL).toBigInteger(); // } // // public static double convertLongToLatitude(long lat) { // only used for previewing the resulting value, and unit tests // BigDecimal latitude = new BigDecimal(unsignedToBigInteger(lat)); // return latitude.divide(MAX_FLEXINT_VALUE_DECIMAL, MathContext.DECIMAL128).multiply(ONEHUNDREDEIGHTY).subtract(NINETY).doubleValue(); // } // // public static BigInteger convertLongitudeToLong(double lng) { // if (Math.abs(lng) > 180) throw new IllegalArgumentException("Longitude can only be between -180 and 180"); // BigDecimal decimal = BigDecimal.valueOf(lng); // return decimal.add(ONEHUNDREDEIGHTY).divide(THREEHUNDRESIXTY, MathContext.DECIMAL128).multiply(MAX_FLEXINT_VALUE_DECIMAL).toBigInteger(); // } // // public static double convertLongToLongitude(long lng) { // BigDecimal latitude = new BigDecimal(unsignedToBigInteger(lng)); // return latitude.divide(MAX_FLEXINT_VALUE_DECIMAL, MathContext.DECIMAL128).multiply(THREEHUNDRESIXTY).subtract(ONEHUNDREDEIGHTY).doubleValue(); // } // } // // Path: src/test/java/cpabe/tests/rules/RepeatRule.java // public class RepeatRule implements TestRule { // // @Override // public Statement apply(Statement statement, Description description) { // Statement result = statement; // Repeat repeat = description.getAnnotation(Repeat.class); // if (repeat != null) { // int times = repeat.value(); // result = new RepeatStatement(times, statement); // } // return result; // } // // private static class RepeatStatement extends Statement { // private final int times; // private final Statement statement; // // private RepeatStatement(int times, Statement statement) { // this.times = times; // this.statement = statement; // } // // @Override // public void evaluate() throws Throwable { // for (int i = 0; i < times; i++) { // statement.evaluate(); // } // } // } // }
import cpabe.policy.Util; import cpabe.tests.rules.Repeat; import cpabe.tests.rules.RepeatRule; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import java.math.BigInteger; import java.security.SecureRandom; import static org.junit.Assert.assertTrue;
package cpabe.tests; public class ConversionTest { public static BigInteger MAX_SIGNED_LONG = BigInteger.valueOf(Long.MAX_VALUE); private static SecureRandom random; private final double epsilon = Util.FLEXINT_MAXBITS == 64 ? 1E-10 : (Util.FLEXINT_MAXBITS == 32 ? 1E-7 : 1E-2); //TODO calculate bound for 16 bits @Rule
// Path: src/main/java/cpabe/policy/Util.java // public class Util { // // public static final String FLEXINT_TYPE = "flexint"; // public static final int FLEXINT_MAXBITS = 64; // // public static final BigInteger MIN_FLEXINT_VALUE = BigInteger.ZERO; // public static final BigInteger MAX_FLEXINT_VALUE = BigInteger.ONE.shiftLeft(FLEXINT_MAXBITS).subtract(BigInteger.ONE); // private static final BigDecimal MAX_FLEXINT_VALUE_DECIMAL = new BigDecimal(MAX_FLEXINT_VALUE); // // public static final BigDecimal NINETY = BigDecimal.valueOf(90); // public static final BigDecimal ONEHUNDREDEIGHTY = BigDecimal.valueOf(180); // public static final BigDecimal THREEHUNDRESIXTY = BigDecimal.valueOf(360); // // private static final BigInteger BI_2_64 = BigInteger.ONE.shiftLeft(64); // only use once in long to biginteger conversion // public static BigInteger unsignedToBigInteger(long l) { // final BigInteger bi = BigInteger.valueOf(l); // return l >= 0 ? bi : bi.add(BI_2_64); // } // // public static String bit_marker_flexint(String attribute, int bit, boolean on) { // return bit_marker(attribute, FLEXINT_TYPE, FLEXINT_MAXBITS, bit, on); // } // // private static String bit_marker(String attribute, String type, int maxBits, int bit, boolean on) { // if (bit >= maxBits) throw new RuntimeException("bit is greater than maxbits"); // StringBuilder result = new StringBuilder(attribute.length() + maxBits + type.length() + 2); // StringBuilder bitmarks = new StringBuilder(maxBits + 1); // result.append(attribute).append('_').append(type).append('_'); // for (int i = 0; i < maxBits; i++) { // bitmarks.append('x'); // } // bitmarks.setCharAt(maxBits - bit - 1, on ? '1' : '0'); // return result.append(bitmarks).toString(); // } // // public static boolean isLessThanUnsigned(long n1, long n2) { // boolean comp = (n1 < n2); // if ((n1 < 0) != (n2 < 0)) { // comp = !comp; // } // return comp; // } // // public static BigInteger convertLatitudeToLong(double lat) { // if (Math.abs(lat) > 90) throw new IllegalArgumentException("Latitude can only be between -90 and 90"); // BigDecimal decimal = BigDecimal.valueOf(lat); // //truncating ok, since number is always positive and would ne to be rounded down anyway // return decimal.add(NINETY).divide(ONEHUNDREDEIGHTY, MathContext.DECIMAL128).multiply(MAX_FLEXINT_VALUE_DECIMAL).toBigInteger(); // } // // public static double convertLongToLatitude(long lat) { // only used for previewing the resulting value, and unit tests // BigDecimal latitude = new BigDecimal(unsignedToBigInteger(lat)); // return latitude.divide(MAX_FLEXINT_VALUE_DECIMAL, MathContext.DECIMAL128).multiply(ONEHUNDREDEIGHTY).subtract(NINETY).doubleValue(); // } // // public static BigInteger convertLongitudeToLong(double lng) { // if (Math.abs(lng) > 180) throw new IllegalArgumentException("Longitude can only be between -180 and 180"); // BigDecimal decimal = BigDecimal.valueOf(lng); // return decimal.add(ONEHUNDREDEIGHTY).divide(THREEHUNDRESIXTY, MathContext.DECIMAL128).multiply(MAX_FLEXINT_VALUE_DECIMAL).toBigInteger(); // } // // public static double convertLongToLongitude(long lng) { // BigDecimal latitude = new BigDecimal(unsignedToBigInteger(lng)); // return latitude.divide(MAX_FLEXINT_VALUE_DECIMAL, MathContext.DECIMAL128).multiply(THREEHUNDRESIXTY).subtract(ONEHUNDREDEIGHTY).doubleValue(); // } // } // // Path: src/test/java/cpabe/tests/rules/RepeatRule.java // public class RepeatRule implements TestRule { // // @Override // public Statement apply(Statement statement, Description description) { // Statement result = statement; // Repeat repeat = description.getAnnotation(Repeat.class); // if (repeat != null) { // int times = repeat.value(); // result = new RepeatStatement(times, statement); // } // return result; // } // // private static class RepeatStatement extends Statement { // private final int times; // private final Statement statement; // // private RepeatStatement(int times, Statement statement) { // this.times = times; // this.statement = statement; // } // // @Override // public void evaluate() throws Throwable { // for (int i = 0; i < times; i++) { // statement.evaluate(); // } // } // } // } // Path: src/test/java/cpabe/tests/ConversionTest.java import cpabe.policy.Util; import cpabe.tests.rules.Repeat; import cpabe.tests.rules.RepeatRule; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import java.math.BigInteger; import java.security.SecureRandom; import static org.junit.Assert.assertTrue; package cpabe.tests; public class ConversionTest { public static BigInteger MAX_SIGNED_LONG = BigInteger.valueOf(Long.MAX_VALUE); private static SecureRandom random; private final double epsilon = Util.FLEXINT_MAXBITS == 64 ? 1E-10 : (Util.FLEXINT_MAXBITS == 32 ? 1E-7 : 1E-2); //TODO calculate bound for 16 bits @Rule
public RepeatRule repeatRule = new RepeatRule();
TU-Berlin-SNET/JCPABE
src/main/java/cpabe/aes/AesEncryption.java
// Path: src/main/java/cpabe/AbeDecryptionException.java // public class AbeDecryptionException extends GeneralSecurityException { // // private static final long serialVersionUID = 2848983353356933397L; // // public AbeDecryptionException(String msg) { // super(msg); // } // // public AbeDecryptionException(String msg, Throwable t) { // super(msg, t); // } // } // // Path: src/main/java/cpabe/AbeEncryptionException.java // public class AbeEncryptionException extends GeneralSecurityException { // // private static final long serialVersionUID = 1043863535572140323L; // // public AbeEncryptionException(String msg) { // super(msg); // } // // public AbeEncryptionException(String msg, Throwable t) { // super(msg, t); // } // // }
import cpabe.AbeDecryptionException; import cpabe.AbeEncryptionException; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays;
package cpabe.aes; //import org.bouncycastle.jce.provider.BouncyCastleProvider; public class AesEncryption { private final static String KEY_ALGORITHM = "AES"; private final static String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; //"AES/GCM/NoPadding" not working on android private final static String HASHING_ALGORITHM = "SHA-256"; private static final int BUFFERSIZE = 1024; // We use AES128 per schneier, so we need to reduce the keysize private static final int AES_KEY_LENGTH = 16; static { //Security.addProvider(new BouncyCastleProvider()); } private static byte[] hash(byte[] cpabeData) { try { MessageDigest sha256 = MessageDigest.getInstance(HASHING_ALGORITHM); return Arrays.copyOf(sha256.digest(cpabeData), AES_KEY_LENGTH); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Hashing Alogrithm not available: " + HASHING_ALGORITHM, e); } } private static byte[] combine(byte[] cpabeData, byte[] lbeKey) { byte[] hashedCpabeSecret = hash(cpabeData); if (lbeKey != null) { if (hashedCpabeSecret.length != lbeKey.length) { throw new RuntimeException("wrong key size for lbeKey, " + hashedCpabeSecret.length + " bytes required"); } for (int i = 0; i < lbeKey.length; i++) { hashedCpabeSecret[i] = (byte) (hashedCpabeSecret[i] ^ lbeKey[i]); } } return hashedCpabeSecret; }
// Path: src/main/java/cpabe/AbeDecryptionException.java // public class AbeDecryptionException extends GeneralSecurityException { // // private static final long serialVersionUID = 2848983353356933397L; // // public AbeDecryptionException(String msg) { // super(msg); // } // // public AbeDecryptionException(String msg, Throwable t) { // super(msg, t); // } // } // // Path: src/main/java/cpabe/AbeEncryptionException.java // public class AbeEncryptionException extends GeneralSecurityException { // // private static final long serialVersionUID = 1043863535572140323L; // // public AbeEncryptionException(String msg) { // super(msg); // } // // public AbeEncryptionException(String msg, Throwable t) { // super(msg, t); // } // // } // Path: src/main/java/cpabe/aes/AesEncryption.java import cpabe.AbeDecryptionException; import cpabe.AbeEncryptionException; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; package cpabe.aes; //import org.bouncycastle.jce.provider.BouncyCastleProvider; public class AesEncryption { private final static String KEY_ALGORITHM = "AES"; private final static String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; //"AES/GCM/NoPadding" not working on android private final static String HASHING_ALGORITHM = "SHA-256"; private static final int BUFFERSIZE = 1024; // We use AES128 per schneier, so we need to reduce the keysize private static final int AES_KEY_LENGTH = 16; static { //Security.addProvider(new BouncyCastleProvider()); } private static byte[] hash(byte[] cpabeData) { try { MessageDigest sha256 = MessageDigest.getInstance(HASHING_ALGORITHM); return Arrays.copyOf(sha256.digest(cpabeData), AES_KEY_LENGTH); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Hashing Alogrithm not available: " + HASHING_ALGORITHM, e); } } private static byte[] combine(byte[] cpabeData, byte[] lbeKey) { byte[] hashedCpabeSecret = hash(cpabeData); if (lbeKey != null) { if (hashedCpabeSecret.length != lbeKey.length) { throw new RuntimeException("wrong key size for lbeKey, " + hashedCpabeSecret.length + " bytes required"); } for (int i = 0; i < lbeKey.length; i++) { hashedCpabeSecret[i] = (byte) (hashedCpabeSecret[i] ^ lbeKey[i]); } } return hashedCpabeSecret; }
public static void encrypt(byte[] cpabeKey, byte[] lbeKey, byte[] iv, InputStream input, OutputStream output) throws IOException, AbeEncryptionException {
TU-Berlin-SNET/JCPABE
src/main/java/cpabe/aes/AesEncryption.java
// Path: src/main/java/cpabe/AbeDecryptionException.java // public class AbeDecryptionException extends GeneralSecurityException { // // private static final long serialVersionUID = 2848983353356933397L; // // public AbeDecryptionException(String msg) { // super(msg); // } // // public AbeDecryptionException(String msg, Throwable t) { // super(msg, t); // } // } // // Path: src/main/java/cpabe/AbeEncryptionException.java // public class AbeEncryptionException extends GeneralSecurityException { // // private static final long serialVersionUID = 1043863535572140323L; // // public AbeEncryptionException(String msg) { // super(msg); // } // // public AbeEncryptionException(String msg, Throwable t) { // super(msg, t); // } // // }
import cpabe.AbeDecryptionException; import cpabe.AbeEncryptionException; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays;
return hashedCpabeSecret; } public static void encrypt(byte[] cpabeKey, byte[] lbeKey, byte[] iv, InputStream input, OutputStream output) throws IOException, AbeEncryptionException { try { CipherInputStream cis = encrypt(cpabeKey, lbeKey, iv, input); int read; byte[] buffer = new byte[BUFFERSIZE]; while ((read = cis.read(buffer)) >= 0) { output.write(buffer, 0, read); } output.close(); cis.close(); } catch (GeneralSecurityException e) { throw new AbeEncryptionException(e.getMessage(), e); } } public static CipherInputStream encrypt(byte[] cpabeKey, byte[] lbeKey, byte[] iv, InputStream input) throws AbeEncryptionException { try { SecretKeySpec skeySpec = new SecretKeySpec(combine(cpabeKey, lbeKey), KEY_ALGORITHM); Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv)); CipherInputStream cis = new CipherInputStream(input, cipher); return cis; } catch (GeneralSecurityException e) { throw new AbeEncryptionException(e.getMessage(), e); } }
// Path: src/main/java/cpabe/AbeDecryptionException.java // public class AbeDecryptionException extends GeneralSecurityException { // // private static final long serialVersionUID = 2848983353356933397L; // // public AbeDecryptionException(String msg) { // super(msg); // } // // public AbeDecryptionException(String msg, Throwable t) { // super(msg, t); // } // } // // Path: src/main/java/cpabe/AbeEncryptionException.java // public class AbeEncryptionException extends GeneralSecurityException { // // private static final long serialVersionUID = 1043863535572140323L; // // public AbeEncryptionException(String msg) { // super(msg); // } // // public AbeEncryptionException(String msg, Throwable t) { // super(msg, t); // } // // } // Path: src/main/java/cpabe/aes/AesEncryption.java import cpabe.AbeDecryptionException; import cpabe.AbeEncryptionException; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; return hashedCpabeSecret; } public static void encrypt(byte[] cpabeKey, byte[] lbeKey, byte[] iv, InputStream input, OutputStream output) throws IOException, AbeEncryptionException { try { CipherInputStream cis = encrypt(cpabeKey, lbeKey, iv, input); int read; byte[] buffer = new byte[BUFFERSIZE]; while ((read = cis.read(buffer)) >= 0) { output.write(buffer, 0, read); } output.close(); cis.close(); } catch (GeneralSecurityException e) { throw new AbeEncryptionException(e.getMessage(), e); } } public static CipherInputStream encrypt(byte[] cpabeKey, byte[] lbeKey, byte[] iv, InputStream input) throws AbeEncryptionException { try { SecretKeySpec skeySpec = new SecretKeySpec(combine(cpabeKey, lbeKey), KEY_ALGORITHM); Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv)); CipherInputStream cis = new CipherInputStream(input, cipher); return cis; } catch (GeneralSecurityException e) { throw new AbeEncryptionException(e.getMessage(), e); } }
public static CipherInputStream decrypt(byte[] cpabeKey, byte[] lbeKey, byte[] iv, InputStream input) throws AbeDecryptionException {
TU-Berlin-SNET/JCPABE
src/main/java/cpabe/AbePrivateKey.java
// Path: src/main/java/cpabe/bsw07/Bsw07PrivateKeyComponent.java // public class Bsw07PrivateKeyComponent { // /* these actually get serialized */ // /** // * G2 // **/ // public Element hashedAttribute; // /** // * G2 // **/ // public Element d; // /** // * G2 // **/ // public Element dp; // // public Bsw07PrivateKeyComponent(Element hashedAttribute, Element d, Element dp) { // this.hashedAttribute = hashedAttribute; // this.d = d; // this.dp = dp; // } // // // @Override // public String toString() { // return hashedAttribute.toString(); // } // // public static Bsw07PrivateKeyComponent readFromStream(AbeInputStream abeStream) throws IOException { // Element hashedAttribute = abeStream.readElement(); // Element d = abeStream.readElement(); // Element dp = abeStream.readElement(); // return new Bsw07PrivateKeyComponent(hashedAttribute, d, dp); // } // // public void writeToStream(AbeOutputStream abeStream) throws IOException { // abeStream.writeElement(hashedAttribute); // abeStream.writeElement(d); // abeStream.writeElement(dp); // } // }
import cpabe.bsw07.Bsw07PrivateKeyComponent; import it.unisa.dia.gas.jpbc.Element; import java.io.*; import java.util.ArrayList; import java.util.List;
package cpabe; public class AbePrivateKey { /* * A private key */ /** * G2 **/ Element d;
// Path: src/main/java/cpabe/bsw07/Bsw07PrivateKeyComponent.java // public class Bsw07PrivateKeyComponent { // /* these actually get serialized */ // /** // * G2 // **/ // public Element hashedAttribute; // /** // * G2 // **/ // public Element d; // /** // * G2 // **/ // public Element dp; // // public Bsw07PrivateKeyComponent(Element hashedAttribute, Element d, Element dp) { // this.hashedAttribute = hashedAttribute; // this.d = d; // this.dp = dp; // } // // // @Override // public String toString() { // return hashedAttribute.toString(); // } // // public static Bsw07PrivateKeyComponent readFromStream(AbeInputStream abeStream) throws IOException { // Element hashedAttribute = abeStream.readElement(); // Element d = abeStream.readElement(); // Element dp = abeStream.readElement(); // return new Bsw07PrivateKeyComponent(hashedAttribute, d, dp); // } // // public void writeToStream(AbeOutputStream abeStream) throws IOException { // abeStream.writeElement(hashedAttribute); // abeStream.writeElement(d); // abeStream.writeElement(dp); // } // } // Path: src/main/java/cpabe/AbePrivateKey.java import cpabe.bsw07.Bsw07PrivateKeyComponent; import it.unisa.dia.gas.jpbc.Element; import java.io.*; import java.util.ArrayList; import java.util.List; package cpabe; public class AbePrivateKey { /* * A private key */ /** * G2 **/ Element d;
ArrayList<Bsw07PrivateKeyComponent> components;
TU-Berlin-SNET/JCPABE
src/main/java/cpabe/bsw07/Bsw07Util.java
// Path: src/main/java/cpabe/AbePublicKey.java // public class AbePublicKey { // /** // * G_1 // **/ // public Element g; // /** // * G_1 // **/ // public Element h; // /** // * G_1 // **/ // public Element f; // /** // * G_T // **/ // public Element e_g_g_hat_alpha; // /* // * A public key // */ // private String pairingDesc; // private transient Pairing p; // // /** // * Creates a new AbePublicKey. This key should only be used after the elements have been set (setElements). // * // * @param pairingDescription // */ // public AbePublicKey(String pairingDescription) { // this.pairingDesc = pairingDescription; // } // // public static AbePublicKey readFromFile(File file) throws IOException { // try (AbeInputStream stream = new AbeInputStream(new FileInputStream(file))) { // return readFromStream(stream); // } // } // // public static AbePublicKey readFromStream(AbeInputStream stream) throws IOException { // String pairingDescription = stream.readString(); // AbePublicKey publicKey = new AbePublicKey(pairingDescription); // stream.setPublicKey(publicKey); // publicKey.g = stream.readElement(); // publicKey.h = stream.readElement(); // publicKey.f = stream.readElement(); // publicKey.e_g_g_hat_alpha = stream.readElement(); // return publicKey; // } // // public String getPairingDescription() { // return pairingDesc; // } // // public Pairing getPairing() { // if (p == null) { // PairingParameters params = new PropertiesParameters().load(new ByteArrayInputStream(pairingDesc.getBytes())); // p = PairingFactory.getPairing(params); // } // return p; // } // // public void setElements(Element g, Element h, Element f, Element e_g_g_hat_alpha) { // this.g = g; // this.h = h; // this.f = f; // this.e_g_g_hat_alpha = e_g_g_hat_alpha; // } // // public void writeToStream(AbeOutputStream stream) throws IOException { // stream.writeString(pairingDesc); // stream.writeElement(g); // stream.writeElement(h); // stream.writeElement(f); // stream.writeElement(e_g_g_hat_alpha); // } // // public void writeToFile(File file) throws IOException { // try (AbeOutputStream fos = new AbeOutputStream(new FileOutputStream(file), this)) { // writeToStream(fos); // } // } // } // // Path: src/main/java/cpabe/AbeSettings.java // public class AbeSettings { // public final static DateFormat defaultDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // public final static String STRINGS_LOCALE = "US-ASCII"; // public final static String ELEMENT_HASHING_ALGORITHM = "SHA-1"; // public final static String curveParams = "type a\n" + "q 87807107996633125224377819847540498158068831994142082" // + "1102865339926647563088022295707862517942266222142315585" // + "8769582317459277713367317481324925129998224791\n" // + "h 12016012264891146079388821366740534204802954401251311" // + "822919615131047207289359704531102844802183906537786776\n" // + "r 730750818665451621361119245571504901405976559617\n" + "exp2 159\n" + "exp1 107\n" // + "sign1 1\n" + "sign0 1\n"; // // public static String getCurrentTime() { // return AbeSettings.defaultDateFormat.format(Calendar.getInstance().getTime()); // } // }
import cpabe.AbePublicKey; import cpabe.AbeSettings; import it.unisa.dia.gas.jpbc.Element; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException;
package cpabe.bsw07; public class Bsw07Util { public static Element elementG2FromString(String s, AbePublicKey publicKey) { try {
// Path: src/main/java/cpabe/AbePublicKey.java // public class AbePublicKey { // /** // * G_1 // **/ // public Element g; // /** // * G_1 // **/ // public Element h; // /** // * G_1 // **/ // public Element f; // /** // * G_T // **/ // public Element e_g_g_hat_alpha; // /* // * A public key // */ // private String pairingDesc; // private transient Pairing p; // // /** // * Creates a new AbePublicKey. This key should only be used after the elements have been set (setElements). // * // * @param pairingDescription // */ // public AbePublicKey(String pairingDescription) { // this.pairingDesc = pairingDescription; // } // // public static AbePublicKey readFromFile(File file) throws IOException { // try (AbeInputStream stream = new AbeInputStream(new FileInputStream(file))) { // return readFromStream(stream); // } // } // // public static AbePublicKey readFromStream(AbeInputStream stream) throws IOException { // String pairingDescription = stream.readString(); // AbePublicKey publicKey = new AbePublicKey(pairingDescription); // stream.setPublicKey(publicKey); // publicKey.g = stream.readElement(); // publicKey.h = stream.readElement(); // publicKey.f = stream.readElement(); // publicKey.e_g_g_hat_alpha = stream.readElement(); // return publicKey; // } // // public String getPairingDescription() { // return pairingDesc; // } // // public Pairing getPairing() { // if (p == null) { // PairingParameters params = new PropertiesParameters().load(new ByteArrayInputStream(pairingDesc.getBytes())); // p = PairingFactory.getPairing(params); // } // return p; // } // // public void setElements(Element g, Element h, Element f, Element e_g_g_hat_alpha) { // this.g = g; // this.h = h; // this.f = f; // this.e_g_g_hat_alpha = e_g_g_hat_alpha; // } // // public void writeToStream(AbeOutputStream stream) throws IOException { // stream.writeString(pairingDesc); // stream.writeElement(g); // stream.writeElement(h); // stream.writeElement(f); // stream.writeElement(e_g_g_hat_alpha); // } // // public void writeToFile(File file) throws IOException { // try (AbeOutputStream fos = new AbeOutputStream(new FileOutputStream(file), this)) { // writeToStream(fos); // } // } // } // // Path: src/main/java/cpabe/AbeSettings.java // public class AbeSettings { // public final static DateFormat defaultDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // public final static String STRINGS_LOCALE = "US-ASCII"; // public final static String ELEMENT_HASHING_ALGORITHM = "SHA-1"; // public final static String curveParams = "type a\n" + "q 87807107996633125224377819847540498158068831994142082" // + "1102865339926647563088022295707862517942266222142315585" // + "8769582317459277713367317481324925129998224791\n" // + "h 12016012264891146079388821366740534204802954401251311" // + "822919615131047207289359704531102844802183906537786776\n" // + "r 730750818665451621361119245571504901405976559617\n" + "exp2 159\n" + "exp1 107\n" // + "sign1 1\n" + "sign0 1\n"; // // public static String getCurrentTime() { // return AbeSettings.defaultDateFormat.format(Calendar.getInstance().getTime()); // } // } // Path: src/main/java/cpabe/bsw07/Bsw07Util.java import cpabe.AbePublicKey; import cpabe.AbeSettings; import it.unisa.dia.gas.jpbc.Element; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; package cpabe.bsw07; public class Bsw07Util { public static Element elementG2FromString(String s, AbePublicKey publicKey) { try {
MessageDigest sha1 = MessageDigest.getInstance(AbeSettings.ELEMENT_HASHING_ALGORITHM);
TU-Berlin-SNET/JCPABE
src/main/java/cpabe/bsw07/Bsw07PrivateKeyComponent.java
// Path: src/main/java/cpabe/AbeInputStream.java // public class AbeInputStream extends DataInputStream { // private final String PUB_MISSING_ERROR = "Can't read Elements without the public master key."; // // private AbePublicKey publicKey; // // public AbeInputStream(InputStream in, AbePublicKey publicKey) { // super(in); // this.publicKey = publicKey; // } // // /** // * If you use this constructor you need to manually set the public key before reading any elements. // * // * @param in // */ // public AbeInputStream(InputStream in) { // this(in, null); // } // // public void setPublicKey(AbePublicKey pubKey) { // this.publicKey = pubKey; // } // // // only used for the curve parameters and attributes, no need for fancy encodings // // since internal attribute representation only uses [a-zA-Z0-9:_] // public String readString() throws IOException { // int length = readInt(); // byte[] bytes = new byte[length]; // readFully(bytes); // return new String(bytes, AbeSettings.STRINGS_LOCALE); // } // // public Element readElement() throws IOException { // if (publicKey == null) throw new IOException(PUB_MISSING_ERROR); // int fieldIndex = readInt(); // int length = readInt(); // byte[] bytes = new byte[length]; // readFully(bytes); // return publicKey.getPairing().getFieldAt(fieldIndex).newElementFromBytes(bytes); // } // } // // Path: src/main/java/cpabe/AbeOutputStream.java // public class AbeOutputStream extends DataOutputStream { // // private AbePublicKey pubKey; // // public AbeOutputStream(OutputStream out, AbePublicKey pubKey) { // super(out); // this.pubKey = pubKey; // } // // // only used for the curve parameters and attributes, no need for fancy encodings // public void writeString(String string) throws IOException { // byte[] bytes = string.getBytes(AbeSettings.STRINGS_LOCALE); // writeInt(bytes.length); // write(bytes); // } // // public void writeElement(Element elem) throws IOException { // writeInt(pubKey.getPairing().getFieldIndex(elem.getField())); // byte[] bytes = elem.toBytes(); // writeInt(bytes.length); // write(bytes); // } // // }
import cpabe.AbeInputStream; import cpabe.AbeOutputStream; import it.unisa.dia.gas.jpbc.Element; import java.io.IOException;
package cpabe.bsw07; public class Bsw07PrivateKeyComponent { /* these actually get serialized */ /** * G2 **/ public Element hashedAttribute; /** * G2 **/ public Element d; /** * G2 **/ public Element dp; public Bsw07PrivateKeyComponent(Element hashedAttribute, Element d, Element dp) { this.hashedAttribute = hashedAttribute; this.d = d; this.dp = dp; } @Override public String toString() { return hashedAttribute.toString(); }
// Path: src/main/java/cpabe/AbeInputStream.java // public class AbeInputStream extends DataInputStream { // private final String PUB_MISSING_ERROR = "Can't read Elements without the public master key."; // // private AbePublicKey publicKey; // // public AbeInputStream(InputStream in, AbePublicKey publicKey) { // super(in); // this.publicKey = publicKey; // } // // /** // * If you use this constructor you need to manually set the public key before reading any elements. // * // * @param in // */ // public AbeInputStream(InputStream in) { // this(in, null); // } // // public void setPublicKey(AbePublicKey pubKey) { // this.publicKey = pubKey; // } // // // only used for the curve parameters and attributes, no need for fancy encodings // // since internal attribute representation only uses [a-zA-Z0-9:_] // public String readString() throws IOException { // int length = readInt(); // byte[] bytes = new byte[length]; // readFully(bytes); // return new String(bytes, AbeSettings.STRINGS_LOCALE); // } // // public Element readElement() throws IOException { // if (publicKey == null) throw new IOException(PUB_MISSING_ERROR); // int fieldIndex = readInt(); // int length = readInt(); // byte[] bytes = new byte[length]; // readFully(bytes); // return publicKey.getPairing().getFieldAt(fieldIndex).newElementFromBytes(bytes); // } // } // // Path: src/main/java/cpabe/AbeOutputStream.java // public class AbeOutputStream extends DataOutputStream { // // private AbePublicKey pubKey; // // public AbeOutputStream(OutputStream out, AbePublicKey pubKey) { // super(out); // this.pubKey = pubKey; // } // // // only used for the curve parameters and attributes, no need for fancy encodings // public void writeString(String string) throws IOException { // byte[] bytes = string.getBytes(AbeSettings.STRINGS_LOCALE); // writeInt(bytes.length); // write(bytes); // } // // public void writeElement(Element elem) throws IOException { // writeInt(pubKey.getPairing().getFieldIndex(elem.getField())); // byte[] bytes = elem.toBytes(); // writeInt(bytes.length); // write(bytes); // } // // } // Path: src/main/java/cpabe/bsw07/Bsw07PrivateKeyComponent.java import cpabe.AbeInputStream; import cpabe.AbeOutputStream; import it.unisa.dia.gas.jpbc.Element; import java.io.IOException; package cpabe.bsw07; public class Bsw07PrivateKeyComponent { /* these actually get serialized */ /** * G2 **/ public Element hashedAttribute; /** * G2 **/ public Element d; /** * G2 **/ public Element dp; public Bsw07PrivateKeyComponent(Element hashedAttribute, Element d, Element dp) { this.hashedAttribute = hashedAttribute; this.d = d; this.dp = dp; } @Override public String toString() { return hashedAttribute.toString(); }
public static Bsw07PrivateKeyComponent readFromStream(AbeInputStream abeStream) throws IOException {
TU-Berlin-SNET/JCPABE
src/main/java/cpabe/bsw07/Bsw07PrivateKeyComponent.java
// Path: src/main/java/cpabe/AbeInputStream.java // public class AbeInputStream extends DataInputStream { // private final String PUB_MISSING_ERROR = "Can't read Elements without the public master key."; // // private AbePublicKey publicKey; // // public AbeInputStream(InputStream in, AbePublicKey publicKey) { // super(in); // this.publicKey = publicKey; // } // // /** // * If you use this constructor you need to manually set the public key before reading any elements. // * // * @param in // */ // public AbeInputStream(InputStream in) { // this(in, null); // } // // public void setPublicKey(AbePublicKey pubKey) { // this.publicKey = pubKey; // } // // // only used for the curve parameters and attributes, no need for fancy encodings // // since internal attribute representation only uses [a-zA-Z0-9:_] // public String readString() throws IOException { // int length = readInt(); // byte[] bytes = new byte[length]; // readFully(bytes); // return new String(bytes, AbeSettings.STRINGS_LOCALE); // } // // public Element readElement() throws IOException { // if (publicKey == null) throw new IOException(PUB_MISSING_ERROR); // int fieldIndex = readInt(); // int length = readInt(); // byte[] bytes = new byte[length]; // readFully(bytes); // return publicKey.getPairing().getFieldAt(fieldIndex).newElementFromBytes(bytes); // } // } // // Path: src/main/java/cpabe/AbeOutputStream.java // public class AbeOutputStream extends DataOutputStream { // // private AbePublicKey pubKey; // // public AbeOutputStream(OutputStream out, AbePublicKey pubKey) { // super(out); // this.pubKey = pubKey; // } // // // only used for the curve parameters and attributes, no need for fancy encodings // public void writeString(String string) throws IOException { // byte[] bytes = string.getBytes(AbeSettings.STRINGS_LOCALE); // writeInt(bytes.length); // write(bytes); // } // // public void writeElement(Element elem) throws IOException { // writeInt(pubKey.getPairing().getFieldIndex(elem.getField())); // byte[] bytes = elem.toBytes(); // writeInt(bytes.length); // write(bytes); // } // // }
import cpabe.AbeInputStream; import cpabe.AbeOutputStream; import it.unisa.dia.gas.jpbc.Element; import java.io.IOException;
package cpabe.bsw07; public class Bsw07PrivateKeyComponent { /* these actually get serialized */ /** * G2 **/ public Element hashedAttribute; /** * G2 **/ public Element d; /** * G2 **/ public Element dp; public Bsw07PrivateKeyComponent(Element hashedAttribute, Element d, Element dp) { this.hashedAttribute = hashedAttribute; this.d = d; this.dp = dp; } @Override public String toString() { return hashedAttribute.toString(); } public static Bsw07PrivateKeyComponent readFromStream(AbeInputStream abeStream) throws IOException { Element hashedAttribute = abeStream.readElement(); Element d = abeStream.readElement(); Element dp = abeStream.readElement(); return new Bsw07PrivateKeyComponent(hashedAttribute, d, dp); }
// Path: src/main/java/cpabe/AbeInputStream.java // public class AbeInputStream extends DataInputStream { // private final String PUB_MISSING_ERROR = "Can't read Elements without the public master key."; // // private AbePublicKey publicKey; // // public AbeInputStream(InputStream in, AbePublicKey publicKey) { // super(in); // this.publicKey = publicKey; // } // // /** // * If you use this constructor you need to manually set the public key before reading any elements. // * // * @param in // */ // public AbeInputStream(InputStream in) { // this(in, null); // } // // public void setPublicKey(AbePublicKey pubKey) { // this.publicKey = pubKey; // } // // // only used for the curve parameters and attributes, no need for fancy encodings // // since internal attribute representation only uses [a-zA-Z0-9:_] // public String readString() throws IOException { // int length = readInt(); // byte[] bytes = new byte[length]; // readFully(bytes); // return new String(bytes, AbeSettings.STRINGS_LOCALE); // } // // public Element readElement() throws IOException { // if (publicKey == null) throw new IOException(PUB_MISSING_ERROR); // int fieldIndex = readInt(); // int length = readInt(); // byte[] bytes = new byte[length]; // readFully(bytes); // return publicKey.getPairing().getFieldAt(fieldIndex).newElementFromBytes(bytes); // } // } // // Path: src/main/java/cpabe/AbeOutputStream.java // public class AbeOutputStream extends DataOutputStream { // // private AbePublicKey pubKey; // // public AbeOutputStream(OutputStream out, AbePublicKey pubKey) { // super(out); // this.pubKey = pubKey; // } // // // only used for the curve parameters and attributes, no need for fancy encodings // public void writeString(String string) throws IOException { // byte[] bytes = string.getBytes(AbeSettings.STRINGS_LOCALE); // writeInt(bytes.length); // write(bytes); // } // // public void writeElement(Element elem) throws IOException { // writeInt(pubKey.getPairing().getFieldIndex(elem.getField())); // byte[] bytes = elem.toBytes(); // writeInt(bytes.length); // write(bytes); // } // // } // Path: src/main/java/cpabe/bsw07/Bsw07PrivateKeyComponent.java import cpabe.AbeInputStream; import cpabe.AbeOutputStream; import it.unisa.dia.gas.jpbc.Element; import java.io.IOException; package cpabe.bsw07; public class Bsw07PrivateKeyComponent { /* these actually get serialized */ /** * G2 **/ public Element hashedAttribute; /** * G2 **/ public Element d; /** * G2 **/ public Element dp; public Bsw07PrivateKeyComponent(Element hashedAttribute, Element d, Element dp) { this.hashedAttribute = hashedAttribute; this.d = d; this.dp = dp; } @Override public String toString() { return hashedAttribute.toString(); } public static Bsw07PrivateKeyComponent readFromStream(AbeInputStream abeStream) throws IOException { Element hashedAttribute = abeStream.readElement(); Element d = abeStream.readElement(); Element dp = abeStream.readElement(); return new Bsw07PrivateKeyComponent(hashedAttribute, d, dp); }
public void writeToStream(AbeOutputStream abeStream) throws IOException {
TU-Berlin-SNET/JCPABE
src/test/java/cpabe/tests/Bsw07Test.java
// Path: src/main/java/cpabe/policy/Util.java // public class Util { // // public static final String FLEXINT_TYPE = "flexint"; // public static final int FLEXINT_MAXBITS = 64; // // public static final BigInteger MIN_FLEXINT_VALUE = BigInteger.ZERO; // public static final BigInteger MAX_FLEXINT_VALUE = BigInteger.ONE.shiftLeft(FLEXINT_MAXBITS).subtract(BigInteger.ONE); // private static final BigDecimal MAX_FLEXINT_VALUE_DECIMAL = new BigDecimal(MAX_FLEXINT_VALUE); // // public static final BigDecimal NINETY = BigDecimal.valueOf(90); // public static final BigDecimal ONEHUNDREDEIGHTY = BigDecimal.valueOf(180); // public static final BigDecimal THREEHUNDRESIXTY = BigDecimal.valueOf(360); // // private static final BigInteger BI_2_64 = BigInteger.ONE.shiftLeft(64); // only use once in long to biginteger conversion // public static BigInteger unsignedToBigInteger(long l) { // final BigInteger bi = BigInteger.valueOf(l); // return l >= 0 ? bi : bi.add(BI_2_64); // } // // public static String bit_marker_flexint(String attribute, int bit, boolean on) { // return bit_marker(attribute, FLEXINT_TYPE, FLEXINT_MAXBITS, bit, on); // } // // private static String bit_marker(String attribute, String type, int maxBits, int bit, boolean on) { // if (bit >= maxBits) throw new RuntimeException("bit is greater than maxbits"); // StringBuilder result = new StringBuilder(attribute.length() + maxBits + type.length() + 2); // StringBuilder bitmarks = new StringBuilder(maxBits + 1); // result.append(attribute).append('_').append(type).append('_'); // for (int i = 0; i < maxBits; i++) { // bitmarks.append('x'); // } // bitmarks.setCharAt(maxBits - bit - 1, on ? '1' : '0'); // return result.append(bitmarks).toString(); // } // // public static boolean isLessThanUnsigned(long n1, long n2) { // boolean comp = (n1 < n2); // if ((n1 < 0) != (n2 < 0)) { // comp = !comp; // } // return comp; // } // // public static BigInteger convertLatitudeToLong(double lat) { // if (Math.abs(lat) > 90) throw new IllegalArgumentException("Latitude can only be between -90 and 90"); // BigDecimal decimal = BigDecimal.valueOf(lat); // //truncating ok, since number is always positive and would ne to be rounded down anyway // return decimal.add(NINETY).divide(ONEHUNDREDEIGHTY, MathContext.DECIMAL128).multiply(MAX_FLEXINT_VALUE_DECIMAL).toBigInteger(); // } // // public static double convertLongToLatitude(long lat) { // only used for previewing the resulting value, and unit tests // BigDecimal latitude = new BigDecimal(unsignedToBigInteger(lat)); // return latitude.divide(MAX_FLEXINT_VALUE_DECIMAL, MathContext.DECIMAL128).multiply(ONEHUNDREDEIGHTY).subtract(NINETY).doubleValue(); // } // // public static BigInteger convertLongitudeToLong(double lng) { // if (Math.abs(lng) > 180) throw new IllegalArgumentException("Longitude can only be between -180 and 180"); // BigDecimal decimal = BigDecimal.valueOf(lng); // return decimal.add(ONEHUNDREDEIGHTY).divide(THREEHUNDRESIXTY, MathContext.DECIMAL128).multiply(MAX_FLEXINT_VALUE_DECIMAL).toBigInteger(); // } // // public static double convertLongToLongitude(long lng) { // BigDecimal latitude = new BigDecimal(unsignedToBigInteger(lng)); // return latitude.divide(MAX_FLEXINT_VALUE_DECIMAL, MathContext.DECIMAL128).multiply(THREEHUNDRESIXTY).subtract(ONEHUNDREDEIGHTY).doubleValue(); // } // } // // Path: src/test/java/cpabe/tests/rules/RepeatRule.java // public class RepeatRule implements TestRule { // // @Override // public Statement apply(Statement statement, Description description) { // Statement result = statement; // Repeat repeat = description.getAnnotation(Repeat.class); // if (repeat != null) { // int times = repeat.value(); // result = new RepeatStatement(times, statement); // } // return result; // } // // private static class RepeatStatement extends Statement { // private final int times; // private final Statement statement; // // private RepeatStatement(int times, Statement statement) { // this.times = times; // this.statement = statement; // } // // @Override // public void evaluate() throws Throwable { // for (int i = 0; i < times; i++) { // statement.evaluate(); // } // } // } // }
import cpabe.*; import cpabe.policy.Util; import cpabe.tests.rules.Repeat; import cpabe.tests.rules.RepeatRule; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import java.io.ByteArrayInputStream; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Arrays; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
package cpabe.tests; public class Bsw07Test { private static SecureRandom random; @Rule
// Path: src/main/java/cpabe/policy/Util.java // public class Util { // // public static final String FLEXINT_TYPE = "flexint"; // public static final int FLEXINT_MAXBITS = 64; // // public static final BigInteger MIN_FLEXINT_VALUE = BigInteger.ZERO; // public static final BigInteger MAX_FLEXINT_VALUE = BigInteger.ONE.shiftLeft(FLEXINT_MAXBITS).subtract(BigInteger.ONE); // private static final BigDecimal MAX_FLEXINT_VALUE_DECIMAL = new BigDecimal(MAX_FLEXINT_VALUE); // // public static final BigDecimal NINETY = BigDecimal.valueOf(90); // public static final BigDecimal ONEHUNDREDEIGHTY = BigDecimal.valueOf(180); // public static final BigDecimal THREEHUNDRESIXTY = BigDecimal.valueOf(360); // // private static final BigInteger BI_2_64 = BigInteger.ONE.shiftLeft(64); // only use once in long to biginteger conversion // public static BigInteger unsignedToBigInteger(long l) { // final BigInteger bi = BigInteger.valueOf(l); // return l >= 0 ? bi : bi.add(BI_2_64); // } // // public static String bit_marker_flexint(String attribute, int bit, boolean on) { // return bit_marker(attribute, FLEXINT_TYPE, FLEXINT_MAXBITS, bit, on); // } // // private static String bit_marker(String attribute, String type, int maxBits, int bit, boolean on) { // if (bit >= maxBits) throw new RuntimeException("bit is greater than maxbits"); // StringBuilder result = new StringBuilder(attribute.length() + maxBits + type.length() + 2); // StringBuilder bitmarks = new StringBuilder(maxBits + 1); // result.append(attribute).append('_').append(type).append('_'); // for (int i = 0; i < maxBits; i++) { // bitmarks.append('x'); // } // bitmarks.setCharAt(maxBits - bit - 1, on ? '1' : '0'); // return result.append(bitmarks).toString(); // } // // public static boolean isLessThanUnsigned(long n1, long n2) { // boolean comp = (n1 < n2); // if ((n1 < 0) != (n2 < 0)) { // comp = !comp; // } // return comp; // } // // public static BigInteger convertLatitudeToLong(double lat) { // if (Math.abs(lat) > 90) throw new IllegalArgumentException("Latitude can only be between -90 and 90"); // BigDecimal decimal = BigDecimal.valueOf(lat); // //truncating ok, since number is always positive and would ne to be rounded down anyway // return decimal.add(NINETY).divide(ONEHUNDREDEIGHTY, MathContext.DECIMAL128).multiply(MAX_FLEXINT_VALUE_DECIMAL).toBigInteger(); // } // // public static double convertLongToLatitude(long lat) { // only used for previewing the resulting value, and unit tests // BigDecimal latitude = new BigDecimal(unsignedToBigInteger(lat)); // return latitude.divide(MAX_FLEXINT_VALUE_DECIMAL, MathContext.DECIMAL128).multiply(ONEHUNDREDEIGHTY).subtract(NINETY).doubleValue(); // } // // public static BigInteger convertLongitudeToLong(double lng) { // if (Math.abs(lng) > 180) throw new IllegalArgumentException("Longitude can only be between -180 and 180"); // BigDecimal decimal = BigDecimal.valueOf(lng); // return decimal.add(ONEHUNDREDEIGHTY).divide(THREEHUNDRESIXTY, MathContext.DECIMAL128).multiply(MAX_FLEXINT_VALUE_DECIMAL).toBigInteger(); // } // // public static double convertLongToLongitude(long lng) { // BigDecimal latitude = new BigDecimal(unsignedToBigInteger(lng)); // return latitude.divide(MAX_FLEXINT_VALUE_DECIMAL, MathContext.DECIMAL128).multiply(THREEHUNDRESIXTY).subtract(ONEHUNDREDEIGHTY).doubleValue(); // } // } // // Path: src/test/java/cpabe/tests/rules/RepeatRule.java // public class RepeatRule implements TestRule { // // @Override // public Statement apply(Statement statement, Description description) { // Statement result = statement; // Repeat repeat = description.getAnnotation(Repeat.class); // if (repeat != null) { // int times = repeat.value(); // result = new RepeatStatement(times, statement); // } // return result; // } // // private static class RepeatStatement extends Statement { // private final int times; // private final Statement statement; // // private RepeatStatement(int times, Statement statement) { // this.times = times; // this.statement = statement; // } // // @Override // public void evaluate() throws Throwable { // for (int i = 0; i < times; i++) { // statement.evaluate(); // } // } // } // } // Path: src/test/java/cpabe/tests/Bsw07Test.java import cpabe.*; import cpabe.policy.Util; import cpabe.tests.rules.Repeat; import cpabe.tests.rules.RepeatRule; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import java.io.ByteArrayInputStream; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Arrays; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; package cpabe.tests; public class Bsw07Test { private static SecureRandom random; @Rule
public RepeatRule repeatRule = new RepeatRule();
jyhehir/mobster
src/main/java/org/umcn/me/util/BAMCollection.java
// Path: src/main/java/org/umcn/me/samexternal/SAMSilentReader.java // public class SAMSilentReader extends SAMFileReader { // // public SAMSilentReader(File samOrBam){ // super(samOrBam); // this.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); // } // // public SAMSilentReader(File bam, File index){ // super(bam, index); // this.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); // } // // }
import java.security.InvalidParameterException; import java.util.List; import java.util.ArrayList; import java.io.File; import java.io.FileNotFoundException; import org.umcn.me.samexternal.SAMSilentReader; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.SAMReadGroupRecord; import net.sf.picard.sam.SamFileHeaderMerger;
package org.umcn.me.util; public class BAMCollection { List<BAMSample> bams = new ArrayList<BAMSample>(); public BAMCollection(String[] files, String[] names) throws InvalidParameterException, FileNotFoundException { this(files, names, false); } public BAMCollection(String[] files, String[] names, boolean prefix) throws InvalidParameterException, FileNotFoundException { if (files.length != names.length){ throw new InvalidParameterException("Number of files does not equal number of sample names"); } for (int i=0; i < files.length; i++){ String fileName = files[i]; File file = new File(fileName); String name = names[i]; if (fileName.isEmpty() || name.isEmpty()){ throw new InvalidParameterException("Name of file or sample may not be empty"); } if (!file.exists()){ throw new FileNotFoundException("File does not exist: " + file); } BAMSample sample = new BAMSample(file, name); if (prefix) sample.setPrefixReadGroupId(Integer.toString(i) + "."); bams.add(sample); } } /** * * @param order * @return SAMFileHeader */ public SAMFileHeader getMergedHeader(SAMFileHeader.SortOrder order) { List<SAMFileHeader> headers = new ArrayList<SAMFileHeader>(); for (BAMSample sample : this.bams){ List<SAMReadGroupRecord> newReadGroups = new ArrayList<SAMReadGroupRecord>();
// Path: src/main/java/org/umcn/me/samexternal/SAMSilentReader.java // public class SAMSilentReader extends SAMFileReader { // // public SAMSilentReader(File samOrBam){ // super(samOrBam); // this.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); // } // // public SAMSilentReader(File bam, File index){ // super(bam, index); // this.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); // } // // } // Path: src/main/java/org/umcn/me/util/BAMCollection.java import java.security.InvalidParameterException; import java.util.List; import java.util.ArrayList; import java.io.File; import java.io.FileNotFoundException; import org.umcn.me.samexternal.SAMSilentReader; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.SAMReadGroupRecord; import net.sf.picard.sam.SamFileHeaderMerger; package org.umcn.me.util; public class BAMCollection { List<BAMSample> bams = new ArrayList<BAMSample>(); public BAMCollection(String[] files, String[] names) throws InvalidParameterException, FileNotFoundException { this(files, names, false); } public BAMCollection(String[] files, String[] names, boolean prefix) throws InvalidParameterException, FileNotFoundException { if (files.length != names.length){ throw new InvalidParameterException("Number of files does not equal number of sample names"); } for (int i=0; i < files.length; i++){ String fileName = files[i]; File file = new File(fileName); String name = names[i]; if (fileName.isEmpty() || name.isEmpty()){ throw new InvalidParameterException("Name of file or sample may not be empty"); } if (!file.exists()){ throw new FileNotFoundException("File does not exist: " + file); } BAMSample sample = new BAMSample(file, name); if (prefix) sample.setPrefixReadGroupId(Integer.toString(i) + "."); bams.add(sample); } } /** * * @param order * @return SAMFileHeader */ public SAMFileHeader getMergedHeader(SAMFileHeader.SortOrder order) { List<SAMFileHeader> headers = new ArrayList<SAMFileHeader>(); for (BAMSample sample : this.bams){ List<SAMReadGroupRecord> newReadGroups = new ArrayList<SAMReadGroupRecord>();
SAMSilentReader reader = new SAMSilentReader(sample.bam);
jyhehir/mobster
src/main/java/org/umcn/me/pairedend/PotentialMEIFinderMain.java
// Path: src/main/java/org/umcn/me/samexternal/SAMDefinitions.java // public class SAMDefinitions { // // public static final String MAPPING_TOOL_BWA = "bwa"; // public static final String MAPPING_TOOL_MOSAIK = "mosaik"; // public static final String MAPPING_TOOL_LIFESCOPE = "lifescope"; // public static final String MAPPING_TOOL_UNSPECIFIED = "unspecified"; // // public static final String[] MAPPING_TOOLS = {MAPPING_TOOL_MOSAIK, MAPPING_TOOL_BWA, MAPPING_TOOL_LIFESCOPE, MAPPING_TOOL_UNSPECIFIED}; // public static final String MOSAIK_MAPPINGINFO_ATTRIBUTE = "ZA"; // public static final String LIFESCOPE_NRHITS_ATTRIBUTE = "NH"; // public static final String BWA_NR_OPTIMAL_HITS_ATTRIBUTE = "X0"; // public static final String BWA_NR_SUBOPTIMAL_HITS_ATTRIBUTE = "X1"; // public static final int MOSAIK_MAPPINGINFO_READ1 = 0; // public static final int MOSAIK_MAPPINGINFO_READ2 = 1; // public static final int MOSAIK_MAPPINGINFO_NRHITS = 4; // public static final String READ_NUMBER_SEPERATOR = "-"; // public static final String UNIQUE_UNIQUE_MAPPING = "UU"; // public static final String UNIQUE_UNMAPPED_MAPPING = "UX"; // public static final String UNIQUE_MULTIPLE_MAPPING = "UM"; // public static final String SPLIT_MAPPING = "S"; // public static final char LEFT_CLIPPED = 'L'; // public static final char RIGHT_CLIPPED = 'R'; // // } // // Path: src/main/java/org/umcn/me/samexternal/UnknownParamException.java // public class UnknownParamException extends Exception { // // private static final long serialVersionUID = 5984202278542517694L; // // public UnknownParamException(String string) { // super(string); // } // }
import java.io.IOException; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.umcn.me.samexternal.SAMDefinitions; import org.umcn.me.samexternal.UnknownParamException;
package org.umcn.me.pairedend; public class PotentialMEIFinderMain { public static Logger logger = Logger.getLogger("PotentialMEIFinderMain"); public static void main(String[] args){ Options options; HelpFormatter formatter = new HelpFormatter(); BasicConfigurator.configure(); PotentialMEIFinder potentialMobileFinder; options = addCmdOptions(); String sep = "/"; String infile; String outfile; String tool; if(args.length == 0){ formatter.printHelp("java -Xmx4g -jar PotentialMEIFinder.jar", options); }else{ CommandLineParser parser = new GnuParser(); try { CommandLine line = parser.parse(options, args); if(line.hasOption("sep")){ sep = line.getOptionValue("sep"); } infile = line.getOptionValue("in"); outfile = line.getOptionValue("out");
// Path: src/main/java/org/umcn/me/samexternal/SAMDefinitions.java // public class SAMDefinitions { // // public static final String MAPPING_TOOL_BWA = "bwa"; // public static final String MAPPING_TOOL_MOSAIK = "mosaik"; // public static final String MAPPING_TOOL_LIFESCOPE = "lifescope"; // public static final String MAPPING_TOOL_UNSPECIFIED = "unspecified"; // // public static final String[] MAPPING_TOOLS = {MAPPING_TOOL_MOSAIK, MAPPING_TOOL_BWA, MAPPING_TOOL_LIFESCOPE, MAPPING_TOOL_UNSPECIFIED}; // public static final String MOSAIK_MAPPINGINFO_ATTRIBUTE = "ZA"; // public static final String LIFESCOPE_NRHITS_ATTRIBUTE = "NH"; // public static final String BWA_NR_OPTIMAL_HITS_ATTRIBUTE = "X0"; // public static final String BWA_NR_SUBOPTIMAL_HITS_ATTRIBUTE = "X1"; // public static final int MOSAIK_MAPPINGINFO_READ1 = 0; // public static final int MOSAIK_MAPPINGINFO_READ2 = 1; // public static final int MOSAIK_MAPPINGINFO_NRHITS = 4; // public static final String READ_NUMBER_SEPERATOR = "-"; // public static final String UNIQUE_UNIQUE_MAPPING = "UU"; // public static final String UNIQUE_UNMAPPED_MAPPING = "UX"; // public static final String UNIQUE_MULTIPLE_MAPPING = "UM"; // public static final String SPLIT_MAPPING = "S"; // public static final char LEFT_CLIPPED = 'L'; // public static final char RIGHT_CLIPPED = 'R'; // // } // // Path: src/main/java/org/umcn/me/samexternal/UnknownParamException.java // public class UnknownParamException extends Exception { // // private static final long serialVersionUID = 5984202278542517694L; // // public UnknownParamException(String string) { // super(string); // } // } // Path: src/main/java/org/umcn/me/pairedend/PotentialMEIFinderMain.java import java.io.IOException; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.umcn.me.samexternal.SAMDefinitions; import org.umcn.me.samexternal.UnknownParamException; package org.umcn.me.pairedend; public class PotentialMEIFinderMain { public static Logger logger = Logger.getLogger("PotentialMEIFinderMain"); public static void main(String[] args){ Options options; HelpFormatter formatter = new HelpFormatter(); BasicConfigurator.configure(); PotentialMEIFinder potentialMobileFinder; options = addCmdOptions(); String sep = "/"; String infile; String outfile; String tool; if(args.length == 0){ formatter.printHelp("java -Xmx4g -jar PotentialMEIFinder.jar", options); }else{ CommandLineParser parser = new GnuParser(); try { CommandLine line = parser.parse(options, args); if(line.hasOption("sep")){ sep = line.getOptionValue("sep"); } infile = line.getOptionValue("in"); outfile = line.getOptionValue("out");
tool = line.getOptionValue("tool", SAMDefinitions.MAPPING_TOOL_MOSAIK);
jyhehir/mobster
src/main/java/org/umcn/me/pairedend/PotentialMEIFinderMain.java
// Path: src/main/java/org/umcn/me/samexternal/SAMDefinitions.java // public class SAMDefinitions { // // public static final String MAPPING_TOOL_BWA = "bwa"; // public static final String MAPPING_TOOL_MOSAIK = "mosaik"; // public static final String MAPPING_TOOL_LIFESCOPE = "lifescope"; // public static final String MAPPING_TOOL_UNSPECIFIED = "unspecified"; // // public static final String[] MAPPING_TOOLS = {MAPPING_TOOL_MOSAIK, MAPPING_TOOL_BWA, MAPPING_TOOL_LIFESCOPE, MAPPING_TOOL_UNSPECIFIED}; // public static final String MOSAIK_MAPPINGINFO_ATTRIBUTE = "ZA"; // public static final String LIFESCOPE_NRHITS_ATTRIBUTE = "NH"; // public static final String BWA_NR_OPTIMAL_HITS_ATTRIBUTE = "X0"; // public static final String BWA_NR_SUBOPTIMAL_HITS_ATTRIBUTE = "X1"; // public static final int MOSAIK_MAPPINGINFO_READ1 = 0; // public static final int MOSAIK_MAPPINGINFO_READ2 = 1; // public static final int MOSAIK_MAPPINGINFO_NRHITS = 4; // public static final String READ_NUMBER_SEPERATOR = "-"; // public static final String UNIQUE_UNIQUE_MAPPING = "UU"; // public static final String UNIQUE_UNMAPPED_MAPPING = "UX"; // public static final String UNIQUE_MULTIPLE_MAPPING = "UM"; // public static final String SPLIT_MAPPING = "S"; // public static final char LEFT_CLIPPED = 'L'; // public static final char RIGHT_CLIPPED = 'R'; // // } // // Path: src/main/java/org/umcn/me/samexternal/UnknownParamException.java // public class UnknownParamException extends Exception { // // private static final long serialVersionUID = 5984202278542517694L; // // public UnknownParamException(String string) { // super(string); // } // }
import java.io.IOException; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.umcn.me.samexternal.SAMDefinitions; import org.umcn.me.samexternal.UnknownParamException;
String tool; if(args.length == 0){ formatter.printHelp("java -Xmx4g -jar PotentialMEIFinder.jar", options); }else{ CommandLineParser parser = new GnuParser(); try { CommandLine line = parser.parse(options, args); if(line.hasOption("sep")){ sep = line.getOptionValue("sep"); } infile = line.getOptionValue("in"); outfile = line.getOptionValue("out"); tool = line.getOptionValue("tool", SAMDefinitions.MAPPING_TOOL_MOSAIK); logger.info("Running PotentialMEIFinder with follow settings:"); logger.info("in: " + infile); logger.info("out: " + outfile); logger.info("sep: " + sep); logger.info("used mapping tool: " + tool); potentialMobileFinder = new PotentialMEIFinder(sep, infile, outfile, tool); potentialMobileFinder.extractPotentialMobileReads(); } catch (ParseException e) { logger.error("Error in parsing CLI arguments: " + e.getMessage()); } catch (IOException e){ logger.error("IO error: " + e.getMessage());
// Path: src/main/java/org/umcn/me/samexternal/SAMDefinitions.java // public class SAMDefinitions { // // public static final String MAPPING_TOOL_BWA = "bwa"; // public static final String MAPPING_TOOL_MOSAIK = "mosaik"; // public static final String MAPPING_TOOL_LIFESCOPE = "lifescope"; // public static final String MAPPING_TOOL_UNSPECIFIED = "unspecified"; // // public static final String[] MAPPING_TOOLS = {MAPPING_TOOL_MOSAIK, MAPPING_TOOL_BWA, MAPPING_TOOL_LIFESCOPE, MAPPING_TOOL_UNSPECIFIED}; // public static final String MOSAIK_MAPPINGINFO_ATTRIBUTE = "ZA"; // public static final String LIFESCOPE_NRHITS_ATTRIBUTE = "NH"; // public static final String BWA_NR_OPTIMAL_HITS_ATTRIBUTE = "X0"; // public static final String BWA_NR_SUBOPTIMAL_HITS_ATTRIBUTE = "X1"; // public static final int MOSAIK_MAPPINGINFO_READ1 = 0; // public static final int MOSAIK_MAPPINGINFO_READ2 = 1; // public static final int MOSAIK_MAPPINGINFO_NRHITS = 4; // public static final String READ_NUMBER_SEPERATOR = "-"; // public static final String UNIQUE_UNIQUE_MAPPING = "UU"; // public static final String UNIQUE_UNMAPPED_MAPPING = "UX"; // public static final String UNIQUE_MULTIPLE_MAPPING = "UM"; // public static final String SPLIT_MAPPING = "S"; // public static final char LEFT_CLIPPED = 'L'; // public static final char RIGHT_CLIPPED = 'R'; // // } // // Path: src/main/java/org/umcn/me/samexternal/UnknownParamException.java // public class UnknownParamException extends Exception { // // private static final long serialVersionUID = 5984202278542517694L; // // public UnknownParamException(String string) { // super(string); // } // } // Path: src/main/java/org/umcn/me/pairedend/PotentialMEIFinderMain.java import java.io.IOException; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.umcn.me.samexternal.SAMDefinitions; import org.umcn.me.samexternal.UnknownParamException; String tool; if(args.length == 0){ formatter.printHelp("java -Xmx4g -jar PotentialMEIFinder.jar", options); }else{ CommandLineParser parser = new GnuParser(); try { CommandLine line = parser.parse(options, args); if(line.hasOption("sep")){ sep = line.getOptionValue("sep"); } infile = line.getOptionValue("in"); outfile = line.getOptionValue("out"); tool = line.getOptionValue("tool", SAMDefinitions.MAPPING_TOOL_MOSAIK); logger.info("Running PotentialMEIFinder with follow settings:"); logger.info("in: " + infile); logger.info("out: " + outfile); logger.info("sep: " + sep); logger.info("used mapping tool: " + tool); potentialMobileFinder = new PotentialMEIFinder(sep, infile, outfile, tool); potentialMobileFinder.extractPotentialMobileReads(); } catch (ParseException e) { logger.error("Error in parsing CLI arguments: " + e.getMessage()); } catch (IOException e){ logger.error("IO error: " + e.getMessage());
} catch (UnknownParamException e){
jyhehir/mobster
src/test/java/org/umcn/me/sam/MateClusterTest.java
// Path: src/main/java/org/umcn/me/samexternal/SAMSilentReader.java // public class SAMSilentReader extends SAMFileReader { // // public SAMSilentReader(File samOrBam){ // super(samOrBam); // this.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); // } // // public SAMSilentReader(File bam, File index){ // super(bam, index); // this.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); // } // // } // // Path: src/main/java/org/umcn/me/util/SampleBam.java // public enum SampleBam { // SINGLESAMPLE, MULTISAMPLE; // }
import java.io.File; import java.util.Iterator; import java.util.Locale; import java.util.Vector; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.SAMFileReader; import net.sf.samtools.SAMRecord; import org.umcn.me.samexternal.SAMSilentReader; import org.umcn.me.util.SampleBam; import junit.framework.TestCase;
package org.umcn.me.sam; public class MateClusterTest extends TestCase { private File anchorFile = new File(this.getClass().getResource("/test_data/A105a_PPIA.sam").getFile()); public void testGetNumberOfDifferentMateMappings(){ //This cluster has mappings to 3 different chromosomes MateCluster<SAMRecord> clusterToTest1 = this.anchorsToClusters().get(0); //This cluster has mappings to 1 chromosome, but also has an unmapped anchor. MateCluster<SAMRecord> clusterToTest2 = this.anchorsToClusters().get(2); //This cluster has mappings to 3 different chromosomes + a couple of unmapped anchors MateCluster<SAMRecord> clusterToTest3 = this.anchorsToClusters().get(3); assertEquals(3, clusterToTest1.getNumberOfDifferentChromosomeMappingsOfMates(true)); assertEquals(1, clusterToTest2.getNumberOfDifferentChromosomeMappingsOfMates(true)); assertEquals(2, clusterToTest2.getNumberOfDifferentChromosomeMappingsOfMates(false)); //also count the unmapped category assertEquals(3, clusterToTest3.getNumberOfDifferentChromosomeMappingsOfMates(true)); assertEquals(4, clusterToTest3.getNumberOfDifferentChromosomeMappingsOfMates(false)); } public void testGettingMaxPercentageToSameChromosome(){ MateCluster<SAMRecord> clusterToTest = this.anchorsToClusters().get(0); MateCluster<SAMRecord> clusterToTest3 = this.anchorsToClusters().get(3); assertEquals("55.56", String.format(Locale.ENGLISH, "%.2f", clusterToTest.getHighestPercentageOfMateAlignmentsToSameChrosome(true))); assertEquals(50.0, clusterToTest3.getHighestPercentageOfMateAlignmentsToSameChrosome(true)); assertEquals(6.0 / 17 * 100, clusterToTest3.getHighestPercentageOfMateAlignmentsToSameChrosome(false)); } private Vector<MateCluster<SAMRecord>> anchorsToClusters(){
// Path: src/main/java/org/umcn/me/samexternal/SAMSilentReader.java // public class SAMSilentReader extends SAMFileReader { // // public SAMSilentReader(File samOrBam){ // super(samOrBam); // this.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); // } // // public SAMSilentReader(File bam, File index){ // super(bam, index); // this.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); // } // // } // // Path: src/main/java/org/umcn/me/util/SampleBam.java // public enum SampleBam { // SINGLESAMPLE, MULTISAMPLE; // } // Path: src/test/java/org/umcn/me/sam/MateClusterTest.java import java.io.File; import java.util.Iterator; import java.util.Locale; import java.util.Vector; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.SAMFileReader; import net.sf.samtools.SAMRecord; import org.umcn.me.samexternal.SAMSilentReader; import org.umcn.me.util.SampleBam; import junit.framework.TestCase; package org.umcn.me.sam; public class MateClusterTest extends TestCase { private File anchorFile = new File(this.getClass().getResource("/test_data/A105a_PPIA.sam").getFile()); public void testGetNumberOfDifferentMateMappings(){ //This cluster has mappings to 3 different chromosomes MateCluster<SAMRecord> clusterToTest1 = this.anchorsToClusters().get(0); //This cluster has mappings to 1 chromosome, but also has an unmapped anchor. MateCluster<SAMRecord> clusterToTest2 = this.anchorsToClusters().get(2); //This cluster has mappings to 3 different chromosomes + a couple of unmapped anchors MateCluster<SAMRecord> clusterToTest3 = this.anchorsToClusters().get(3); assertEquals(3, clusterToTest1.getNumberOfDifferentChromosomeMappingsOfMates(true)); assertEquals(1, clusterToTest2.getNumberOfDifferentChromosomeMappingsOfMates(true)); assertEquals(2, clusterToTest2.getNumberOfDifferentChromosomeMappingsOfMates(false)); //also count the unmapped category assertEquals(3, clusterToTest3.getNumberOfDifferentChromosomeMappingsOfMates(true)); assertEquals(4, clusterToTest3.getNumberOfDifferentChromosomeMappingsOfMates(false)); } public void testGettingMaxPercentageToSameChromosome(){ MateCluster<SAMRecord> clusterToTest = this.anchorsToClusters().get(0); MateCluster<SAMRecord> clusterToTest3 = this.anchorsToClusters().get(3); assertEquals("55.56", String.format(Locale.ENGLISH, "%.2f", clusterToTest.getHighestPercentageOfMateAlignmentsToSameChrosome(true))); assertEquals(50.0, clusterToTest3.getHighestPercentageOfMateAlignmentsToSameChrosome(true)); assertEquals(6.0 / 17 * 100, clusterToTest3.getHighestPercentageOfMateAlignmentsToSameChrosome(false)); } private Vector<MateCluster<SAMRecord>> anchorsToClusters(){
SAMFileReader input = new SAMSilentReader(this.anchorFile);
jyhehir/mobster
src/test/java/org/umcn/me/sam/MateClusterTest.java
// Path: src/main/java/org/umcn/me/samexternal/SAMSilentReader.java // public class SAMSilentReader extends SAMFileReader { // // public SAMSilentReader(File samOrBam){ // super(samOrBam); // this.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); // } // // public SAMSilentReader(File bam, File index){ // super(bam, index); // this.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); // } // // } // // Path: src/main/java/org/umcn/me/util/SampleBam.java // public enum SampleBam { // SINGLESAMPLE, MULTISAMPLE; // }
import java.io.File; import java.util.Iterator; import java.util.Locale; import java.util.Vector; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.SAMFileReader; import net.sf.samtools.SAMRecord; import org.umcn.me.samexternal.SAMSilentReader; import org.umcn.me.util.SampleBam; import junit.framework.TestCase;
package org.umcn.me.sam; public class MateClusterTest extends TestCase { private File anchorFile = new File(this.getClass().getResource("/test_data/A105a_PPIA.sam").getFile()); public void testGetNumberOfDifferentMateMappings(){ //This cluster has mappings to 3 different chromosomes MateCluster<SAMRecord> clusterToTest1 = this.anchorsToClusters().get(0); //This cluster has mappings to 1 chromosome, but also has an unmapped anchor. MateCluster<SAMRecord> clusterToTest2 = this.anchorsToClusters().get(2); //This cluster has mappings to 3 different chromosomes + a couple of unmapped anchors MateCluster<SAMRecord> clusterToTest3 = this.anchorsToClusters().get(3); assertEquals(3, clusterToTest1.getNumberOfDifferentChromosomeMappingsOfMates(true)); assertEquals(1, clusterToTest2.getNumberOfDifferentChromosomeMappingsOfMates(true)); assertEquals(2, clusterToTest2.getNumberOfDifferentChromosomeMappingsOfMates(false)); //also count the unmapped category assertEquals(3, clusterToTest3.getNumberOfDifferentChromosomeMappingsOfMates(true)); assertEquals(4, clusterToTest3.getNumberOfDifferentChromosomeMappingsOfMates(false)); } public void testGettingMaxPercentageToSameChromosome(){ MateCluster<SAMRecord> clusterToTest = this.anchorsToClusters().get(0); MateCluster<SAMRecord> clusterToTest3 = this.anchorsToClusters().get(3); assertEquals("55.56", String.format(Locale.ENGLISH, "%.2f", clusterToTest.getHighestPercentageOfMateAlignmentsToSameChrosome(true))); assertEquals(50.0, clusterToTest3.getHighestPercentageOfMateAlignmentsToSameChrosome(true)); assertEquals(6.0 / 17 * 100, clusterToTest3.getHighestPercentageOfMateAlignmentsToSameChrosome(false)); } private Vector<MateCluster<SAMRecord>> anchorsToClusters(){ SAMFileReader input = new SAMSilentReader(this.anchorFile); SAMFileHeader header = input.getFileHeader();
// Path: src/main/java/org/umcn/me/samexternal/SAMSilentReader.java // public class SAMSilentReader extends SAMFileReader { // // public SAMSilentReader(File samOrBam){ // super(samOrBam); // this.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); // } // // public SAMSilentReader(File bam, File index){ // super(bam, index); // this.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); // } // // } // // Path: src/main/java/org/umcn/me/util/SampleBam.java // public enum SampleBam { // SINGLESAMPLE, MULTISAMPLE; // } // Path: src/test/java/org/umcn/me/sam/MateClusterTest.java import java.io.File; import java.util.Iterator; import java.util.Locale; import java.util.Vector; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.SAMFileReader; import net.sf.samtools.SAMRecord; import org.umcn.me.samexternal.SAMSilentReader; import org.umcn.me.util.SampleBam; import junit.framework.TestCase; package org.umcn.me.sam; public class MateClusterTest extends TestCase { private File anchorFile = new File(this.getClass().getResource("/test_data/A105a_PPIA.sam").getFile()); public void testGetNumberOfDifferentMateMappings(){ //This cluster has mappings to 3 different chromosomes MateCluster<SAMRecord> clusterToTest1 = this.anchorsToClusters().get(0); //This cluster has mappings to 1 chromosome, but also has an unmapped anchor. MateCluster<SAMRecord> clusterToTest2 = this.anchorsToClusters().get(2); //This cluster has mappings to 3 different chromosomes + a couple of unmapped anchors MateCluster<SAMRecord> clusterToTest3 = this.anchorsToClusters().get(3); assertEquals(3, clusterToTest1.getNumberOfDifferentChromosomeMappingsOfMates(true)); assertEquals(1, clusterToTest2.getNumberOfDifferentChromosomeMappingsOfMates(true)); assertEquals(2, clusterToTest2.getNumberOfDifferentChromosomeMappingsOfMates(false)); //also count the unmapped category assertEquals(3, clusterToTest3.getNumberOfDifferentChromosomeMappingsOfMates(true)); assertEquals(4, clusterToTest3.getNumberOfDifferentChromosomeMappingsOfMates(false)); } public void testGettingMaxPercentageToSameChromosome(){ MateCluster<SAMRecord> clusterToTest = this.anchorsToClusters().get(0); MateCluster<SAMRecord> clusterToTest3 = this.anchorsToClusters().get(3); assertEquals("55.56", String.format(Locale.ENGLISH, "%.2f", clusterToTest.getHighestPercentageOfMateAlignmentsToSameChrosome(true))); assertEquals(50.0, clusterToTest3.getHighestPercentageOfMateAlignmentsToSameChrosome(true)); assertEquals(6.0 / 17 * 100, clusterToTest3.getHighestPercentageOfMateAlignmentsToSameChrosome(false)); } private Vector<MateCluster<SAMRecord>> anchorsToClusters(){ SAMFileReader input = new SAMSilentReader(this.anchorFile); SAMFileHeader header = input.getFileHeader();
SampleBam sampleCalling = SampleBam.SINGLESAMPLE;
jyhehir/mobster
src/main/java/org/umcn/me/util/AddSampleNameToBAM.java
// Path: src/main/java/org/umcn/me/samexternal/SAMSilentReader.java // public class SAMSilentReader extends SAMFileReader { // // public SAMSilentReader(File samOrBam){ // super(samOrBam); // this.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); // } // // public SAMSilentReader(File bam, File index){ // super(bam, index); // this.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); // } // // }
import java.io.File; import net.sf.samtools.SAMFileReader; import net.sf.samtools.SAMFileWriter; import net.sf.samtools.SAMFileWriterFactory; import net.sf.samtools.SAMRecord; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.umcn.me.samexternal.SAMSilentReader;
package org.umcn.me.util; public class AddSampleNameToBAM { public static void main(String[] args) { HelpFormatter formatter = new HelpFormatter(); Options options = createOptions(); String inFile; String outFile; String sample; if(args.length == 0){ formatter.printHelp("java -Xmx4g -jar AddSampleNameToBAM.jar" , options); }else{ CommandLineParser parser = new GnuParser(); try { CommandLine line = parser.parse(options, args); inFile = line.getOptionValue("in"); sample = line.getOptionValue("sn"); outFile = line.getOptionValue("out"); addSampleNameToRecords(inFile, outFile, sample); } catch (ParseException e) { e.printStackTrace(); } } } public static void addSampleNameToRecords(String in, String out, String sample){
// Path: src/main/java/org/umcn/me/samexternal/SAMSilentReader.java // public class SAMSilentReader extends SAMFileReader { // // public SAMSilentReader(File samOrBam){ // super(samOrBam); // this.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); // } // // public SAMSilentReader(File bam, File index){ // super(bam, index); // this.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); // } // // } // Path: src/main/java/org/umcn/me/util/AddSampleNameToBAM.java import java.io.File; import net.sf.samtools.SAMFileReader; import net.sf.samtools.SAMFileWriter; import net.sf.samtools.SAMFileWriterFactory; import net.sf.samtools.SAMRecord; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.umcn.me.samexternal.SAMSilentReader; package org.umcn.me.util; public class AddSampleNameToBAM { public static void main(String[] args) { HelpFormatter formatter = new HelpFormatter(); Options options = createOptions(); String inFile; String outFile; String sample; if(args.length == 0){ formatter.printHelp("java -Xmx4g -jar AddSampleNameToBAM.jar" , options); }else{ CommandLineParser parser = new GnuParser(); try { CommandLine line = parser.parse(options, args); inFile = line.getOptionValue("in"); sample = line.getOptionValue("sn"); outFile = line.getOptionValue("out"); addSampleNameToRecords(inFile, outFile, sample); } catch (ParseException e) { e.printStackTrace(); } } } public static void addSampleNameToRecords(String in, String out, String sample){
SAMFileReader reader = new SAMSilentReader(new File(in));
jyhehir/mobster
src/test/java/org/umcn/me/pairedend/SplitClustersInMateClustersTest.java
// Path: src/main/java/org/umcn/me/samexternal/IllegalSAMPairException.java // public class IllegalSAMPairException extends Exception { // // private static final long serialVersionUID = 7638684570930945256L; // // public IllegalSAMPairException(String error){ // super(error); // } // // }
import java.io.File; import java.io.IOException; import java.util.Vector; import org.umcn.me.samexternal.IllegalSAMPairException;
package org.umcn.me.pairedend; public class SplitClustersInMateClustersTest { public static void main(String[] args){ File clusterIn = new File("D:/bams/test/YESSPLIT_r90/ClusterRefacV4_0.1mmYESSplitBWA_clusters_sorted.bam"); File clusterIndex = new File("D:/bams/test/YESSPLIT_r90/ClusterRefacV4_0.1mmYESSplitBWA_clusters_sorted.bam.bai"); File splitCluster = new File("D:/bams/test/YESSPLIT_r90/ClusterRefacV4_0.1mmYESSplitBWA_splitclustersV2sort.bam"); File splitClusterIn = new File("D:/bams/test/YESSPLIT_r90/ClusterRefacV4_0.1mmYESSplitBWA_splitclustersV2sort.bam.bai"); try { Vector<MobilePrediction> predictions = AnchorClusterer.clusterMateClusters(clusterIn, clusterIndex, 50, 700); predictions = AnchorClusterer.mergeSplitAndMateClusters(predictions, splitCluster, splitClusterIn); predictions = AnchorClusterer.filterKnownMEs(AnchorClusterer.getKnownMEs(), predictions); AnchorClusterer.writePredictionsToFile("D:/ClusterRefacV4_0.1mmpSoloSplitSwitchLandRYESSplitBWA_splitmerged.txt", predictions, "#testcomment\n", "testsample"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace();
// Path: src/main/java/org/umcn/me/samexternal/IllegalSAMPairException.java // public class IllegalSAMPairException extends Exception { // // private static final long serialVersionUID = 7638684570930945256L; // // public IllegalSAMPairException(String error){ // super(error); // } // // } // Path: src/test/java/org/umcn/me/pairedend/SplitClustersInMateClustersTest.java import java.io.File; import java.io.IOException; import java.util.Vector; import org.umcn.me.samexternal.IllegalSAMPairException; package org.umcn.me.pairedend; public class SplitClustersInMateClustersTest { public static void main(String[] args){ File clusterIn = new File("D:/bams/test/YESSPLIT_r90/ClusterRefacV4_0.1mmYESSplitBWA_clusters_sorted.bam"); File clusterIndex = new File("D:/bams/test/YESSPLIT_r90/ClusterRefacV4_0.1mmYESSplitBWA_clusters_sorted.bam.bai"); File splitCluster = new File("D:/bams/test/YESSPLIT_r90/ClusterRefacV4_0.1mmYESSplitBWA_splitclustersV2sort.bam"); File splitClusterIn = new File("D:/bams/test/YESSPLIT_r90/ClusterRefacV4_0.1mmYESSplitBWA_splitclustersV2sort.bam.bai"); try { Vector<MobilePrediction> predictions = AnchorClusterer.clusterMateClusters(clusterIn, clusterIndex, 50, 700); predictions = AnchorClusterer.mergeSplitAndMateClusters(predictions, splitCluster, splitClusterIn); predictions = AnchorClusterer.filterKnownMEs(AnchorClusterer.getKnownMEs(), predictions); AnchorClusterer.writePredictionsToFile("D:/ClusterRefacV4_0.1mmpSoloSplitSwitchLandRYESSplitBWA_splitmerged.txt", predictions, "#testcomment\n", "testsample"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace();
} catch (IllegalSAMPairException e) {
jyhehir/mobster
src/main/java/org/umcn/me/pairedend/OnlySplitClusterToPred.java
// Path: src/main/java/org/umcn/me/samexternal/IllegalSAMPairException.java // public class IllegalSAMPairException extends Exception { // // private static final long serialVersionUID = 7638684570930945256L; // // public IllegalSAMPairException(String error){ // super(error); // } // // }
import java.io.File; import java.io.IOException; import java.util.Vector; import org.umcn.me.samexternal.IllegalSAMPairException; import net.sf.samtools.SAMFileReader; import net.sf.samtools.SAMRecord;
package org.umcn.me.pairedend; public class OnlySplitClusterToPred { public static void main(String[] args){ SAMFileReader inBAM = new SAMFileReader(new File("C:/bams/BWA/YESSPLIT_r90/ClusterRefacV4_0.1mmYESSplitBWA_splitclustersV2.bam")); Vector<MobilePrediction> predictions = new Vector<MobilePrediction>(); for (SAMRecord record : inBAM){ try { MobilePrediction prediction = new MobilePrediction(468, 34, 500, record); if (prediction.getLeftTotalHits() + prediction.getRightTotalHits() >= 2){ predictions.add(prediction); }
// Path: src/main/java/org/umcn/me/samexternal/IllegalSAMPairException.java // public class IllegalSAMPairException extends Exception { // // private static final long serialVersionUID = 7638684570930945256L; // // public IllegalSAMPairException(String error){ // super(error); // } // // } // Path: src/main/java/org/umcn/me/pairedend/OnlySplitClusterToPred.java import java.io.File; import java.io.IOException; import java.util.Vector; import org.umcn.me.samexternal.IllegalSAMPairException; import net.sf.samtools.SAMFileReader; import net.sf.samtools.SAMRecord; package org.umcn.me.pairedend; public class OnlySplitClusterToPred { public static void main(String[] args){ SAMFileReader inBAM = new SAMFileReader(new File("C:/bams/BWA/YESSPLIT_r90/ClusterRefacV4_0.1mmYESSplitBWA_splitclustersV2.bam")); Vector<MobilePrediction> predictions = new Vector<MobilePrediction>(); for (SAMRecord record : inBAM){ try { MobilePrediction prediction = new MobilePrediction(468, 34, 500, record); if (prediction.getLeftTotalHits() + prediction.getRightTotalHits() >= 2){ predictions.add(prediction); }
} catch (IllegalSAMPairException e) {
jyhehir/mobster
src/main/java/org/umcn/me/samexternal/NrMappingsSAMRecordHolder.java
// Path: src/main/java/org/umcn/me/parsers/FastqParser.java // public class FastqParser { // // public static Logger logger = Logger.getLogger("FastaParserFast"); // // // //TODO: check whether qual string is a legal qual string // public static void writeFastQToStream(PrintWriter outFile, String id, // String seq, String qual){ // // StringBuilder readId = new StringBuilder(); // // if (!readId.toString().startsWith("@")){ // readId.append("@"); // } // // readId.append(id); // // outFile.println(readId.toString()); // outFile.println(seq); // outFile.println("+"); // outFile.println(qual); // // } // // public static void writeFastQToStream(PrintWriter outFile, SAMRecord rec, boolean reReverse){ // final String pairDelim = "/"; //default Illumina seperator // StringBuilder readId; // String sequence = rec.getReadString(); // String baseQuals = rec.getBaseQualityString(); // // //make reverse complement of sequence if mapped on negative strand, to get to original fastq record // if (reReverse && rec.getReadNegativeStrandFlag()){ // sequence = SequenceUtil.reverseComplement(sequence); // baseQuals = StringUtil.reverseString(baseQuals); // } // // if(!rec.getReadPairedFlag()){ // FastqParser.writeFastQToStream(outFile, rec.getReadName(), sequence, baseQuals); // }else{ // readId = new StringBuilder(rec.getReadName()); // readId.append(pairDelim); // if(rec.getFirstOfPairFlag()){ // readId.append("1"); // }else{ // readId.append("2"); // } // FastqParser.writeFastQToStream(outFile, readId.toString(), sequence, baseQuals); // } // // } // }
import java.io.PrintWriter; import org.umcn.me.parsers.FastqParser; import net.sf.samtools.SAMRecord;
package org.umcn.me.samexternal; /** * @author Djie */ public abstract class NrMappingsSAMRecordHolder extends SpecificSAMRecordHolder implements MappingCountable { protected int min_clipping = 1; protected int max_clipping = 100; protected int min_avg_qual = 20; public NrMappingsSAMRecordHolder(SAMRecord samRecord){ super(samRecord); } public NrMappingsSAMRecordHolder(SAMRecord samRecord, int minClipping, int maxClipping){ this(samRecord); this.min_clipping = minClipping; this.max_clipping = maxClipping; } public void writeSAMRecordToFastQPrintWriter(PrintWriter outFq, boolean appendReadNumber, boolean includeSplit){ StringBuilder readName = new StringBuilder(this.sam_record.getReadName()); String sequence; String qualityString; if(includeSplit && this.isSoftClippedMappedProperAndCertainSizeAndCertainQual()){ sequence = this.getLargestClippedSeq(); qualityString = this.getLargestClippedQual(); }else{ sequence = this.sam_record.getReadString(); qualityString = this.sam_record.getBaseQualityString(); } if(appendReadNumber && this.sam_record.getReadPairedFlag()){ readName.append(getReadNumber()); }
// Path: src/main/java/org/umcn/me/parsers/FastqParser.java // public class FastqParser { // // public static Logger logger = Logger.getLogger("FastaParserFast"); // // // //TODO: check whether qual string is a legal qual string // public static void writeFastQToStream(PrintWriter outFile, String id, // String seq, String qual){ // // StringBuilder readId = new StringBuilder(); // // if (!readId.toString().startsWith("@")){ // readId.append("@"); // } // // readId.append(id); // // outFile.println(readId.toString()); // outFile.println(seq); // outFile.println("+"); // outFile.println(qual); // // } // // public static void writeFastQToStream(PrintWriter outFile, SAMRecord rec, boolean reReverse){ // final String pairDelim = "/"; //default Illumina seperator // StringBuilder readId; // String sequence = rec.getReadString(); // String baseQuals = rec.getBaseQualityString(); // // //make reverse complement of sequence if mapped on negative strand, to get to original fastq record // if (reReverse && rec.getReadNegativeStrandFlag()){ // sequence = SequenceUtil.reverseComplement(sequence); // baseQuals = StringUtil.reverseString(baseQuals); // } // // if(!rec.getReadPairedFlag()){ // FastqParser.writeFastQToStream(outFile, rec.getReadName(), sequence, baseQuals); // }else{ // readId = new StringBuilder(rec.getReadName()); // readId.append(pairDelim); // if(rec.getFirstOfPairFlag()){ // readId.append("1"); // }else{ // readId.append("2"); // } // FastqParser.writeFastQToStream(outFile, readId.toString(), sequence, baseQuals); // } // // } // } // Path: src/main/java/org/umcn/me/samexternal/NrMappingsSAMRecordHolder.java import java.io.PrintWriter; import org.umcn.me.parsers.FastqParser; import net.sf.samtools.SAMRecord; package org.umcn.me.samexternal; /** * @author Djie */ public abstract class NrMappingsSAMRecordHolder extends SpecificSAMRecordHolder implements MappingCountable { protected int min_clipping = 1; protected int max_clipping = 100; protected int min_avg_qual = 20; public NrMappingsSAMRecordHolder(SAMRecord samRecord){ super(samRecord); } public NrMappingsSAMRecordHolder(SAMRecord samRecord, int minClipping, int maxClipping){ this(samRecord); this.min_clipping = minClipping; this.max_clipping = maxClipping; } public void writeSAMRecordToFastQPrintWriter(PrintWriter outFq, boolean appendReadNumber, boolean includeSplit){ StringBuilder readName = new StringBuilder(this.sam_record.getReadName()); String sequence; String qualityString; if(includeSplit && this.isSoftClippedMappedProperAndCertainSizeAndCertainQual()){ sequence = this.getLargestClippedSeq(); qualityString = this.getLargestClippedQual(); }else{ sequence = this.sam_record.getReadString(); qualityString = this.sam_record.getBaseQualityString(); } if(appendReadNumber && this.sam_record.getReadPairedFlag()){ readName.append(getReadNumber()); }
FastqParser.writeFastQToStream(outFq, readName.toString(), sequence, qualityString);
jyhehir/mobster
src/main/java/org/umcn/me/pairedend/PotentialMEIFinder.java
// Path: src/main/java/org/umcn/me/parsers/FastqParser.java // public class FastqParser { // // public static Logger logger = Logger.getLogger("FastaParserFast"); // // // //TODO: check whether qual string is a legal qual string // public static void writeFastQToStream(PrintWriter outFile, String id, // String seq, String qual){ // // StringBuilder readId = new StringBuilder(); // // if (!readId.toString().startsWith("@")){ // readId.append("@"); // } // // readId.append(id); // // outFile.println(readId.toString()); // outFile.println(seq); // outFile.println("+"); // outFile.println(qual); // // } // // public static void writeFastQToStream(PrintWriter outFile, SAMRecord rec, boolean reReverse){ // final String pairDelim = "/"; //default Illumina seperator // StringBuilder readId; // String sequence = rec.getReadString(); // String baseQuals = rec.getBaseQualityString(); // // //make reverse complement of sequence if mapped on negative strand, to get to original fastq record // if (reReverse && rec.getReadNegativeStrandFlag()){ // sequence = SequenceUtil.reverseComplement(sequence); // baseQuals = StringUtil.reverseString(baseQuals); // } // // if(!rec.getReadPairedFlag()){ // FastqParser.writeFastQToStream(outFile, rec.getReadName(), sequence, baseQuals); // }else{ // readId = new StringBuilder(rec.getReadName()); // readId.append(pairDelim); // if(rec.getFirstOfPairFlag()){ // readId.append("1"); // }else{ // readId.append("2"); // } // FastqParser.writeFastQToStream(outFile, readId.toString(), sequence, baseQuals); // } // // } // } // // Path: src/main/java/org/umcn/me/samexternal/SAMDefinitions.java // public class SAMDefinitions { // // public static final String MAPPING_TOOL_BWA = "bwa"; // public static final String MAPPING_TOOL_MOSAIK = "mosaik"; // public static final String MAPPING_TOOL_LIFESCOPE = "lifescope"; // public static final String MAPPING_TOOL_UNSPECIFIED = "unspecified"; // // public static final String[] MAPPING_TOOLS = {MAPPING_TOOL_MOSAIK, MAPPING_TOOL_BWA, MAPPING_TOOL_LIFESCOPE, MAPPING_TOOL_UNSPECIFIED}; // public static final String MOSAIK_MAPPINGINFO_ATTRIBUTE = "ZA"; // public static final String LIFESCOPE_NRHITS_ATTRIBUTE = "NH"; // public static final String BWA_NR_OPTIMAL_HITS_ATTRIBUTE = "X0"; // public static final String BWA_NR_SUBOPTIMAL_HITS_ATTRIBUTE = "X1"; // public static final int MOSAIK_MAPPINGINFO_READ1 = 0; // public static final int MOSAIK_MAPPINGINFO_READ2 = 1; // public static final int MOSAIK_MAPPINGINFO_NRHITS = 4; // public static final String READ_NUMBER_SEPERATOR = "-"; // public static final String UNIQUE_UNIQUE_MAPPING = "UU"; // public static final String UNIQUE_UNMAPPED_MAPPING = "UX"; // public static final String UNIQUE_MULTIPLE_MAPPING = "UM"; // public static final String SPLIT_MAPPING = "S"; // public static final char LEFT_CLIPPED = 'L'; // public static final char RIGHT_CLIPPED = 'R'; // // } // // Path: src/main/java/org/umcn/me/samexternal/UnknownParamException.java // public class UnknownParamException extends Exception { // // private static final long serialVersionUID = 5984202278542517694L; // // public UnknownParamException(String string) { // super(string); // } // }
import net.sf.samtools.*; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import java.io.*; import java.util.*; import org.umcn.me.parsers.FastqParser; import org.umcn.me.samexternal.SAMDefinitions; import org.umcn.me.samexternal.UnknownParamException;
package org.umcn.me.pairedend; /** * This class is used to find read pairs that could potentially indicate * a MEI event: * - Read pairs which map for one end uniquely to the genome and for * the other end multiple times to the genome; but only when * the reads are not properly paired**. * - Read pairs which map for for one end uniquely to the genome and * for the other end 0 times to the genome (orphans). * - Read pairs which map for both ends uniquely to genome but * are not properly paired**. * * **unproperly paired: * - both reads map on + strand * - both reads map on - strand * - read mapping on + strand has higher genomic coordinate * than read mapping on - strand * - proper FR orientation but insert size not in * mean fragment size +/- local search * * All potential MEI supporting read pairs are written to a bam file. * All reads in a read pair which may potentially map (orphans, multiple mappings, * unproper pairs for unique-unique pairs) to mobile references * are written to seperate fq files. * @author Djie * */ public class PotentialMEIFinder { public static Logger logger = Logger.getLogger("PotentialMEIFinder"); private String pair_number_seperator; private String mapping_tool; private String output_prefix; private String bam_mapped_to_ref; public PotentialMEIFinder(String pairNumberSeperator, String inBam, String outPrefix,
// Path: src/main/java/org/umcn/me/parsers/FastqParser.java // public class FastqParser { // // public static Logger logger = Logger.getLogger("FastaParserFast"); // // // //TODO: check whether qual string is a legal qual string // public static void writeFastQToStream(PrintWriter outFile, String id, // String seq, String qual){ // // StringBuilder readId = new StringBuilder(); // // if (!readId.toString().startsWith("@")){ // readId.append("@"); // } // // readId.append(id); // // outFile.println(readId.toString()); // outFile.println(seq); // outFile.println("+"); // outFile.println(qual); // // } // // public static void writeFastQToStream(PrintWriter outFile, SAMRecord rec, boolean reReverse){ // final String pairDelim = "/"; //default Illumina seperator // StringBuilder readId; // String sequence = rec.getReadString(); // String baseQuals = rec.getBaseQualityString(); // // //make reverse complement of sequence if mapped on negative strand, to get to original fastq record // if (reReverse && rec.getReadNegativeStrandFlag()){ // sequence = SequenceUtil.reverseComplement(sequence); // baseQuals = StringUtil.reverseString(baseQuals); // } // // if(!rec.getReadPairedFlag()){ // FastqParser.writeFastQToStream(outFile, rec.getReadName(), sequence, baseQuals); // }else{ // readId = new StringBuilder(rec.getReadName()); // readId.append(pairDelim); // if(rec.getFirstOfPairFlag()){ // readId.append("1"); // }else{ // readId.append("2"); // } // FastqParser.writeFastQToStream(outFile, readId.toString(), sequence, baseQuals); // } // // } // } // // Path: src/main/java/org/umcn/me/samexternal/SAMDefinitions.java // public class SAMDefinitions { // // public static final String MAPPING_TOOL_BWA = "bwa"; // public static final String MAPPING_TOOL_MOSAIK = "mosaik"; // public static final String MAPPING_TOOL_LIFESCOPE = "lifescope"; // public static final String MAPPING_TOOL_UNSPECIFIED = "unspecified"; // // public static final String[] MAPPING_TOOLS = {MAPPING_TOOL_MOSAIK, MAPPING_TOOL_BWA, MAPPING_TOOL_LIFESCOPE, MAPPING_TOOL_UNSPECIFIED}; // public static final String MOSAIK_MAPPINGINFO_ATTRIBUTE = "ZA"; // public static final String LIFESCOPE_NRHITS_ATTRIBUTE = "NH"; // public static final String BWA_NR_OPTIMAL_HITS_ATTRIBUTE = "X0"; // public static final String BWA_NR_SUBOPTIMAL_HITS_ATTRIBUTE = "X1"; // public static final int MOSAIK_MAPPINGINFO_READ1 = 0; // public static final int MOSAIK_MAPPINGINFO_READ2 = 1; // public static final int MOSAIK_MAPPINGINFO_NRHITS = 4; // public static final String READ_NUMBER_SEPERATOR = "-"; // public static final String UNIQUE_UNIQUE_MAPPING = "UU"; // public static final String UNIQUE_UNMAPPED_MAPPING = "UX"; // public static final String UNIQUE_MULTIPLE_MAPPING = "UM"; // public static final String SPLIT_MAPPING = "S"; // public static final char LEFT_CLIPPED = 'L'; // public static final char RIGHT_CLIPPED = 'R'; // // } // // Path: src/main/java/org/umcn/me/samexternal/UnknownParamException.java // public class UnknownParamException extends Exception { // // private static final long serialVersionUID = 5984202278542517694L; // // public UnknownParamException(String string) { // super(string); // } // } // Path: src/main/java/org/umcn/me/pairedend/PotentialMEIFinder.java import net.sf.samtools.*; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import java.io.*; import java.util.*; import org.umcn.me.parsers.FastqParser; import org.umcn.me.samexternal.SAMDefinitions; import org.umcn.me.samexternal.UnknownParamException; package org.umcn.me.pairedend; /** * This class is used to find read pairs that could potentially indicate * a MEI event: * - Read pairs which map for one end uniquely to the genome and for * the other end multiple times to the genome; but only when * the reads are not properly paired**. * - Read pairs which map for for one end uniquely to the genome and * for the other end 0 times to the genome (orphans). * - Read pairs which map for both ends uniquely to genome but * are not properly paired**. * * **unproperly paired: * - both reads map on + strand * - both reads map on - strand * - read mapping on + strand has higher genomic coordinate * than read mapping on - strand * - proper FR orientation but insert size not in * mean fragment size +/- local search * * All potential MEI supporting read pairs are written to a bam file. * All reads in a read pair which may potentially map (orphans, multiple mappings, * unproper pairs for unique-unique pairs) to mobile references * are written to seperate fq files. * @author Djie * */ public class PotentialMEIFinder { public static Logger logger = Logger.getLogger("PotentialMEIFinder"); private String pair_number_seperator; private String mapping_tool; private String output_prefix; private String bam_mapped_to_ref; public PotentialMEIFinder(String pairNumberSeperator, String inBam, String outPrefix,
String tool) throws UnknownParamException{
jyhehir/mobster
src/main/java/org/umcn/me/pairedend/PotentialMEIFinder.java
// Path: src/main/java/org/umcn/me/parsers/FastqParser.java // public class FastqParser { // // public static Logger logger = Logger.getLogger("FastaParserFast"); // // // //TODO: check whether qual string is a legal qual string // public static void writeFastQToStream(PrintWriter outFile, String id, // String seq, String qual){ // // StringBuilder readId = new StringBuilder(); // // if (!readId.toString().startsWith("@")){ // readId.append("@"); // } // // readId.append(id); // // outFile.println(readId.toString()); // outFile.println(seq); // outFile.println("+"); // outFile.println(qual); // // } // // public static void writeFastQToStream(PrintWriter outFile, SAMRecord rec, boolean reReverse){ // final String pairDelim = "/"; //default Illumina seperator // StringBuilder readId; // String sequence = rec.getReadString(); // String baseQuals = rec.getBaseQualityString(); // // //make reverse complement of sequence if mapped on negative strand, to get to original fastq record // if (reReverse && rec.getReadNegativeStrandFlag()){ // sequence = SequenceUtil.reverseComplement(sequence); // baseQuals = StringUtil.reverseString(baseQuals); // } // // if(!rec.getReadPairedFlag()){ // FastqParser.writeFastQToStream(outFile, rec.getReadName(), sequence, baseQuals); // }else{ // readId = new StringBuilder(rec.getReadName()); // readId.append(pairDelim); // if(rec.getFirstOfPairFlag()){ // readId.append("1"); // }else{ // readId.append("2"); // } // FastqParser.writeFastQToStream(outFile, readId.toString(), sequence, baseQuals); // } // // } // } // // Path: src/main/java/org/umcn/me/samexternal/SAMDefinitions.java // public class SAMDefinitions { // // public static final String MAPPING_TOOL_BWA = "bwa"; // public static final String MAPPING_TOOL_MOSAIK = "mosaik"; // public static final String MAPPING_TOOL_LIFESCOPE = "lifescope"; // public static final String MAPPING_TOOL_UNSPECIFIED = "unspecified"; // // public static final String[] MAPPING_TOOLS = {MAPPING_TOOL_MOSAIK, MAPPING_TOOL_BWA, MAPPING_TOOL_LIFESCOPE, MAPPING_TOOL_UNSPECIFIED}; // public static final String MOSAIK_MAPPINGINFO_ATTRIBUTE = "ZA"; // public static final String LIFESCOPE_NRHITS_ATTRIBUTE = "NH"; // public static final String BWA_NR_OPTIMAL_HITS_ATTRIBUTE = "X0"; // public static final String BWA_NR_SUBOPTIMAL_HITS_ATTRIBUTE = "X1"; // public static final int MOSAIK_MAPPINGINFO_READ1 = 0; // public static final int MOSAIK_MAPPINGINFO_READ2 = 1; // public static final int MOSAIK_MAPPINGINFO_NRHITS = 4; // public static final String READ_NUMBER_SEPERATOR = "-"; // public static final String UNIQUE_UNIQUE_MAPPING = "UU"; // public static final String UNIQUE_UNMAPPED_MAPPING = "UX"; // public static final String UNIQUE_MULTIPLE_MAPPING = "UM"; // public static final String SPLIT_MAPPING = "S"; // public static final char LEFT_CLIPPED = 'L'; // public static final char RIGHT_CLIPPED = 'R'; // // } // // Path: src/main/java/org/umcn/me/samexternal/UnknownParamException.java // public class UnknownParamException extends Exception { // // private static final long serialVersionUID = 5984202278542517694L; // // public UnknownParamException(String string) { // super(string); // } // }
import net.sf.samtools.*; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import java.io.*; import java.util.*; import org.umcn.me.parsers.FastqParser; import org.umcn.me.samexternal.SAMDefinitions; import org.umcn.me.samexternal.UnknownParamException;
package org.umcn.me.pairedend; /** * This class is used to find read pairs that could potentially indicate * a MEI event: * - Read pairs which map for one end uniquely to the genome and for * the other end multiple times to the genome; but only when * the reads are not properly paired**. * - Read pairs which map for for one end uniquely to the genome and * for the other end 0 times to the genome (orphans). * - Read pairs which map for both ends uniquely to genome but * are not properly paired**. * * **unproperly paired: * - both reads map on + strand * - both reads map on - strand * - read mapping on + strand has higher genomic coordinate * than read mapping on - strand * - proper FR orientation but insert size not in * mean fragment size +/- local search * * All potential MEI supporting read pairs are written to a bam file. * All reads in a read pair which may potentially map (orphans, multiple mappings, * unproper pairs for unique-unique pairs) to mobile references * are written to seperate fq files. * @author Djie * */ public class PotentialMEIFinder { public static Logger logger = Logger.getLogger("PotentialMEIFinder"); private String pair_number_seperator; private String mapping_tool; private String output_prefix; private String bam_mapped_to_ref; public PotentialMEIFinder(String pairNumberSeperator, String inBam, String outPrefix, String tool) throws UnknownParamException{ BasicConfigurator.configure(); this.pair_number_seperator = pairNumberSeperator; this.bam_mapped_to_ref = inBam; this.output_prefix = outPrefix; this.mapping_tool = tool;
// Path: src/main/java/org/umcn/me/parsers/FastqParser.java // public class FastqParser { // // public static Logger logger = Logger.getLogger("FastaParserFast"); // // // //TODO: check whether qual string is a legal qual string // public static void writeFastQToStream(PrintWriter outFile, String id, // String seq, String qual){ // // StringBuilder readId = new StringBuilder(); // // if (!readId.toString().startsWith("@")){ // readId.append("@"); // } // // readId.append(id); // // outFile.println(readId.toString()); // outFile.println(seq); // outFile.println("+"); // outFile.println(qual); // // } // // public static void writeFastQToStream(PrintWriter outFile, SAMRecord rec, boolean reReverse){ // final String pairDelim = "/"; //default Illumina seperator // StringBuilder readId; // String sequence = rec.getReadString(); // String baseQuals = rec.getBaseQualityString(); // // //make reverse complement of sequence if mapped on negative strand, to get to original fastq record // if (reReverse && rec.getReadNegativeStrandFlag()){ // sequence = SequenceUtil.reverseComplement(sequence); // baseQuals = StringUtil.reverseString(baseQuals); // } // // if(!rec.getReadPairedFlag()){ // FastqParser.writeFastQToStream(outFile, rec.getReadName(), sequence, baseQuals); // }else{ // readId = new StringBuilder(rec.getReadName()); // readId.append(pairDelim); // if(rec.getFirstOfPairFlag()){ // readId.append("1"); // }else{ // readId.append("2"); // } // FastqParser.writeFastQToStream(outFile, readId.toString(), sequence, baseQuals); // } // // } // } // // Path: src/main/java/org/umcn/me/samexternal/SAMDefinitions.java // public class SAMDefinitions { // // public static final String MAPPING_TOOL_BWA = "bwa"; // public static final String MAPPING_TOOL_MOSAIK = "mosaik"; // public static final String MAPPING_TOOL_LIFESCOPE = "lifescope"; // public static final String MAPPING_TOOL_UNSPECIFIED = "unspecified"; // // public static final String[] MAPPING_TOOLS = {MAPPING_TOOL_MOSAIK, MAPPING_TOOL_BWA, MAPPING_TOOL_LIFESCOPE, MAPPING_TOOL_UNSPECIFIED}; // public static final String MOSAIK_MAPPINGINFO_ATTRIBUTE = "ZA"; // public static final String LIFESCOPE_NRHITS_ATTRIBUTE = "NH"; // public static final String BWA_NR_OPTIMAL_HITS_ATTRIBUTE = "X0"; // public static final String BWA_NR_SUBOPTIMAL_HITS_ATTRIBUTE = "X1"; // public static final int MOSAIK_MAPPINGINFO_READ1 = 0; // public static final int MOSAIK_MAPPINGINFO_READ2 = 1; // public static final int MOSAIK_MAPPINGINFO_NRHITS = 4; // public static final String READ_NUMBER_SEPERATOR = "-"; // public static final String UNIQUE_UNIQUE_MAPPING = "UU"; // public static final String UNIQUE_UNMAPPED_MAPPING = "UX"; // public static final String UNIQUE_MULTIPLE_MAPPING = "UM"; // public static final String SPLIT_MAPPING = "S"; // public static final char LEFT_CLIPPED = 'L'; // public static final char RIGHT_CLIPPED = 'R'; // // } // // Path: src/main/java/org/umcn/me/samexternal/UnknownParamException.java // public class UnknownParamException extends Exception { // // private static final long serialVersionUID = 5984202278542517694L; // // public UnknownParamException(String string) { // super(string); // } // } // Path: src/main/java/org/umcn/me/pairedend/PotentialMEIFinder.java import net.sf.samtools.*; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import java.io.*; import java.util.*; import org.umcn.me.parsers.FastqParser; import org.umcn.me.samexternal.SAMDefinitions; import org.umcn.me.samexternal.UnknownParamException; package org.umcn.me.pairedend; /** * This class is used to find read pairs that could potentially indicate * a MEI event: * - Read pairs which map for one end uniquely to the genome and for * the other end multiple times to the genome; but only when * the reads are not properly paired**. * - Read pairs which map for for one end uniquely to the genome and * for the other end 0 times to the genome (orphans). * - Read pairs which map for both ends uniquely to genome but * are not properly paired**. * * **unproperly paired: * - both reads map on + strand * - both reads map on - strand * - read mapping on + strand has higher genomic coordinate * than read mapping on - strand * - proper FR orientation but insert size not in * mean fragment size +/- local search * * All potential MEI supporting read pairs are written to a bam file. * All reads in a read pair which may potentially map (orphans, multiple mappings, * unproper pairs for unique-unique pairs) to mobile references * are written to seperate fq files. * @author Djie * */ public class PotentialMEIFinder { public static Logger logger = Logger.getLogger("PotentialMEIFinder"); private String pair_number_seperator; private String mapping_tool; private String output_prefix; private String bam_mapped_to_ref; public PotentialMEIFinder(String pairNumberSeperator, String inBam, String outPrefix, String tool) throws UnknownParamException{ BasicConfigurator.configure(); this.pair_number_seperator = pairNumberSeperator; this.bam_mapped_to_ref = inBam; this.output_prefix = outPrefix; this.mapping_tool = tool;
supportedParamCheck(SAMDefinitions.MAPPING_TOOLS, tool);
jyhehir/mobster
src/main/java/org/umcn/me/pairedend/PotentialMEIFinder.java
// Path: src/main/java/org/umcn/me/parsers/FastqParser.java // public class FastqParser { // // public static Logger logger = Logger.getLogger("FastaParserFast"); // // // //TODO: check whether qual string is a legal qual string // public static void writeFastQToStream(PrintWriter outFile, String id, // String seq, String qual){ // // StringBuilder readId = new StringBuilder(); // // if (!readId.toString().startsWith("@")){ // readId.append("@"); // } // // readId.append(id); // // outFile.println(readId.toString()); // outFile.println(seq); // outFile.println("+"); // outFile.println(qual); // // } // // public static void writeFastQToStream(PrintWriter outFile, SAMRecord rec, boolean reReverse){ // final String pairDelim = "/"; //default Illumina seperator // StringBuilder readId; // String sequence = rec.getReadString(); // String baseQuals = rec.getBaseQualityString(); // // //make reverse complement of sequence if mapped on negative strand, to get to original fastq record // if (reReverse && rec.getReadNegativeStrandFlag()){ // sequence = SequenceUtil.reverseComplement(sequence); // baseQuals = StringUtil.reverseString(baseQuals); // } // // if(!rec.getReadPairedFlag()){ // FastqParser.writeFastQToStream(outFile, rec.getReadName(), sequence, baseQuals); // }else{ // readId = new StringBuilder(rec.getReadName()); // readId.append(pairDelim); // if(rec.getFirstOfPairFlag()){ // readId.append("1"); // }else{ // readId.append("2"); // } // FastqParser.writeFastQToStream(outFile, readId.toString(), sequence, baseQuals); // } // // } // } // // Path: src/main/java/org/umcn/me/samexternal/SAMDefinitions.java // public class SAMDefinitions { // // public static final String MAPPING_TOOL_BWA = "bwa"; // public static final String MAPPING_TOOL_MOSAIK = "mosaik"; // public static final String MAPPING_TOOL_LIFESCOPE = "lifescope"; // public static final String MAPPING_TOOL_UNSPECIFIED = "unspecified"; // // public static final String[] MAPPING_TOOLS = {MAPPING_TOOL_MOSAIK, MAPPING_TOOL_BWA, MAPPING_TOOL_LIFESCOPE, MAPPING_TOOL_UNSPECIFIED}; // public static final String MOSAIK_MAPPINGINFO_ATTRIBUTE = "ZA"; // public static final String LIFESCOPE_NRHITS_ATTRIBUTE = "NH"; // public static final String BWA_NR_OPTIMAL_HITS_ATTRIBUTE = "X0"; // public static final String BWA_NR_SUBOPTIMAL_HITS_ATTRIBUTE = "X1"; // public static final int MOSAIK_MAPPINGINFO_READ1 = 0; // public static final int MOSAIK_MAPPINGINFO_READ2 = 1; // public static final int MOSAIK_MAPPINGINFO_NRHITS = 4; // public static final String READ_NUMBER_SEPERATOR = "-"; // public static final String UNIQUE_UNIQUE_MAPPING = "UU"; // public static final String UNIQUE_UNMAPPED_MAPPING = "UX"; // public static final String UNIQUE_MULTIPLE_MAPPING = "UM"; // public static final String SPLIT_MAPPING = "S"; // public static final char LEFT_CLIPPED = 'L'; // public static final char RIGHT_CLIPPED = 'R'; // // } // // Path: src/main/java/org/umcn/me/samexternal/UnknownParamException.java // public class UnknownParamException extends Exception { // // private static final long serialVersionUID = 5984202278542517694L; // // public UnknownParamException(String string) { // super(string); // } // }
import net.sf.samtools.*; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import java.io.*; import java.util.*; import org.umcn.me.parsers.FastqParser; import org.umcn.me.samexternal.SAMDefinitions; import org.umcn.me.samexternal.UnknownParamException;
File input = new File(this.bam_mapped_to_ref); int mappingsRead; //Nr mappings for current SAM Record Read int mappingsMate; //Nr mappings for mate of current SAM Record Read int nrPotentialMobileReads = 0; int nrMatesOfPotentialMobileReads = 0; int c = 0; File outputBam = new File(this.output_prefix + "_potential.bam"); PrintWriter outFq = new PrintWriter(new FileWriter(this.output_prefix + "_potential.fq"), true); SAMFileReader inputSam = new SAMFileReader(input); inputSam.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); SAMFileReader inputSam2 = new SAMFileReader(input); inputSam2.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); SAMFileWriter outputSam = new SAMFileWriterFactory().makeSAMOrBAMWriter(inputSam.getFileHeader(), false, outputBam); for (SAMRecord samRecord : inputSam) { c++; if (c % 10000 == 0){ System.out.println(c); } mappingsRead = getNumberOfMappings(samRecord, this.mapping_tool); mappingsMate = getNumberOfMappingsOfMate(samRecord, this.mapping_tool, inputSam2); if (isReadPotentialMobile(mappingsRead, mappingsMate, samRecord)){
// Path: src/main/java/org/umcn/me/parsers/FastqParser.java // public class FastqParser { // // public static Logger logger = Logger.getLogger("FastaParserFast"); // // // //TODO: check whether qual string is a legal qual string // public static void writeFastQToStream(PrintWriter outFile, String id, // String seq, String qual){ // // StringBuilder readId = new StringBuilder(); // // if (!readId.toString().startsWith("@")){ // readId.append("@"); // } // // readId.append(id); // // outFile.println(readId.toString()); // outFile.println(seq); // outFile.println("+"); // outFile.println(qual); // // } // // public static void writeFastQToStream(PrintWriter outFile, SAMRecord rec, boolean reReverse){ // final String pairDelim = "/"; //default Illumina seperator // StringBuilder readId; // String sequence = rec.getReadString(); // String baseQuals = rec.getBaseQualityString(); // // //make reverse complement of sequence if mapped on negative strand, to get to original fastq record // if (reReverse && rec.getReadNegativeStrandFlag()){ // sequence = SequenceUtil.reverseComplement(sequence); // baseQuals = StringUtil.reverseString(baseQuals); // } // // if(!rec.getReadPairedFlag()){ // FastqParser.writeFastQToStream(outFile, rec.getReadName(), sequence, baseQuals); // }else{ // readId = new StringBuilder(rec.getReadName()); // readId.append(pairDelim); // if(rec.getFirstOfPairFlag()){ // readId.append("1"); // }else{ // readId.append("2"); // } // FastqParser.writeFastQToStream(outFile, readId.toString(), sequence, baseQuals); // } // // } // } // // Path: src/main/java/org/umcn/me/samexternal/SAMDefinitions.java // public class SAMDefinitions { // // public static final String MAPPING_TOOL_BWA = "bwa"; // public static final String MAPPING_TOOL_MOSAIK = "mosaik"; // public static final String MAPPING_TOOL_LIFESCOPE = "lifescope"; // public static final String MAPPING_TOOL_UNSPECIFIED = "unspecified"; // // public static final String[] MAPPING_TOOLS = {MAPPING_TOOL_MOSAIK, MAPPING_TOOL_BWA, MAPPING_TOOL_LIFESCOPE, MAPPING_TOOL_UNSPECIFIED}; // public static final String MOSAIK_MAPPINGINFO_ATTRIBUTE = "ZA"; // public static final String LIFESCOPE_NRHITS_ATTRIBUTE = "NH"; // public static final String BWA_NR_OPTIMAL_HITS_ATTRIBUTE = "X0"; // public static final String BWA_NR_SUBOPTIMAL_HITS_ATTRIBUTE = "X1"; // public static final int MOSAIK_MAPPINGINFO_READ1 = 0; // public static final int MOSAIK_MAPPINGINFO_READ2 = 1; // public static final int MOSAIK_MAPPINGINFO_NRHITS = 4; // public static final String READ_NUMBER_SEPERATOR = "-"; // public static final String UNIQUE_UNIQUE_MAPPING = "UU"; // public static final String UNIQUE_UNMAPPED_MAPPING = "UX"; // public static final String UNIQUE_MULTIPLE_MAPPING = "UM"; // public static final String SPLIT_MAPPING = "S"; // public static final char LEFT_CLIPPED = 'L'; // public static final char RIGHT_CLIPPED = 'R'; // // } // // Path: src/main/java/org/umcn/me/samexternal/UnknownParamException.java // public class UnknownParamException extends Exception { // // private static final long serialVersionUID = 5984202278542517694L; // // public UnknownParamException(String string) { // super(string); // } // } // Path: src/main/java/org/umcn/me/pairedend/PotentialMEIFinder.java import net.sf.samtools.*; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import java.io.*; import java.util.*; import org.umcn.me.parsers.FastqParser; import org.umcn.me.samexternal.SAMDefinitions; import org.umcn.me.samexternal.UnknownParamException; File input = new File(this.bam_mapped_to_ref); int mappingsRead; //Nr mappings for current SAM Record Read int mappingsMate; //Nr mappings for mate of current SAM Record Read int nrPotentialMobileReads = 0; int nrMatesOfPotentialMobileReads = 0; int c = 0; File outputBam = new File(this.output_prefix + "_potential.bam"); PrintWriter outFq = new PrintWriter(new FileWriter(this.output_prefix + "_potential.fq"), true); SAMFileReader inputSam = new SAMFileReader(input); inputSam.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); SAMFileReader inputSam2 = new SAMFileReader(input); inputSam2.setValidationStringency(SAMFileReader.ValidationStringency.SILENT); SAMFileWriter outputSam = new SAMFileWriterFactory().makeSAMOrBAMWriter(inputSam.getFileHeader(), false, outputBam); for (SAMRecord samRecord : inputSam) { c++; if (c % 10000 == 0){ System.out.println(c); } mappingsRead = getNumberOfMappings(samRecord, this.mapping_tool); mappingsMate = getNumberOfMappingsOfMate(samRecord, this.mapping_tool, inputSam2); if (isReadPotentialMobile(mappingsRead, mappingsMate, samRecord)){
FastqParser.writeFastQToStream(outFq, makeFastQHeaderFromSAMRecord(samRecord, this.pair_number_seperator),
janishar/JPost
jpost/src/main/java/com/mindorks/jpost/core/PrivateChannel.java
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/InvalidSubscriberException.java // public class InvalidSubscriberException extends Exception{ // // public InvalidSubscriberException(String message) { // super(message); // } // // public String toString() { // return "InvalidSubscriberException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // }
import com.mindorks.jpost.exceptions.InvalidSubscriberException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.ref.WeakReference; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue;
/* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public class PrivateChannel< Q extends PriorityBlockingQueue<WeakReference<ChannelPost>>, M extends ConcurrentHashMap<Integer,WeakReference<Object>>> extends PublicChannel<Q,M>{ private WeakReference<Object> channelOwnerRef; public PrivateChannel(Integer channelId, ChannelState state, ChannelType type, Q postQueue, M subscriberMap, WeakReference<Object> channelOwnerRef) { super(channelId, state, type, postQueue, subscriberMap); this.channelOwnerRef = channelOwnerRef; } protected WeakReference<Object> getChannelOwnerRef() { return channelOwnerRef; }
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/InvalidSubscriberException.java // public class InvalidSubscriberException extends Exception{ // // public InvalidSubscriberException(String message) { // super(message); // } // // public String toString() { // return "InvalidSubscriberException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // } // Path: jpost/src/main/java/com/mindorks/jpost/core/PrivateChannel.java import com.mindorks.jpost.exceptions.InvalidSubscriberException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.ref.WeakReference; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue; /* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public class PrivateChannel< Q extends PriorityBlockingQueue<WeakReference<ChannelPost>>, M extends ConcurrentHashMap<Integer,WeakReference<Object>>> extends PublicChannel<Q,M>{ private WeakReference<Object> channelOwnerRef; public PrivateChannel(Integer channelId, ChannelState state, ChannelType type, Q postQueue, M subscriberMap, WeakReference<Object> channelOwnerRef) { super(channelId, state, type, postQueue, subscriberMap); this.channelOwnerRef = channelOwnerRef; } protected WeakReference<Object> getChannelOwnerRef() { return channelOwnerRef; }
protected synchronized void removeSubscriber(Integer subscriberId) throws NullObjectException,InvalidSubscriberException {
janishar/JPost
jpost/src/main/java/com/mindorks/jpost/core/PrivateChannel.java
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/InvalidSubscriberException.java // public class InvalidSubscriberException extends Exception{ // // public InvalidSubscriberException(String message) { // super(message); // } // // public String toString() { // return "InvalidSubscriberException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // }
import com.mindorks.jpost.exceptions.InvalidSubscriberException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.ref.WeakReference; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue;
/* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public class PrivateChannel< Q extends PriorityBlockingQueue<WeakReference<ChannelPost>>, M extends ConcurrentHashMap<Integer,WeakReference<Object>>> extends PublicChannel<Q,M>{ private WeakReference<Object> channelOwnerRef; public PrivateChannel(Integer channelId, ChannelState state, ChannelType type, Q postQueue, M subscriberMap, WeakReference<Object> channelOwnerRef) { super(channelId, state, type, postQueue, subscriberMap); this.channelOwnerRef = channelOwnerRef; } protected WeakReference<Object> getChannelOwnerRef() { return channelOwnerRef; }
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/InvalidSubscriberException.java // public class InvalidSubscriberException extends Exception{ // // public InvalidSubscriberException(String message) { // super(message); // } // // public String toString() { // return "InvalidSubscriberException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // } // Path: jpost/src/main/java/com/mindorks/jpost/core/PrivateChannel.java import com.mindorks.jpost.exceptions.InvalidSubscriberException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.ref.WeakReference; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue; /* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public class PrivateChannel< Q extends PriorityBlockingQueue<WeakReference<ChannelPost>>, M extends ConcurrentHashMap<Integer,WeakReference<Object>>> extends PublicChannel<Q,M>{ private WeakReference<Object> channelOwnerRef; public PrivateChannel(Integer channelId, ChannelState state, ChannelType type, Q postQueue, M subscriberMap, WeakReference<Object> channelOwnerRef) { super(channelId, state, type, postQueue, subscriberMap); this.channelOwnerRef = channelOwnerRef; } protected WeakReference<Object> getChannelOwnerRef() { return channelOwnerRef; }
protected synchronized void removeSubscriber(Integer subscriberId) throws NullObjectException,InvalidSubscriberException {
janishar/JPost
src/main/java/tes/mindorks/jpost/subscriber/Subscriber.java
// Path: java-jpost/src/main/java/com/mindorks/javajpost/JPost.java // public class JPost { // // private static ReentrantLock JPostBootLock = new ReentrantLock(); // // private static ConcurrentHashMap<Integer, Channel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>> channelMap; // // private static BroadcastCenter broadcastCenter; // // private static DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>> channel; // // private static int threadCount; // private static ExecutorService executorService; // // static { // init(); // } // // private static void init(){ // threadCount = Runtime.getRuntime().availableProcessors() + 1; // executorService = Executors.newFixedThreadPool(threadCount); // channelMap = new ConcurrentHashMap<>(Broadcast.CHANNEL_INITIAL_CAPACITY); // channel = new DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>( // Channel.DEFAULT_CHANNEL_ID, // ChannelState.OPEN, // ChannelType.DEFAULT, // new PriorityBlockingQueue<>(Channel.MSG_QUEUE_INITIAL_CAPACITY, // new Comparator<WeakReference<ChannelPost>>() { // @Override // public int compare(WeakReference<ChannelPost> o1, WeakReference<ChannelPost> o2) { // ChannelPost post1 = o1.get(); // ChannelPost post2 = o2.get(); // if(post1 != null || post2 != null // || post1.getPriority() != null // || post2.getPriority() != null){ // return post1.getPriority().compareTo(post2.getPriority()); // }else{ // return 0; // } // } // }), // new ConcurrentHashMap<Integer,WeakReference<Object>>(Channel.SUBSCRIBER_INITIAL_CAPACITY)); // // channelMap.put(Channel.DEFAULT_CHANNEL_ID, channel); // broadcastCenter = new BroadcastCenter(channelMap, executorService); // } // // public static Broadcast getBroadcastCenter(){ // return broadcastCenter; // } // // public static void reboot(){ // JPostBootLock.lock(); // executorService = Executors.newFixedThreadPool(threadCount); // broadcastCenter.setExecutorService(executorService); // JPostBootLock.unlock(); // } // // public static void shutdown(){ // JPostBootLock.lock(); // executorService.shutdown(); // JPostBootLock.unlock(); // } // // public static void haltAndShutdown(){ // JPostBootLock.lock(); // executorService.shutdownNow(); // JPostBootLock.unlock(); // } // } // // Path: src/main/java/tes/mindorks/jpost/ChannelIds.java // public class ChannelIds { // // public static final int publicChannel1 = 1; // public static final int privateChannel1 = 2; // } // // Path: src/main/java/tes/mindorks/jpost/message/Message1.java // public class Message1 { // // private String msg; // // public Message1(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message1: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // // Path: src/main/java/tes/mindorks/jpost/message/Message2.java // public class Message2 { // // private String msg; // // public Message2(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message2: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // }
import com.mindorks.javajpost.JPost; import com.mindorks.jpost.core.OnMessage; import tes.mindorks.jpost.ChannelIds; import tes.mindorks.jpost.message.Message1; import tes.mindorks.jpost.message.Message2;
package tes.mindorks.jpost.subscriber; /** * Created by janisharali on 24/09/16. */ public class Subscriber { private char classifier; public Subscriber(char classifier) { this.classifier = classifier; try {
// Path: java-jpost/src/main/java/com/mindorks/javajpost/JPost.java // public class JPost { // // private static ReentrantLock JPostBootLock = new ReentrantLock(); // // private static ConcurrentHashMap<Integer, Channel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>> channelMap; // // private static BroadcastCenter broadcastCenter; // // private static DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>> channel; // // private static int threadCount; // private static ExecutorService executorService; // // static { // init(); // } // // private static void init(){ // threadCount = Runtime.getRuntime().availableProcessors() + 1; // executorService = Executors.newFixedThreadPool(threadCount); // channelMap = new ConcurrentHashMap<>(Broadcast.CHANNEL_INITIAL_CAPACITY); // channel = new DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>( // Channel.DEFAULT_CHANNEL_ID, // ChannelState.OPEN, // ChannelType.DEFAULT, // new PriorityBlockingQueue<>(Channel.MSG_QUEUE_INITIAL_CAPACITY, // new Comparator<WeakReference<ChannelPost>>() { // @Override // public int compare(WeakReference<ChannelPost> o1, WeakReference<ChannelPost> o2) { // ChannelPost post1 = o1.get(); // ChannelPost post2 = o2.get(); // if(post1 != null || post2 != null // || post1.getPriority() != null // || post2.getPriority() != null){ // return post1.getPriority().compareTo(post2.getPriority()); // }else{ // return 0; // } // } // }), // new ConcurrentHashMap<Integer,WeakReference<Object>>(Channel.SUBSCRIBER_INITIAL_CAPACITY)); // // channelMap.put(Channel.DEFAULT_CHANNEL_ID, channel); // broadcastCenter = new BroadcastCenter(channelMap, executorService); // } // // public static Broadcast getBroadcastCenter(){ // return broadcastCenter; // } // // public static void reboot(){ // JPostBootLock.lock(); // executorService = Executors.newFixedThreadPool(threadCount); // broadcastCenter.setExecutorService(executorService); // JPostBootLock.unlock(); // } // // public static void shutdown(){ // JPostBootLock.lock(); // executorService.shutdown(); // JPostBootLock.unlock(); // } // // public static void haltAndShutdown(){ // JPostBootLock.lock(); // executorService.shutdownNow(); // JPostBootLock.unlock(); // } // } // // Path: src/main/java/tes/mindorks/jpost/ChannelIds.java // public class ChannelIds { // // public static final int publicChannel1 = 1; // public static final int privateChannel1 = 2; // } // // Path: src/main/java/tes/mindorks/jpost/message/Message1.java // public class Message1 { // // private String msg; // // public Message1(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message1: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // // Path: src/main/java/tes/mindorks/jpost/message/Message2.java // public class Message2 { // // private String msg; // // public Message2(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message2: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // Path: src/main/java/tes/mindorks/jpost/subscriber/Subscriber.java import com.mindorks.javajpost.JPost; import com.mindorks.jpost.core.OnMessage; import tes.mindorks.jpost.ChannelIds; import tes.mindorks.jpost.message.Message1; import tes.mindorks.jpost.message.Message2; package tes.mindorks.jpost.subscriber; /** * Created by janisharali on 24/09/16. */ public class Subscriber { private char classifier; public Subscriber(char classifier) { this.classifier = classifier; try {
JPost.getBroadcastCenter().addSubscriber(this);
janishar/JPost
src/main/java/tes/mindorks/jpost/subscriber/Subscriber.java
// Path: java-jpost/src/main/java/com/mindorks/javajpost/JPost.java // public class JPost { // // private static ReentrantLock JPostBootLock = new ReentrantLock(); // // private static ConcurrentHashMap<Integer, Channel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>> channelMap; // // private static BroadcastCenter broadcastCenter; // // private static DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>> channel; // // private static int threadCount; // private static ExecutorService executorService; // // static { // init(); // } // // private static void init(){ // threadCount = Runtime.getRuntime().availableProcessors() + 1; // executorService = Executors.newFixedThreadPool(threadCount); // channelMap = new ConcurrentHashMap<>(Broadcast.CHANNEL_INITIAL_CAPACITY); // channel = new DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>( // Channel.DEFAULT_CHANNEL_ID, // ChannelState.OPEN, // ChannelType.DEFAULT, // new PriorityBlockingQueue<>(Channel.MSG_QUEUE_INITIAL_CAPACITY, // new Comparator<WeakReference<ChannelPost>>() { // @Override // public int compare(WeakReference<ChannelPost> o1, WeakReference<ChannelPost> o2) { // ChannelPost post1 = o1.get(); // ChannelPost post2 = o2.get(); // if(post1 != null || post2 != null // || post1.getPriority() != null // || post2.getPriority() != null){ // return post1.getPriority().compareTo(post2.getPriority()); // }else{ // return 0; // } // } // }), // new ConcurrentHashMap<Integer,WeakReference<Object>>(Channel.SUBSCRIBER_INITIAL_CAPACITY)); // // channelMap.put(Channel.DEFAULT_CHANNEL_ID, channel); // broadcastCenter = new BroadcastCenter(channelMap, executorService); // } // // public static Broadcast getBroadcastCenter(){ // return broadcastCenter; // } // // public static void reboot(){ // JPostBootLock.lock(); // executorService = Executors.newFixedThreadPool(threadCount); // broadcastCenter.setExecutorService(executorService); // JPostBootLock.unlock(); // } // // public static void shutdown(){ // JPostBootLock.lock(); // executorService.shutdown(); // JPostBootLock.unlock(); // } // // public static void haltAndShutdown(){ // JPostBootLock.lock(); // executorService.shutdownNow(); // JPostBootLock.unlock(); // } // } // // Path: src/main/java/tes/mindorks/jpost/ChannelIds.java // public class ChannelIds { // // public static final int publicChannel1 = 1; // public static final int privateChannel1 = 2; // } // // Path: src/main/java/tes/mindorks/jpost/message/Message1.java // public class Message1 { // // private String msg; // // public Message1(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message1: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // // Path: src/main/java/tes/mindorks/jpost/message/Message2.java // public class Message2 { // // private String msg; // // public Message2(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message2: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // }
import com.mindorks.javajpost.JPost; import com.mindorks.jpost.core.OnMessage; import tes.mindorks.jpost.ChannelIds; import tes.mindorks.jpost.message.Message1; import tes.mindorks.jpost.message.Message2;
} public Subscriber(char classifier, int channelId, int subscriberId) { this.classifier = classifier; try { JPost.getBroadcastCenter().addSubscriber(channelId, this, subscriberId); }catch (Exception e){ e.printStackTrace(); } } public <T>Subscriber(T owner, char classifier, int channelId) { this.classifier = classifier; try { JPost.getBroadcastCenter().addSubscriber(owner, channelId, this); }catch (Exception e){ e.printStackTrace(); } } public <T>Subscriber(T owner, char classifier, int channelId, int subscriberId) { this.classifier = classifier; try { JPost.getBroadcastCenter().addSubscriber(owner, channelId, this, subscriberId); }catch (Exception e){ e.printStackTrace(); } } @OnMessage
// Path: java-jpost/src/main/java/com/mindorks/javajpost/JPost.java // public class JPost { // // private static ReentrantLock JPostBootLock = new ReentrantLock(); // // private static ConcurrentHashMap<Integer, Channel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>> channelMap; // // private static BroadcastCenter broadcastCenter; // // private static DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>> channel; // // private static int threadCount; // private static ExecutorService executorService; // // static { // init(); // } // // private static void init(){ // threadCount = Runtime.getRuntime().availableProcessors() + 1; // executorService = Executors.newFixedThreadPool(threadCount); // channelMap = new ConcurrentHashMap<>(Broadcast.CHANNEL_INITIAL_CAPACITY); // channel = new DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>( // Channel.DEFAULT_CHANNEL_ID, // ChannelState.OPEN, // ChannelType.DEFAULT, // new PriorityBlockingQueue<>(Channel.MSG_QUEUE_INITIAL_CAPACITY, // new Comparator<WeakReference<ChannelPost>>() { // @Override // public int compare(WeakReference<ChannelPost> o1, WeakReference<ChannelPost> o2) { // ChannelPost post1 = o1.get(); // ChannelPost post2 = o2.get(); // if(post1 != null || post2 != null // || post1.getPriority() != null // || post2.getPriority() != null){ // return post1.getPriority().compareTo(post2.getPriority()); // }else{ // return 0; // } // } // }), // new ConcurrentHashMap<Integer,WeakReference<Object>>(Channel.SUBSCRIBER_INITIAL_CAPACITY)); // // channelMap.put(Channel.DEFAULT_CHANNEL_ID, channel); // broadcastCenter = new BroadcastCenter(channelMap, executorService); // } // // public static Broadcast getBroadcastCenter(){ // return broadcastCenter; // } // // public static void reboot(){ // JPostBootLock.lock(); // executorService = Executors.newFixedThreadPool(threadCount); // broadcastCenter.setExecutorService(executorService); // JPostBootLock.unlock(); // } // // public static void shutdown(){ // JPostBootLock.lock(); // executorService.shutdown(); // JPostBootLock.unlock(); // } // // public static void haltAndShutdown(){ // JPostBootLock.lock(); // executorService.shutdownNow(); // JPostBootLock.unlock(); // } // } // // Path: src/main/java/tes/mindorks/jpost/ChannelIds.java // public class ChannelIds { // // public static final int publicChannel1 = 1; // public static final int privateChannel1 = 2; // } // // Path: src/main/java/tes/mindorks/jpost/message/Message1.java // public class Message1 { // // private String msg; // // public Message1(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message1: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // // Path: src/main/java/tes/mindorks/jpost/message/Message2.java // public class Message2 { // // private String msg; // // public Message2(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message2: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // Path: src/main/java/tes/mindorks/jpost/subscriber/Subscriber.java import com.mindorks.javajpost.JPost; import com.mindorks.jpost.core.OnMessage; import tes.mindorks.jpost.ChannelIds; import tes.mindorks.jpost.message.Message1; import tes.mindorks.jpost.message.Message2; } public Subscriber(char classifier, int channelId, int subscriberId) { this.classifier = classifier; try { JPost.getBroadcastCenter().addSubscriber(channelId, this, subscriberId); }catch (Exception e){ e.printStackTrace(); } } public <T>Subscriber(T owner, char classifier, int channelId) { this.classifier = classifier; try { JPost.getBroadcastCenter().addSubscriber(owner, channelId, this); }catch (Exception e){ e.printStackTrace(); } } public <T>Subscriber(T owner, char classifier, int channelId, int subscriberId) { this.classifier = classifier; try { JPost.getBroadcastCenter().addSubscriber(owner, channelId, this, subscriberId); }catch (Exception e){ e.printStackTrace(); } } @OnMessage
private void onMessage1(Message1 msg){
janishar/JPost
src/main/java/tes/mindorks/jpost/subscriber/Subscriber.java
// Path: java-jpost/src/main/java/com/mindorks/javajpost/JPost.java // public class JPost { // // private static ReentrantLock JPostBootLock = new ReentrantLock(); // // private static ConcurrentHashMap<Integer, Channel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>> channelMap; // // private static BroadcastCenter broadcastCenter; // // private static DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>> channel; // // private static int threadCount; // private static ExecutorService executorService; // // static { // init(); // } // // private static void init(){ // threadCount = Runtime.getRuntime().availableProcessors() + 1; // executorService = Executors.newFixedThreadPool(threadCount); // channelMap = new ConcurrentHashMap<>(Broadcast.CHANNEL_INITIAL_CAPACITY); // channel = new DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>( // Channel.DEFAULT_CHANNEL_ID, // ChannelState.OPEN, // ChannelType.DEFAULT, // new PriorityBlockingQueue<>(Channel.MSG_QUEUE_INITIAL_CAPACITY, // new Comparator<WeakReference<ChannelPost>>() { // @Override // public int compare(WeakReference<ChannelPost> o1, WeakReference<ChannelPost> o2) { // ChannelPost post1 = o1.get(); // ChannelPost post2 = o2.get(); // if(post1 != null || post2 != null // || post1.getPriority() != null // || post2.getPriority() != null){ // return post1.getPriority().compareTo(post2.getPriority()); // }else{ // return 0; // } // } // }), // new ConcurrentHashMap<Integer,WeakReference<Object>>(Channel.SUBSCRIBER_INITIAL_CAPACITY)); // // channelMap.put(Channel.DEFAULT_CHANNEL_ID, channel); // broadcastCenter = new BroadcastCenter(channelMap, executorService); // } // // public static Broadcast getBroadcastCenter(){ // return broadcastCenter; // } // // public static void reboot(){ // JPostBootLock.lock(); // executorService = Executors.newFixedThreadPool(threadCount); // broadcastCenter.setExecutorService(executorService); // JPostBootLock.unlock(); // } // // public static void shutdown(){ // JPostBootLock.lock(); // executorService.shutdown(); // JPostBootLock.unlock(); // } // // public static void haltAndShutdown(){ // JPostBootLock.lock(); // executorService.shutdownNow(); // JPostBootLock.unlock(); // } // } // // Path: src/main/java/tes/mindorks/jpost/ChannelIds.java // public class ChannelIds { // // public static final int publicChannel1 = 1; // public static final int privateChannel1 = 2; // } // // Path: src/main/java/tes/mindorks/jpost/message/Message1.java // public class Message1 { // // private String msg; // // public Message1(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message1: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // // Path: src/main/java/tes/mindorks/jpost/message/Message2.java // public class Message2 { // // private String msg; // // public Message2(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message2: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // }
import com.mindorks.javajpost.JPost; import com.mindorks.jpost.core.OnMessage; import tes.mindorks.jpost.ChannelIds; import tes.mindorks.jpost.message.Message1; import tes.mindorks.jpost.message.Message2;
try { JPost.getBroadcastCenter().addSubscriber(channelId, this, subscriberId); }catch (Exception e){ e.printStackTrace(); } } public <T>Subscriber(T owner, char classifier, int channelId) { this.classifier = classifier; try { JPost.getBroadcastCenter().addSubscriber(owner, channelId, this); }catch (Exception e){ e.printStackTrace(); } } public <T>Subscriber(T owner, char classifier, int channelId, int subscriberId) { this.classifier = classifier; try { JPost.getBroadcastCenter().addSubscriber(owner, channelId, this, subscriberId); }catch (Exception e){ e.printStackTrace(); } } @OnMessage private void onMessage1(Message1 msg){ System.out.println("Subscriber" + classifier + ": "+ msg.getMsg()); }
// Path: java-jpost/src/main/java/com/mindorks/javajpost/JPost.java // public class JPost { // // private static ReentrantLock JPostBootLock = new ReentrantLock(); // // private static ConcurrentHashMap<Integer, Channel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>> channelMap; // // private static BroadcastCenter broadcastCenter; // // private static DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>> channel; // // private static int threadCount; // private static ExecutorService executorService; // // static { // init(); // } // // private static void init(){ // threadCount = Runtime.getRuntime().availableProcessors() + 1; // executorService = Executors.newFixedThreadPool(threadCount); // channelMap = new ConcurrentHashMap<>(Broadcast.CHANNEL_INITIAL_CAPACITY); // channel = new DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>( // Channel.DEFAULT_CHANNEL_ID, // ChannelState.OPEN, // ChannelType.DEFAULT, // new PriorityBlockingQueue<>(Channel.MSG_QUEUE_INITIAL_CAPACITY, // new Comparator<WeakReference<ChannelPost>>() { // @Override // public int compare(WeakReference<ChannelPost> o1, WeakReference<ChannelPost> o2) { // ChannelPost post1 = o1.get(); // ChannelPost post2 = o2.get(); // if(post1 != null || post2 != null // || post1.getPriority() != null // || post2.getPriority() != null){ // return post1.getPriority().compareTo(post2.getPriority()); // }else{ // return 0; // } // } // }), // new ConcurrentHashMap<Integer,WeakReference<Object>>(Channel.SUBSCRIBER_INITIAL_CAPACITY)); // // channelMap.put(Channel.DEFAULT_CHANNEL_ID, channel); // broadcastCenter = new BroadcastCenter(channelMap, executorService); // } // // public static Broadcast getBroadcastCenter(){ // return broadcastCenter; // } // // public static void reboot(){ // JPostBootLock.lock(); // executorService = Executors.newFixedThreadPool(threadCount); // broadcastCenter.setExecutorService(executorService); // JPostBootLock.unlock(); // } // // public static void shutdown(){ // JPostBootLock.lock(); // executorService.shutdown(); // JPostBootLock.unlock(); // } // // public static void haltAndShutdown(){ // JPostBootLock.lock(); // executorService.shutdownNow(); // JPostBootLock.unlock(); // } // } // // Path: src/main/java/tes/mindorks/jpost/ChannelIds.java // public class ChannelIds { // // public static final int publicChannel1 = 1; // public static final int privateChannel1 = 2; // } // // Path: src/main/java/tes/mindorks/jpost/message/Message1.java // public class Message1 { // // private String msg; // // public Message1(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message1: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // // Path: src/main/java/tes/mindorks/jpost/message/Message2.java // public class Message2 { // // private String msg; // // public Message2(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message2: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // Path: src/main/java/tes/mindorks/jpost/subscriber/Subscriber.java import com.mindorks.javajpost.JPost; import com.mindorks.jpost.core.OnMessage; import tes.mindorks.jpost.ChannelIds; import tes.mindorks.jpost.message.Message1; import tes.mindorks.jpost.message.Message2; try { JPost.getBroadcastCenter().addSubscriber(channelId, this, subscriberId); }catch (Exception e){ e.printStackTrace(); } } public <T>Subscriber(T owner, char classifier, int channelId) { this.classifier = classifier; try { JPost.getBroadcastCenter().addSubscriber(owner, channelId, this); }catch (Exception e){ e.printStackTrace(); } } public <T>Subscriber(T owner, char classifier, int channelId, int subscriberId) { this.classifier = classifier; try { JPost.getBroadcastCenter().addSubscriber(owner, channelId, this, subscriberId); }catch (Exception e){ e.printStackTrace(); } } @OnMessage private void onMessage1(Message1 msg){ System.out.println("Subscriber" + classifier + ": "+ msg.getMsg()); }
@OnMessage(channelId = ChannelIds.publicChannel1)
janishar/JPost
src/main/java/tes/mindorks/jpost/subscriber/Subscriber.java
// Path: java-jpost/src/main/java/com/mindorks/javajpost/JPost.java // public class JPost { // // private static ReentrantLock JPostBootLock = new ReentrantLock(); // // private static ConcurrentHashMap<Integer, Channel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>> channelMap; // // private static BroadcastCenter broadcastCenter; // // private static DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>> channel; // // private static int threadCount; // private static ExecutorService executorService; // // static { // init(); // } // // private static void init(){ // threadCount = Runtime.getRuntime().availableProcessors() + 1; // executorService = Executors.newFixedThreadPool(threadCount); // channelMap = new ConcurrentHashMap<>(Broadcast.CHANNEL_INITIAL_CAPACITY); // channel = new DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>( // Channel.DEFAULT_CHANNEL_ID, // ChannelState.OPEN, // ChannelType.DEFAULT, // new PriorityBlockingQueue<>(Channel.MSG_QUEUE_INITIAL_CAPACITY, // new Comparator<WeakReference<ChannelPost>>() { // @Override // public int compare(WeakReference<ChannelPost> o1, WeakReference<ChannelPost> o2) { // ChannelPost post1 = o1.get(); // ChannelPost post2 = o2.get(); // if(post1 != null || post2 != null // || post1.getPriority() != null // || post2.getPriority() != null){ // return post1.getPriority().compareTo(post2.getPriority()); // }else{ // return 0; // } // } // }), // new ConcurrentHashMap<Integer,WeakReference<Object>>(Channel.SUBSCRIBER_INITIAL_CAPACITY)); // // channelMap.put(Channel.DEFAULT_CHANNEL_ID, channel); // broadcastCenter = new BroadcastCenter(channelMap, executorService); // } // // public static Broadcast getBroadcastCenter(){ // return broadcastCenter; // } // // public static void reboot(){ // JPostBootLock.lock(); // executorService = Executors.newFixedThreadPool(threadCount); // broadcastCenter.setExecutorService(executorService); // JPostBootLock.unlock(); // } // // public static void shutdown(){ // JPostBootLock.lock(); // executorService.shutdown(); // JPostBootLock.unlock(); // } // // public static void haltAndShutdown(){ // JPostBootLock.lock(); // executorService.shutdownNow(); // JPostBootLock.unlock(); // } // } // // Path: src/main/java/tes/mindorks/jpost/ChannelIds.java // public class ChannelIds { // // public static final int publicChannel1 = 1; // public static final int privateChannel1 = 2; // } // // Path: src/main/java/tes/mindorks/jpost/message/Message1.java // public class Message1 { // // private String msg; // // public Message1(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message1: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // // Path: src/main/java/tes/mindorks/jpost/message/Message2.java // public class Message2 { // // private String msg; // // public Message2(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message2: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // }
import com.mindorks.javajpost.JPost; import com.mindorks.jpost.core.OnMessage; import tes.mindorks.jpost.ChannelIds; import tes.mindorks.jpost.message.Message1; import tes.mindorks.jpost.message.Message2;
}catch (Exception e){ e.printStackTrace(); } } public <T>Subscriber(T owner, char classifier, int channelId, int subscriberId) { this.classifier = classifier; try { JPost.getBroadcastCenter().addSubscriber(owner, channelId, this, subscriberId); }catch (Exception e){ e.printStackTrace(); } } @OnMessage private void onMessage1(Message1 msg){ System.out.println("Subscriber" + classifier + ": "+ msg.getMsg()); } @OnMessage(channelId = ChannelIds.publicChannel1) private void onMessage1Pub(Message1 msg){ System.out.println("Subscriber" + classifier + ": "+ msg.getMsg()); } @OnMessage(channelId = ChannelIds.privateChannel1) private void onMessage1Pri(Message1 msg){ System.out.println("Subscriber" + classifier + ": "+ msg.getMsg()); } @OnMessage(isCommonReceiver = true)
// Path: java-jpost/src/main/java/com/mindorks/javajpost/JPost.java // public class JPost { // // private static ReentrantLock JPostBootLock = new ReentrantLock(); // // private static ConcurrentHashMap<Integer, Channel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>> channelMap; // // private static BroadcastCenter broadcastCenter; // // private static DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>> channel; // // private static int threadCount; // private static ExecutorService executorService; // // static { // init(); // } // // private static void init(){ // threadCount = Runtime.getRuntime().availableProcessors() + 1; // executorService = Executors.newFixedThreadPool(threadCount); // channelMap = new ConcurrentHashMap<>(Broadcast.CHANNEL_INITIAL_CAPACITY); // channel = new DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>( // Channel.DEFAULT_CHANNEL_ID, // ChannelState.OPEN, // ChannelType.DEFAULT, // new PriorityBlockingQueue<>(Channel.MSG_QUEUE_INITIAL_CAPACITY, // new Comparator<WeakReference<ChannelPost>>() { // @Override // public int compare(WeakReference<ChannelPost> o1, WeakReference<ChannelPost> o2) { // ChannelPost post1 = o1.get(); // ChannelPost post2 = o2.get(); // if(post1 != null || post2 != null // || post1.getPriority() != null // || post2.getPriority() != null){ // return post1.getPriority().compareTo(post2.getPriority()); // }else{ // return 0; // } // } // }), // new ConcurrentHashMap<Integer,WeakReference<Object>>(Channel.SUBSCRIBER_INITIAL_CAPACITY)); // // channelMap.put(Channel.DEFAULT_CHANNEL_ID, channel); // broadcastCenter = new BroadcastCenter(channelMap, executorService); // } // // public static Broadcast getBroadcastCenter(){ // return broadcastCenter; // } // // public static void reboot(){ // JPostBootLock.lock(); // executorService = Executors.newFixedThreadPool(threadCount); // broadcastCenter.setExecutorService(executorService); // JPostBootLock.unlock(); // } // // public static void shutdown(){ // JPostBootLock.lock(); // executorService.shutdown(); // JPostBootLock.unlock(); // } // // public static void haltAndShutdown(){ // JPostBootLock.lock(); // executorService.shutdownNow(); // JPostBootLock.unlock(); // } // } // // Path: src/main/java/tes/mindorks/jpost/ChannelIds.java // public class ChannelIds { // // public static final int publicChannel1 = 1; // public static final int privateChannel1 = 2; // } // // Path: src/main/java/tes/mindorks/jpost/message/Message1.java // public class Message1 { // // private String msg; // // public Message1(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message1: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // // Path: src/main/java/tes/mindorks/jpost/message/Message2.java // public class Message2 { // // private String msg; // // public Message2(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message2: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // Path: src/main/java/tes/mindorks/jpost/subscriber/Subscriber.java import com.mindorks.javajpost.JPost; import com.mindorks.jpost.core.OnMessage; import tes.mindorks.jpost.ChannelIds; import tes.mindorks.jpost.message.Message1; import tes.mindorks.jpost.message.Message2; }catch (Exception e){ e.printStackTrace(); } } public <T>Subscriber(T owner, char classifier, int channelId, int subscriberId) { this.classifier = classifier; try { JPost.getBroadcastCenter().addSubscriber(owner, channelId, this, subscriberId); }catch (Exception e){ e.printStackTrace(); } } @OnMessage private void onMessage1(Message1 msg){ System.out.println("Subscriber" + classifier + ": "+ msg.getMsg()); } @OnMessage(channelId = ChannelIds.publicChannel1) private void onMessage1Pub(Message1 msg){ System.out.println("Subscriber" + classifier + ": "+ msg.getMsg()); } @OnMessage(channelId = ChannelIds.privateChannel1) private void onMessage1Pri(Message1 msg){ System.out.println("Subscriber" + classifier + ": "+ msg.getMsg()); } @OnMessage(isCommonReceiver = true)
private void onMessage2(Message2 msg){
janishar/JPost
jpost/src/main/java/com/mindorks/jpost/core/Channel.java
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // }
import com.mindorks.jpost.exceptions.*; import com.mindorks.jpost.exceptions.IllegalChannelStateException; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue;
/* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public interface Channel<Q extends PriorityBlockingQueue<? extends WeakReference<? extends ChannelPost>>, M extends ConcurrentHashMap<? extends Integer,? extends WeakReference<?>>> { int MSG_QUEUE_INITIAL_CAPACITY = 10; int SUBSCRIBER_INITIAL_CAPACITY = 10; int DEFAULT_CHANNEL_ID = -99999999; /** * * @return */ Integer getChannelId(); /** * * @return */ ChannelType getChannelType(); /** * * @return */ Q getPostQueue(); /** * * @return */ M getSubscriberMap(); /** * * @return */ ChannelState getChannelState(); /** * * @param state */ void setChannelState(ChannelState state); /** * * @param msg * @param <T> * @throws NullObjectException * @throws IllegalChannelStateException */
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // Path: jpost/src/main/java/com/mindorks/jpost/core/Channel.java import com.mindorks.jpost.exceptions.*; import com.mindorks.jpost.exceptions.IllegalChannelStateException; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue; /* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public interface Channel<Q extends PriorityBlockingQueue<? extends WeakReference<? extends ChannelPost>>, M extends ConcurrentHashMap<? extends Integer,? extends WeakReference<?>>> { int MSG_QUEUE_INITIAL_CAPACITY = 10; int SUBSCRIBER_INITIAL_CAPACITY = 10; int DEFAULT_CHANNEL_ID = -99999999; /** * * @return */ Integer getChannelId(); /** * * @return */ ChannelType getChannelType(); /** * * @return */ Q getPostQueue(); /** * * @return */ M getSubscriberMap(); /** * * @return */ ChannelState getChannelState(); /** * * @param state */ void setChannelState(ChannelState state); /** * * @param msg * @param <T> * @throws NullObjectException * @throws IllegalChannelStateException */
<T>void broadcast(T msg) throws NullObjectException, IllegalChannelStateException;
janishar/JPost
android-jpost/src/main/java/com/mindorks/androidjpost/droid/AndroidPublicChannel.java
// Path: jpost/src/main/java/com/mindorks/jpost/core/PublicChannel.java // public class PublicChannel< // Q extends PriorityBlockingQueue<WeakReference<ChannelPost>>, // M extends ConcurrentHashMap<Integer,WeakReference<Object>>> // extends DefaultChannel<Q,M> // implements CustomChannel<Q,M>{ // // public PublicChannel(Integer channelId, ChannelState state, ChannelType type, Q postQueue, M subscriberMap) { // super(channelId, state, type, postQueue, subscriberMap); // } // // @Override // public void terminateChannel() { // super.setChannelState(ChannelState.TERMINATED); // super.getSubscriberMap().clear(); // super.getPostQueue().clear(); // } // // @Override // public void startChannel() { // super.setChannelState(ChannelState.OPEN); // } // // @Override // public void stopChannel() { // super.setChannelState(ChannelState.STOPPED); // } // // @Override // public <T> void broadcast(T msg, Integer... subscriberIds) throws NullObjectException, IllegalChannelStateException { // if(super.getChannelState() != ChannelState.OPEN){ // throw new IllegalChannelStateException("Channel with id " + super.getChannelId() + " is closed"); // } // if(msg == null){ // throw new NullObjectException("message is null"); // } // ChannelPost post = new ChannelPost<>(msg, getChannelId(), Post.PRIORITY_MEDIUM); // getPostQueue().put(new WeakReference<>(post)); // // while (!getPostQueue().isEmpty()) { // WeakReference<ChannelPost> msgRef = getPostQueue().poll(); // if(msgRef != null) { // ChannelPost mspPost = msgRef.get(); // if (mspPost != null && mspPost.getChannelId() != null) { // if (mspPost.getChannelId().equals(getChannelId())) { // for (Integer subscriberId : subscriberIds) { // if (getSubscriberMap().containsKey(subscriberId)) { // WeakReference<Object> subscriberRef = getSubscriberMap().get(subscriberId); // if(subscriberRef != null) { // Object subscriberObj = subscriberRef.get(); // if (subscriberObj != null) { // for (final Method method : subscriberObj.getClass().getDeclaredMethods()) { // Annotation annotation = method.getAnnotation(OnMessage.class); // if (annotation != null) { // deliverMessage(subscriberObj, (OnMessage) annotation, method, mspPost); // } // } // } // } // } // } // } // } // } // } // } // }
import android.os.Handler; import android.os.Looper; import com.mindorks.jpost.core.PublicChannel; import com.mindorks.jpost.core.OnMessage; import com.mindorks.jpost.core.*; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue;
/* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.androidjpost.droid; /** * Created by janisharali on 22/09/16. */ public class AndroidPublicChannel<Q extends PriorityBlockingQueue<WeakReference<ChannelPost>>, M extends ConcurrentHashMap<Integer,WeakReference<Object>>>
// Path: jpost/src/main/java/com/mindorks/jpost/core/PublicChannel.java // public class PublicChannel< // Q extends PriorityBlockingQueue<WeakReference<ChannelPost>>, // M extends ConcurrentHashMap<Integer,WeakReference<Object>>> // extends DefaultChannel<Q,M> // implements CustomChannel<Q,M>{ // // public PublicChannel(Integer channelId, ChannelState state, ChannelType type, Q postQueue, M subscriberMap) { // super(channelId, state, type, postQueue, subscriberMap); // } // // @Override // public void terminateChannel() { // super.setChannelState(ChannelState.TERMINATED); // super.getSubscriberMap().clear(); // super.getPostQueue().clear(); // } // // @Override // public void startChannel() { // super.setChannelState(ChannelState.OPEN); // } // // @Override // public void stopChannel() { // super.setChannelState(ChannelState.STOPPED); // } // // @Override // public <T> void broadcast(T msg, Integer... subscriberIds) throws NullObjectException, IllegalChannelStateException { // if(super.getChannelState() != ChannelState.OPEN){ // throw new IllegalChannelStateException("Channel with id " + super.getChannelId() + " is closed"); // } // if(msg == null){ // throw new NullObjectException("message is null"); // } // ChannelPost post = new ChannelPost<>(msg, getChannelId(), Post.PRIORITY_MEDIUM); // getPostQueue().put(new WeakReference<>(post)); // // while (!getPostQueue().isEmpty()) { // WeakReference<ChannelPost> msgRef = getPostQueue().poll(); // if(msgRef != null) { // ChannelPost mspPost = msgRef.get(); // if (mspPost != null && mspPost.getChannelId() != null) { // if (mspPost.getChannelId().equals(getChannelId())) { // for (Integer subscriberId : subscriberIds) { // if (getSubscriberMap().containsKey(subscriberId)) { // WeakReference<Object> subscriberRef = getSubscriberMap().get(subscriberId); // if(subscriberRef != null) { // Object subscriberObj = subscriberRef.get(); // if (subscriberObj != null) { // for (final Method method : subscriberObj.getClass().getDeclaredMethods()) { // Annotation annotation = method.getAnnotation(OnMessage.class); // if (annotation != null) { // deliverMessage(subscriberObj, (OnMessage) annotation, method, mspPost); // } // } // } // } // } // } // } // } // } // } // } // } // Path: android-jpost/src/main/java/com/mindorks/androidjpost/droid/AndroidPublicChannel.java import android.os.Handler; import android.os.Looper; import com.mindorks.jpost.core.PublicChannel; import com.mindorks.jpost.core.OnMessage; import com.mindorks.jpost.core.*; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue; /* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.androidjpost.droid; /** * Created by janisharali on 22/09/16. */ public class AndroidPublicChannel<Q extends PriorityBlockingQueue<WeakReference<ChannelPost>>, M extends ConcurrentHashMap<Integer,WeakReference<Object>>>
extends PublicChannel<Q,M> implements CustomChannel<Q,M>{
janishar/JPost
jpost/src/main/java/com/mindorks/jpost/core/OnMessage.java
// Path: jpost/src/main/java/com/mindorks/jpost/core/Channel.java // public interface Channel<Q extends PriorityBlockingQueue<? extends WeakReference<? extends ChannelPost>>, // M extends ConcurrentHashMap<? extends Integer,? extends WeakReference<?>>> { // // int MSG_QUEUE_INITIAL_CAPACITY = 10; // int SUBSCRIBER_INITIAL_CAPACITY = 10; // int DEFAULT_CHANNEL_ID = -99999999; // // /** // * // * @return // */ // Integer getChannelId(); // // /** // * // * @return // */ // ChannelType getChannelType(); // // /** // * // * @return // */ // Q getPostQueue(); // // /** // * // * @return // */ // M getSubscriberMap(); // // /** // * // * @return // */ // ChannelState getChannelState(); // // /** // * // * @param state // */ // void setChannelState(ChannelState state); // // /** // * // * @param msg // * @param <T> // * @throws NullObjectException // * @throws IllegalChannelStateException // */ // <T>void broadcast(T msg) throws NullObjectException, IllegalChannelStateException; // // /** // * // * @param subscriber // * @param subscriberId // * @param <T> // * @return // * @throws NullObjectException // * @throws AlreadyExistsException // * @throws IllegalChannelStateException // */ // <T> T addSubscriber(T subscriber, Integer subscriberId) throws NullObjectException, AlreadyExistsException, IllegalChannelStateException; // // /** // * // * @param subscriber // * @param <T> // * @throws NullObjectException // * @throws InvalidSubscriberException // */ // <T> void removeSubscriber(T subscriber) throws NullObjectException, InvalidSubscriberException; // // <T, P extends Post<?, ?>>boolean deliverMessage(T subscriber, OnMessage msgAnnotation, Method method, P post); // // /** // * // * @return // */ // Collection<? extends WeakReference<?>> getAllSubscribersReferenceList(); // }
import com.mindorks.jpost.core.Channel; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
/* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 23/09/16. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface OnMessage {
// Path: jpost/src/main/java/com/mindorks/jpost/core/Channel.java // public interface Channel<Q extends PriorityBlockingQueue<? extends WeakReference<? extends ChannelPost>>, // M extends ConcurrentHashMap<? extends Integer,? extends WeakReference<?>>> { // // int MSG_QUEUE_INITIAL_CAPACITY = 10; // int SUBSCRIBER_INITIAL_CAPACITY = 10; // int DEFAULT_CHANNEL_ID = -99999999; // // /** // * // * @return // */ // Integer getChannelId(); // // /** // * // * @return // */ // ChannelType getChannelType(); // // /** // * // * @return // */ // Q getPostQueue(); // // /** // * // * @return // */ // M getSubscriberMap(); // // /** // * // * @return // */ // ChannelState getChannelState(); // // /** // * // * @param state // */ // void setChannelState(ChannelState state); // // /** // * // * @param msg // * @param <T> // * @throws NullObjectException // * @throws IllegalChannelStateException // */ // <T>void broadcast(T msg) throws NullObjectException, IllegalChannelStateException; // // /** // * // * @param subscriber // * @param subscriberId // * @param <T> // * @return // * @throws NullObjectException // * @throws AlreadyExistsException // * @throws IllegalChannelStateException // */ // <T> T addSubscriber(T subscriber, Integer subscriberId) throws NullObjectException, AlreadyExistsException, IllegalChannelStateException; // // /** // * // * @param subscriber // * @param <T> // * @throws NullObjectException // * @throws InvalidSubscriberException // */ // <T> void removeSubscriber(T subscriber) throws NullObjectException, InvalidSubscriberException; // // <T, P extends Post<?, ?>>boolean deliverMessage(T subscriber, OnMessage msgAnnotation, Method method, P post); // // /** // * // * @return // */ // Collection<? extends WeakReference<?>> getAllSubscribersReferenceList(); // } // Path: jpost/src/main/java/com/mindorks/jpost/core/OnMessage.java import com.mindorks.jpost.core.Channel; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 23/09/16. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface OnMessage {
int channelId() default Channel.DEFAULT_CHANNEL_ID;
janishar/JPost
jpost/src/main/java/com/mindorks/jpost/core/CustomChannel.java
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // }
import com.mindorks.jpost.exceptions.IllegalChannelStateException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.ref.WeakReference; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue;
/* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public interface CustomChannel<Q extends PriorityBlockingQueue<? extends WeakReference<? extends ChannelPost>>, M extends ConcurrentHashMap<? extends Integer,? extends WeakReference<?>>> extends Channel<Q, M>{ void terminateChannel(); void startChannel(); void stopChannel(); /** * * @param msg * @param subscriberIds * @param <T> * @throws NullObjectException * @throws IllegalChannelStateException */
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // } // Path: jpost/src/main/java/com/mindorks/jpost/core/CustomChannel.java import com.mindorks.jpost.exceptions.IllegalChannelStateException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.ref.WeakReference; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue; /* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public interface CustomChannel<Q extends PriorityBlockingQueue<? extends WeakReference<? extends ChannelPost>>, M extends ConcurrentHashMap<? extends Integer,? extends WeakReference<?>>> extends Channel<Q, M>{ void terminateChannel(); void startChannel(); void stopChannel(); /** * * @param msg * @param subscriberIds * @param <T> * @throws NullObjectException * @throws IllegalChannelStateException */
<T>void broadcast(T msg, Integer... subscriberIds) throws NullObjectException, IllegalChannelStateException;
janishar/JPost
jpost/src/main/java/com/mindorks/jpost/core/CustomChannel.java
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // }
import com.mindorks.jpost.exceptions.IllegalChannelStateException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.ref.WeakReference; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue;
/* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public interface CustomChannel<Q extends PriorityBlockingQueue<? extends WeakReference<? extends ChannelPost>>, M extends ConcurrentHashMap<? extends Integer,? extends WeakReference<?>>> extends Channel<Q, M>{ void terminateChannel(); void startChannel(); void stopChannel(); /** * * @param msg * @param subscriberIds * @param <T> * @throws NullObjectException * @throws IllegalChannelStateException */
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // } // Path: jpost/src/main/java/com/mindorks/jpost/core/CustomChannel.java import com.mindorks.jpost.exceptions.IllegalChannelStateException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.ref.WeakReference; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue; /* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public interface CustomChannel<Q extends PriorityBlockingQueue<? extends WeakReference<? extends ChannelPost>>, M extends ConcurrentHashMap<? extends Integer,? extends WeakReference<?>>> extends Channel<Q, M>{ void terminateChannel(); void startChannel(); void stopChannel(); /** * * @param msg * @param subscriberIds * @param <T> * @throws NullObjectException * @throws IllegalChannelStateException */
<T>void broadcast(T msg, Integer... subscriberIds) throws NullObjectException, IllegalChannelStateException;
janishar/JPost
jpost/src/main/java/com/mindorks/jpost/core/PublicChannel.java
// Path: jpost/src/main/java/com/mindorks/jpost/core/ChannelPost.java // public class ChannelPost<T, V> implements Post<T, V> { // // private T message; // private V sender; // private Integer channelId; // private Integer priority; // private Object[] receivers; // private boolean isSerialised; // private String className; // // public ChannelPost(T message, Integer channelId, Integer priority) { // this.message = message; // this.channelId = channelId; // this.priority = priority; // } // // public ChannelPost(T message, Integer channelId, Integer priority, boolean isSerialised, String className) { // this.message = message; // this.channelId = channelId; // this.priority = priority; // this.isSerialised = isSerialised; // this.className = className; // } // // @Override // public void setMessage(T message){ // this.message = message; // } // // @Override // public T getMessage() { // return message; // } // // @Override // public void setPriority(Integer priority){ // this.priority = priority; // } // // @Override // public Integer getPriority() { // return priority; // } // // @Override // public V getSender() throws NullObjectException { // return sender; // } // // @Override // public void setSender(V sender) { // this.sender = sender; // } // // @Override // public void setReceivers(Object... receivers){ // this.receivers = receivers; // } // // @Override // public Object[] getReceiversList() { // return receivers; // } // // @Override // public void setIsSerialised(boolean isSerialised) { // this.isSerialised = isSerialised; // } // // @Override // public boolean isSerialised() { // return isSerialised; // } // // @Override // public void setSerialisedClassName(String className){ // this.className = className; // } // // @Override // public String getSerialisedClassName() { // return className; // } // // public Integer getChannelId() { // return channelId; // } // // public void setChannelId(Integer channelId){ // this.channelId = channelId; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // }
import com.mindorks.jpost.core.OnMessage; import com.mindorks.jpost.core.*; import com.mindorks.jpost.core.ChannelPost; import com.mindorks.jpost.exceptions.IllegalChannelStateException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue;
/* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public class PublicChannel< Q extends PriorityBlockingQueue<WeakReference<ChannelPost>>, M extends ConcurrentHashMap<Integer,WeakReference<Object>>> extends DefaultChannel<Q,M> implements CustomChannel<Q,M>{ public PublicChannel(Integer channelId, ChannelState state, ChannelType type, Q postQueue, M subscriberMap) { super(channelId, state, type, postQueue, subscriberMap); } @Override public void terminateChannel() { super.setChannelState(ChannelState.TERMINATED); super.getSubscriberMap().clear(); super.getPostQueue().clear(); } @Override public void startChannel() { super.setChannelState(ChannelState.OPEN); } @Override public void stopChannel() { super.setChannelState(ChannelState.STOPPED); } @Override
// Path: jpost/src/main/java/com/mindorks/jpost/core/ChannelPost.java // public class ChannelPost<T, V> implements Post<T, V> { // // private T message; // private V sender; // private Integer channelId; // private Integer priority; // private Object[] receivers; // private boolean isSerialised; // private String className; // // public ChannelPost(T message, Integer channelId, Integer priority) { // this.message = message; // this.channelId = channelId; // this.priority = priority; // } // // public ChannelPost(T message, Integer channelId, Integer priority, boolean isSerialised, String className) { // this.message = message; // this.channelId = channelId; // this.priority = priority; // this.isSerialised = isSerialised; // this.className = className; // } // // @Override // public void setMessage(T message){ // this.message = message; // } // // @Override // public T getMessage() { // return message; // } // // @Override // public void setPriority(Integer priority){ // this.priority = priority; // } // // @Override // public Integer getPriority() { // return priority; // } // // @Override // public V getSender() throws NullObjectException { // return sender; // } // // @Override // public void setSender(V sender) { // this.sender = sender; // } // // @Override // public void setReceivers(Object... receivers){ // this.receivers = receivers; // } // // @Override // public Object[] getReceiversList() { // return receivers; // } // // @Override // public void setIsSerialised(boolean isSerialised) { // this.isSerialised = isSerialised; // } // // @Override // public boolean isSerialised() { // return isSerialised; // } // // @Override // public void setSerialisedClassName(String className){ // this.className = className; // } // // @Override // public String getSerialisedClassName() { // return className; // } // // public Integer getChannelId() { // return channelId; // } // // public void setChannelId(Integer channelId){ // this.channelId = channelId; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // } // Path: jpost/src/main/java/com/mindorks/jpost/core/PublicChannel.java import com.mindorks.jpost.core.OnMessage; import com.mindorks.jpost.core.*; import com.mindorks.jpost.core.ChannelPost; import com.mindorks.jpost.exceptions.IllegalChannelStateException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue; /* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public class PublicChannel< Q extends PriorityBlockingQueue<WeakReference<ChannelPost>>, M extends ConcurrentHashMap<Integer,WeakReference<Object>>> extends DefaultChannel<Q,M> implements CustomChannel<Q,M>{ public PublicChannel(Integer channelId, ChannelState state, ChannelType type, Q postQueue, M subscriberMap) { super(channelId, state, type, postQueue, subscriberMap); } @Override public void terminateChannel() { super.setChannelState(ChannelState.TERMINATED); super.getSubscriberMap().clear(); super.getPostQueue().clear(); } @Override public void startChannel() { super.setChannelState(ChannelState.OPEN); } @Override public void stopChannel() { super.setChannelState(ChannelState.STOPPED); } @Override
public <T> void broadcast(T msg, Integer... subscriberIds) throws NullObjectException, IllegalChannelStateException {
janishar/JPost
jpost/src/main/java/com/mindorks/jpost/core/PublicChannel.java
// Path: jpost/src/main/java/com/mindorks/jpost/core/ChannelPost.java // public class ChannelPost<T, V> implements Post<T, V> { // // private T message; // private V sender; // private Integer channelId; // private Integer priority; // private Object[] receivers; // private boolean isSerialised; // private String className; // // public ChannelPost(T message, Integer channelId, Integer priority) { // this.message = message; // this.channelId = channelId; // this.priority = priority; // } // // public ChannelPost(T message, Integer channelId, Integer priority, boolean isSerialised, String className) { // this.message = message; // this.channelId = channelId; // this.priority = priority; // this.isSerialised = isSerialised; // this.className = className; // } // // @Override // public void setMessage(T message){ // this.message = message; // } // // @Override // public T getMessage() { // return message; // } // // @Override // public void setPriority(Integer priority){ // this.priority = priority; // } // // @Override // public Integer getPriority() { // return priority; // } // // @Override // public V getSender() throws NullObjectException { // return sender; // } // // @Override // public void setSender(V sender) { // this.sender = sender; // } // // @Override // public void setReceivers(Object... receivers){ // this.receivers = receivers; // } // // @Override // public Object[] getReceiversList() { // return receivers; // } // // @Override // public void setIsSerialised(boolean isSerialised) { // this.isSerialised = isSerialised; // } // // @Override // public boolean isSerialised() { // return isSerialised; // } // // @Override // public void setSerialisedClassName(String className){ // this.className = className; // } // // @Override // public String getSerialisedClassName() { // return className; // } // // public Integer getChannelId() { // return channelId; // } // // public void setChannelId(Integer channelId){ // this.channelId = channelId; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // }
import com.mindorks.jpost.core.OnMessage; import com.mindorks.jpost.core.*; import com.mindorks.jpost.core.ChannelPost; import com.mindorks.jpost.exceptions.IllegalChannelStateException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue;
/* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public class PublicChannel< Q extends PriorityBlockingQueue<WeakReference<ChannelPost>>, M extends ConcurrentHashMap<Integer,WeakReference<Object>>> extends DefaultChannel<Q,M> implements CustomChannel<Q,M>{ public PublicChannel(Integer channelId, ChannelState state, ChannelType type, Q postQueue, M subscriberMap) { super(channelId, state, type, postQueue, subscriberMap); } @Override public void terminateChannel() { super.setChannelState(ChannelState.TERMINATED); super.getSubscriberMap().clear(); super.getPostQueue().clear(); } @Override public void startChannel() { super.setChannelState(ChannelState.OPEN); } @Override public void stopChannel() { super.setChannelState(ChannelState.STOPPED); } @Override
// Path: jpost/src/main/java/com/mindorks/jpost/core/ChannelPost.java // public class ChannelPost<T, V> implements Post<T, V> { // // private T message; // private V sender; // private Integer channelId; // private Integer priority; // private Object[] receivers; // private boolean isSerialised; // private String className; // // public ChannelPost(T message, Integer channelId, Integer priority) { // this.message = message; // this.channelId = channelId; // this.priority = priority; // } // // public ChannelPost(T message, Integer channelId, Integer priority, boolean isSerialised, String className) { // this.message = message; // this.channelId = channelId; // this.priority = priority; // this.isSerialised = isSerialised; // this.className = className; // } // // @Override // public void setMessage(T message){ // this.message = message; // } // // @Override // public T getMessage() { // return message; // } // // @Override // public void setPriority(Integer priority){ // this.priority = priority; // } // // @Override // public Integer getPriority() { // return priority; // } // // @Override // public V getSender() throws NullObjectException { // return sender; // } // // @Override // public void setSender(V sender) { // this.sender = sender; // } // // @Override // public void setReceivers(Object... receivers){ // this.receivers = receivers; // } // // @Override // public Object[] getReceiversList() { // return receivers; // } // // @Override // public void setIsSerialised(boolean isSerialised) { // this.isSerialised = isSerialised; // } // // @Override // public boolean isSerialised() { // return isSerialised; // } // // @Override // public void setSerialisedClassName(String className){ // this.className = className; // } // // @Override // public String getSerialisedClassName() { // return className; // } // // public Integer getChannelId() { // return channelId; // } // // public void setChannelId(Integer channelId){ // this.channelId = channelId; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // } // Path: jpost/src/main/java/com/mindorks/jpost/core/PublicChannel.java import com.mindorks.jpost.core.OnMessage; import com.mindorks.jpost.core.*; import com.mindorks.jpost.core.ChannelPost; import com.mindorks.jpost.exceptions.IllegalChannelStateException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue; /* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public class PublicChannel< Q extends PriorityBlockingQueue<WeakReference<ChannelPost>>, M extends ConcurrentHashMap<Integer,WeakReference<Object>>> extends DefaultChannel<Q,M> implements CustomChannel<Q,M>{ public PublicChannel(Integer channelId, ChannelState state, ChannelType type, Q postQueue, M subscriberMap) { super(channelId, state, type, postQueue, subscriberMap); } @Override public void terminateChannel() { super.setChannelState(ChannelState.TERMINATED); super.getSubscriberMap().clear(); super.getPostQueue().clear(); } @Override public void startChannel() { super.setChannelState(ChannelState.OPEN); } @Override public void stopChannel() { super.setChannelState(ChannelState.STOPPED); } @Override
public <T> void broadcast(T msg, Integer... subscriberIds) throws NullObjectException, IllegalChannelStateException {
janishar/JPost
src/main/java/tes/mindorks/jpost/subscriber/SubscriberAsync.java
// Path: java-jpost/src/main/java/com/mindorks/javajpost/JPost.java // public class JPost { // // private static ReentrantLock JPostBootLock = new ReentrantLock(); // // private static ConcurrentHashMap<Integer, Channel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>> channelMap; // // private static BroadcastCenter broadcastCenter; // // private static DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>> channel; // // private static int threadCount; // private static ExecutorService executorService; // // static { // init(); // } // // private static void init(){ // threadCount = Runtime.getRuntime().availableProcessors() + 1; // executorService = Executors.newFixedThreadPool(threadCount); // channelMap = new ConcurrentHashMap<>(Broadcast.CHANNEL_INITIAL_CAPACITY); // channel = new DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>( // Channel.DEFAULT_CHANNEL_ID, // ChannelState.OPEN, // ChannelType.DEFAULT, // new PriorityBlockingQueue<>(Channel.MSG_QUEUE_INITIAL_CAPACITY, // new Comparator<WeakReference<ChannelPost>>() { // @Override // public int compare(WeakReference<ChannelPost> o1, WeakReference<ChannelPost> o2) { // ChannelPost post1 = o1.get(); // ChannelPost post2 = o2.get(); // if(post1 != null || post2 != null // || post1.getPriority() != null // || post2.getPriority() != null){ // return post1.getPriority().compareTo(post2.getPriority()); // }else{ // return 0; // } // } // }), // new ConcurrentHashMap<Integer,WeakReference<Object>>(Channel.SUBSCRIBER_INITIAL_CAPACITY)); // // channelMap.put(Channel.DEFAULT_CHANNEL_ID, channel); // broadcastCenter = new BroadcastCenter(channelMap, executorService); // } // // public static Broadcast getBroadcastCenter(){ // return broadcastCenter; // } // // public static void reboot(){ // JPostBootLock.lock(); // executorService = Executors.newFixedThreadPool(threadCount); // broadcastCenter.setExecutorService(executorService); // JPostBootLock.unlock(); // } // // public static void shutdown(){ // JPostBootLock.lock(); // executorService.shutdown(); // JPostBootLock.unlock(); // } // // public static void haltAndShutdown(){ // JPostBootLock.lock(); // executorService.shutdownNow(); // JPostBootLock.unlock(); // } // } // // Path: src/main/java/tes/mindorks/jpost/ChannelIds.java // public class ChannelIds { // // public static final int publicChannel1 = 1; // public static final int privateChannel1 = 2; // } // // Path: src/main/java/tes/mindorks/jpost/message/Message1.java // public class Message1 { // // private String msg; // // public Message1(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message1: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // // Path: src/main/java/tes/mindorks/jpost/message/Message2.java // public class Message2 { // // private String msg; // // public Message2(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message2: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // }
import com.mindorks.javajpost.JPost; import com.mindorks.jpost.core.OnMessage; import tes.mindorks.jpost.ChannelIds; import tes.mindorks.jpost.message.Message1; import tes.mindorks.jpost.message.Message2;
package tes.mindorks.jpost.subscriber; /** * Created by janisharali on 24/09/16. */ public class SubscriberAsync { private char classifier; public SubscriberAsync(char classifier) { this.classifier = classifier;
// Path: java-jpost/src/main/java/com/mindorks/javajpost/JPost.java // public class JPost { // // private static ReentrantLock JPostBootLock = new ReentrantLock(); // // private static ConcurrentHashMap<Integer, Channel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>> channelMap; // // private static BroadcastCenter broadcastCenter; // // private static DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>> channel; // // private static int threadCount; // private static ExecutorService executorService; // // static { // init(); // } // // private static void init(){ // threadCount = Runtime.getRuntime().availableProcessors() + 1; // executorService = Executors.newFixedThreadPool(threadCount); // channelMap = new ConcurrentHashMap<>(Broadcast.CHANNEL_INITIAL_CAPACITY); // channel = new DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>( // Channel.DEFAULT_CHANNEL_ID, // ChannelState.OPEN, // ChannelType.DEFAULT, // new PriorityBlockingQueue<>(Channel.MSG_QUEUE_INITIAL_CAPACITY, // new Comparator<WeakReference<ChannelPost>>() { // @Override // public int compare(WeakReference<ChannelPost> o1, WeakReference<ChannelPost> o2) { // ChannelPost post1 = o1.get(); // ChannelPost post2 = o2.get(); // if(post1 != null || post2 != null // || post1.getPriority() != null // || post2.getPriority() != null){ // return post1.getPriority().compareTo(post2.getPriority()); // }else{ // return 0; // } // } // }), // new ConcurrentHashMap<Integer,WeakReference<Object>>(Channel.SUBSCRIBER_INITIAL_CAPACITY)); // // channelMap.put(Channel.DEFAULT_CHANNEL_ID, channel); // broadcastCenter = new BroadcastCenter(channelMap, executorService); // } // // public static Broadcast getBroadcastCenter(){ // return broadcastCenter; // } // // public static void reboot(){ // JPostBootLock.lock(); // executorService = Executors.newFixedThreadPool(threadCount); // broadcastCenter.setExecutorService(executorService); // JPostBootLock.unlock(); // } // // public static void shutdown(){ // JPostBootLock.lock(); // executorService.shutdown(); // JPostBootLock.unlock(); // } // // public static void haltAndShutdown(){ // JPostBootLock.lock(); // executorService.shutdownNow(); // JPostBootLock.unlock(); // } // } // // Path: src/main/java/tes/mindorks/jpost/ChannelIds.java // public class ChannelIds { // // public static final int publicChannel1 = 1; // public static final int privateChannel1 = 2; // } // // Path: src/main/java/tes/mindorks/jpost/message/Message1.java // public class Message1 { // // private String msg; // // public Message1(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message1: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // // Path: src/main/java/tes/mindorks/jpost/message/Message2.java // public class Message2 { // // private String msg; // // public Message2(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message2: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // Path: src/main/java/tes/mindorks/jpost/subscriber/SubscriberAsync.java import com.mindorks.javajpost.JPost; import com.mindorks.jpost.core.OnMessage; import tes.mindorks.jpost.ChannelIds; import tes.mindorks.jpost.message.Message1; import tes.mindorks.jpost.message.Message2; package tes.mindorks.jpost.subscriber; /** * Created by janisharali on 24/09/16. */ public class SubscriberAsync { private char classifier; public SubscriberAsync(char classifier) { this.classifier = classifier;
JPost.getBroadcastCenter().addSubscriberAsync(this);
janishar/JPost
src/main/java/tes/mindorks/jpost/subscriber/SubscriberAsync.java
// Path: java-jpost/src/main/java/com/mindorks/javajpost/JPost.java // public class JPost { // // private static ReentrantLock JPostBootLock = new ReentrantLock(); // // private static ConcurrentHashMap<Integer, Channel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>> channelMap; // // private static BroadcastCenter broadcastCenter; // // private static DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>> channel; // // private static int threadCount; // private static ExecutorService executorService; // // static { // init(); // } // // private static void init(){ // threadCount = Runtime.getRuntime().availableProcessors() + 1; // executorService = Executors.newFixedThreadPool(threadCount); // channelMap = new ConcurrentHashMap<>(Broadcast.CHANNEL_INITIAL_CAPACITY); // channel = new DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>( // Channel.DEFAULT_CHANNEL_ID, // ChannelState.OPEN, // ChannelType.DEFAULT, // new PriorityBlockingQueue<>(Channel.MSG_QUEUE_INITIAL_CAPACITY, // new Comparator<WeakReference<ChannelPost>>() { // @Override // public int compare(WeakReference<ChannelPost> o1, WeakReference<ChannelPost> o2) { // ChannelPost post1 = o1.get(); // ChannelPost post2 = o2.get(); // if(post1 != null || post2 != null // || post1.getPriority() != null // || post2.getPriority() != null){ // return post1.getPriority().compareTo(post2.getPriority()); // }else{ // return 0; // } // } // }), // new ConcurrentHashMap<Integer,WeakReference<Object>>(Channel.SUBSCRIBER_INITIAL_CAPACITY)); // // channelMap.put(Channel.DEFAULT_CHANNEL_ID, channel); // broadcastCenter = new BroadcastCenter(channelMap, executorService); // } // // public static Broadcast getBroadcastCenter(){ // return broadcastCenter; // } // // public static void reboot(){ // JPostBootLock.lock(); // executorService = Executors.newFixedThreadPool(threadCount); // broadcastCenter.setExecutorService(executorService); // JPostBootLock.unlock(); // } // // public static void shutdown(){ // JPostBootLock.lock(); // executorService.shutdown(); // JPostBootLock.unlock(); // } // // public static void haltAndShutdown(){ // JPostBootLock.lock(); // executorService.shutdownNow(); // JPostBootLock.unlock(); // } // } // // Path: src/main/java/tes/mindorks/jpost/ChannelIds.java // public class ChannelIds { // // public static final int publicChannel1 = 1; // public static final int privateChannel1 = 2; // } // // Path: src/main/java/tes/mindorks/jpost/message/Message1.java // public class Message1 { // // private String msg; // // public Message1(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message1: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // // Path: src/main/java/tes/mindorks/jpost/message/Message2.java // public class Message2 { // // private String msg; // // public Message2(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message2: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // }
import com.mindorks.javajpost.JPost; import com.mindorks.jpost.core.OnMessage; import tes.mindorks.jpost.ChannelIds; import tes.mindorks.jpost.message.Message1; import tes.mindorks.jpost.message.Message2;
package tes.mindorks.jpost.subscriber; /** * Created by janisharali on 24/09/16. */ public class SubscriberAsync { private char classifier; public SubscriberAsync(char classifier) { this.classifier = classifier; JPost.getBroadcastCenter().addSubscriberAsync(this); } public SubscriberAsync(char classifier, int channelId) { this.classifier = classifier; JPost.getBroadcastCenter().addSubscriberAsync(channelId, this); } public SubscriberAsync(char classifier, int channelId, int subscriberId) { this.classifier = classifier; JPost.getBroadcastCenter().addSubscriberAsync(channelId, this, subscriberId); } public <T>SubscriberAsync(T owner, char classifier, int channelId, int subscriberId) { this.classifier = classifier; try { JPost.getBroadcastCenter().addSubscriberAsync(owner, channelId, this, subscriberId); }catch (Exception e){ e.printStackTrace(); } } public void subscribeAsync(){ JPost.getBroadcastCenter().addSubscriberAsync(this); } @OnMessage
// Path: java-jpost/src/main/java/com/mindorks/javajpost/JPost.java // public class JPost { // // private static ReentrantLock JPostBootLock = new ReentrantLock(); // // private static ConcurrentHashMap<Integer, Channel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>> channelMap; // // private static BroadcastCenter broadcastCenter; // // private static DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>> channel; // // private static int threadCount; // private static ExecutorService executorService; // // static { // init(); // } // // private static void init(){ // threadCount = Runtime.getRuntime().availableProcessors() + 1; // executorService = Executors.newFixedThreadPool(threadCount); // channelMap = new ConcurrentHashMap<>(Broadcast.CHANNEL_INITIAL_CAPACITY); // channel = new DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>( // Channel.DEFAULT_CHANNEL_ID, // ChannelState.OPEN, // ChannelType.DEFAULT, // new PriorityBlockingQueue<>(Channel.MSG_QUEUE_INITIAL_CAPACITY, // new Comparator<WeakReference<ChannelPost>>() { // @Override // public int compare(WeakReference<ChannelPost> o1, WeakReference<ChannelPost> o2) { // ChannelPost post1 = o1.get(); // ChannelPost post2 = o2.get(); // if(post1 != null || post2 != null // || post1.getPriority() != null // || post2.getPriority() != null){ // return post1.getPriority().compareTo(post2.getPriority()); // }else{ // return 0; // } // } // }), // new ConcurrentHashMap<Integer,WeakReference<Object>>(Channel.SUBSCRIBER_INITIAL_CAPACITY)); // // channelMap.put(Channel.DEFAULT_CHANNEL_ID, channel); // broadcastCenter = new BroadcastCenter(channelMap, executorService); // } // // public static Broadcast getBroadcastCenter(){ // return broadcastCenter; // } // // public static void reboot(){ // JPostBootLock.lock(); // executorService = Executors.newFixedThreadPool(threadCount); // broadcastCenter.setExecutorService(executorService); // JPostBootLock.unlock(); // } // // public static void shutdown(){ // JPostBootLock.lock(); // executorService.shutdown(); // JPostBootLock.unlock(); // } // // public static void haltAndShutdown(){ // JPostBootLock.lock(); // executorService.shutdownNow(); // JPostBootLock.unlock(); // } // } // // Path: src/main/java/tes/mindorks/jpost/ChannelIds.java // public class ChannelIds { // // public static final int publicChannel1 = 1; // public static final int privateChannel1 = 2; // } // // Path: src/main/java/tes/mindorks/jpost/message/Message1.java // public class Message1 { // // private String msg; // // public Message1(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message1: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // // Path: src/main/java/tes/mindorks/jpost/message/Message2.java // public class Message2 { // // private String msg; // // public Message2(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message2: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // Path: src/main/java/tes/mindorks/jpost/subscriber/SubscriberAsync.java import com.mindorks.javajpost.JPost; import com.mindorks.jpost.core.OnMessage; import tes.mindorks.jpost.ChannelIds; import tes.mindorks.jpost.message.Message1; import tes.mindorks.jpost.message.Message2; package tes.mindorks.jpost.subscriber; /** * Created by janisharali on 24/09/16. */ public class SubscriberAsync { private char classifier; public SubscriberAsync(char classifier) { this.classifier = classifier; JPost.getBroadcastCenter().addSubscriberAsync(this); } public SubscriberAsync(char classifier, int channelId) { this.classifier = classifier; JPost.getBroadcastCenter().addSubscriberAsync(channelId, this); } public SubscriberAsync(char classifier, int channelId, int subscriberId) { this.classifier = classifier; JPost.getBroadcastCenter().addSubscriberAsync(channelId, this, subscriberId); } public <T>SubscriberAsync(T owner, char classifier, int channelId, int subscriberId) { this.classifier = classifier; try { JPost.getBroadcastCenter().addSubscriberAsync(owner, channelId, this, subscriberId); }catch (Exception e){ e.printStackTrace(); } } public void subscribeAsync(){ JPost.getBroadcastCenter().addSubscriberAsync(this); } @OnMessage
private void onMessage1(Message1 msg){
janishar/JPost
src/main/java/tes/mindorks/jpost/subscriber/SubscriberAsync.java
// Path: java-jpost/src/main/java/com/mindorks/javajpost/JPost.java // public class JPost { // // private static ReentrantLock JPostBootLock = new ReentrantLock(); // // private static ConcurrentHashMap<Integer, Channel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>> channelMap; // // private static BroadcastCenter broadcastCenter; // // private static DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>> channel; // // private static int threadCount; // private static ExecutorService executorService; // // static { // init(); // } // // private static void init(){ // threadCount = Runtime.getRuntime().availableProcessors() + 1; // executorService = Executors.newFixedThreadPool(threadCount); // channelMap = new ConcurrentHashMap<>(Broadcast.CHANNEL_INITIAL_CAPACITY); // channel = new DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>( // Channel.DEFAULT_CHANNEL_ID, // ChannelState.OPEN, // ChannelType.DEFAULT, // new PriorityBlockingQueue<>(Channel.MSG_QUEUE_INITIAL_CAPACITY, // new Comparator<WeakReference<ChannelPost>>() { // @Override // public int compare(WeakReference<ChannelPost> o1, WeakReference<ChannelPost> o2) { // ChannelPost post1 = o1.get(); // ChannelPost post2 = o2.get(); // if(post1 != null || post2 != null // || post1.getPriority() != null // || post2.getPriority() != null){ // return post1.getPriority().compareTo(post2.getPriority()); // }else{ // return 0; // } // } // }), // new ConcurrentHashMap<Integer,WeakReference<Object>>(Channel.SUBSCRIBER_INITIAL_CAPACITY)); // // channelMap.put(Channel.DEFAULT_CHANNEL_ID, channel); // broadcastCenter = new BroadcastCenter(channelMap, executorService); // } // // public static Broadcast getBroadcastCenter(){ // return broadcastCenter; // } // // public static void reboot(){ // JPostBootLock.lock(); // executorService = Executors.newFixedThreadPool(threadCount); // broadcastCenter.setExecutorService(executorService); // JPostBootLock.unlock(); // } // // public static void shutdown(){ // JPostBootLock.lock(); // executorService.shutdown(); // JPostBootLock.unlock(); // } // // public static void haltAndShutdown(){ // JPostBootLock.lock(); // executorService.shutdownNow(); // JPostBootLock.unlock(); // } // } // // Path: src/main/java/tes/mindorks/jpost/ChannelIds.java // public class ChannelIds { // // public static final int publicChannel1 = 1; // public static final int privateChannel1 = 2; // } // // Path: src/main/java/tes/mindorks/jpost/message/Message1.java // public class Message1 { // // private String msg; // // public Message1(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message1: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // // Path: src/main/java/tes/mindorks/jpost/message/Message2.java // public class Message2 { // // private String msg; // // public Message2(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message2: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // }
import com.mindorks.javajpost.JPost; import com.mindorks.jpost.core.OnMessage; import tes.mindorks.jpost.ChannelIds; import tes.mindorks.jpost.message.Message1; import tes.mindorks.jpost.message.Message2;
package tes.mindorks.jpost.subscriber; /** * Created by janisharali on 24/09/16. */ public class SubscriberAsync { private char classifier; public SubscriberAsync(char classifier) { this.classifier = classifier; JPost.getBroadcastCenter().addSubscriberAsync(this); } public SubscriberAsync(char classifier, int channelId) { this.classifier = classifier; JPost.getBroadcastCenter().addSubscriberAsync(channelId, this); } public SubscriberAsync(char classifier, int channelId, int subscriberId) { this.classifier = classifier; JPost.getBroadcastCenter().addSubscriberAsync(channelId, this, subscriberId); } public <T>SubscriberAsync(T owner, char classifier, int channelId, int subscriberId) { this.classifier = classifier; try { JPost.getBroadcastCenter().addSubscriberAsync(owner, channelId, this, subscriberId); }catch (Exception e){ e.printStackTrace(); } } public void subscribeAsync(){ JPost.getBroadcastCenter().addSubscriberAsync(this); } @OnMessage private void onMessage1(Message1 msg){ System.out.println("SubscriberAsync" + classifier + ": "+ msg.getMsg()); }
// Path: java-jpost/src/main/java/com/mindorks/javajpost/JPost.java // public class JPost { // // private static ReentrantLock JPostBootLock = new ReentrantLock(); // // private static ConcurrentHashMap<Integer, Channel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>> channelMap; // // private static BroadcastCenter broadcastCenter; // // private static DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>> channel; // // private static int threadCount; // private static ExecutorService executorService; // // static { // init(); // } // // private static void init(){ // threadCount = Runtime.getRuntime().availableProcessors() + 1; // executorService = Executors.newFixedThreadPool(threadCount); // channelMap = new ConcurrentHashMap<>(Broadcast.CHANNEL_INITIAL_CAPACITY); // channel = new DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>( // Channel.DEFAULT_CHANNEL_ID, // ChannelState.OPEN, // ChannelType.DEFAULT, // new PriorityBlockingQueue<>(Channel.MSG_QUEUE_INITIAL_CAPACITY, // new Comparator<WeakReference<ChannelPost>>() { // @Override // public int compare(WeakReference<ChannelPost> o1, WeakReference<ChannelPost> o2) { // ChannelPost post1 = o1.get(); // ChannelPost post2 = o2.get(); // if(post1 != null || post2 != null // || post1.getPriority() != null // || post2.getPriority() != null){ // return post1.getPriority().compareTo(post2.getPriority()); // }else{ // return 0; // } // } // }), // new ConcurrentHashMap<Integer,WeakReference<Object>>(Channel.SUBSCRIBER_INITIAL_CAPACITY)); // // channelMap.put(Channel.DEFAULT_CHANNEL_ID, channel); // broadcastCenter = new BroadcastCenter(channelMap, executorService); // } // // public static Broadcast getBroadcastCenter(){ // return broadcastCenter; // } // // public static void reboot(){ // JPostBootLock.lock(); // executorService = Executors.newFixedThreadPool(threadCount); // broadcastCenter.setExecutorService(executorService); // JPostBootLock.unlock(); // } // // public static void shutdown(){ // JPostBootLock.lock(); // executorService.shutdown(); // JPostBootLock.unlock(); // } // // public static void haltAndShutdown(){ // JPostBootLock.lock(); // executorService.shutdownNow(); // JPostBootLock.unlock(); // } // } // // Path: src/main/java/tes/mindorks/jpost/ChannelIds.java // public class ChannelIds { // // public static final int publicChannel1 = 1; // public static final int privateChannel1 = 2; // } // // Path: src/main/java/tes/mindorks/jpost/message/Message1.java // public class Message1 { // // private String msg; // // public Message1(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message1: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // // Path: src/main/java/tes/mindorks/jpost/message/Message2.java // public class Message2 { // // private String msg; // // public Message2(String msg) { // this.msg = msg; // } // // public String getMsg() { // return "Message2: " + msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // } // Path: src/main/java/tes/mindorks/jpost/subscriber/SubscriberAsync.java import com.mindorks.javajpost.JPost; import com.mindorks.jpost.core.OnMessage; import tes.mindorks.jpost.ChannelIds; import tes.mindorks.jpost.message.Message1; import tes.mindorks.jpost.message.Message2; package tes.mindorks.jpost.subscriber; /** * Created by janisharali on 24/09/16. */ public class SubscriberAsync { private char classifier; public SubscriberAsync(char classifier) { this.classifier = classifier; JPost.getBroadcastCenter().addSubscriberAsync(this); } public SubscriberAsync(char classifier, int channelId) { this.classifier = classifier; JPost.getBroadcastCenter().addSubscriberAsync(channelId, this); } public SubscriberAsync(char classifier, int channelId, int subscriberId) { this.classifier = classifier; JPost.getBroadcastCenter().addSubscriberAsync(channelId, this, subscriberId); } public <T>SubscriberAsync(T owner, char classifier, int channelId, int subscriberId) { this.classifier = classifier; try { JPost.getBroadcastCenter().addSubscriberAsync(owner, channelId, this, subscriberId); }catch (Exception e){ e.printStackTrace(); } } public void subscribeAsync(){ JPost.getBroadcastCenter().addSubscriberAsync(this); } @OnMessage private void onMessage1(Message1 msg){ System.out.println("SubscriberAsync" + classifier + ": "+ msg.getMsg()); }
@OnMessage(channelId = ChannelIds.publicChannel1)
janishar/JPost
jpost/src/main/java/com/mindorks/jpost/core/BroadcastCenter.java
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // }
import com.mindorks.jpost.core.*; import com.mindorks.jpost.exceptions.*; import com.mindorks.jpost.exceptions.IllegalChannelStateException; import java.lang.ref.WeakReference; import java.util.Comparator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.PriorityBlockingQueue;
try { PrivateChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, ConcurrentHashMap<Integer, WeakReference<Object>>> privateChannel = new PrivateChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, ConcurrentHashMap<Integer,WeakReference<Object>>>( channelId, ChannelState.OPEN, ChannelType.PRIVATE, new PriorityBlockingQueue<>(Channel.MSG_QUEUE_INITIAL_CAPACITY, new Comparator<WeakReference<ChannelPost>>() { @Override public int compare(WeakReference<ChannelPost> o1, WeakReference<ChannelPost> o2) { ChannelPost post1 = o1.get(); ChannelPost post2 = o2.get(); if(post1 != null || post2 != null || post1.getPriority() != null || post2.getPriority() != null){ return post1.getPriority().compareTo(post2.getPriority()); }else{ return 0; } } }), new ConcurrentHashMap<Integer,WeakReference<Object>>(Channel.SUBSCRIBER_INITIAL_CAPACITY), new WeakReference<Object>(owner)); getChannelMap().put(channelId, privateChannel); runPrivateSubscriptionTask(owner, channelId, owner, owner.hashCode()); return privateChannel;
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // Path: jpost/src/main/java/com/mindorks/jpost/core/BroadcastCenter.java import com.mindorks.jpost.core.*; import com.mindorks.jpost.exceptions.*; import com.mindorks.jpost.exceptions.IllegalChannelStateException; import java.lang.ref.WeakReference; import java.util.Comparator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.PriorityBlockingQueue; try { PrivateChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, ConcurrentHashMap<Integer, WeakReference<Object>>> privateChannel = new PrivateChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, ConcurrentHashMap<Integer,WeakReference<Object>>>( channelId, ChannelState.OPEN, ChannelType.PRIVATE, new PriorityBlockingQueue<>(Channel.MSG_QUEUE_INITIAL_CAPACITY, new Comparator<WeakReference<ChannelPost>>() { @Override public int compare(WeakReference<ChannelPost> o1, WeakReference<ChannelPost> o2) { ChannelPost post1 = o1.get(); ChannelPost post2 = o2.get(); if(post1 != null || post2 != null || post1.getPriority() != null || post2.getPriority() != null){ return post1.getPriority().compareTo(post2.getPriority()); }else{ return 0; } } }), new ConcurrentHashMap<Integer,WeakReference<Object>>(Channel.SUBSCRIBER_INITIAL_CAPACITY), new WeakReference<Object>(owner)); getChannelMap().put(channelId, privateChannel); runPrivateSubscriptionTask(owner, channelId, owner, owner.hashCode()); return privateChannel;
}catch (IllegalChannelStateException | PermissionException| NullObjectException| NoSuchChannelException e){
janishar/JPost
src/main/java/tes/mindorks/jpost/Application.java
// Path: java-jpost/src/main/java/com/mindorks/javajpost/JPost.java // public class JPost { // // private static ReentrantLock JPostBootLock = new ReentrantLock(); // // private static ConcurrentHashMap<Integer, Channel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>> channelMap; // // private static BroadcastCenter broadcastCenter; // // private static DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>> channel; // // private static int threadCount; // private static ExecutorService executorService; // // static { // init(); // } // // private static void init(){ // threadCount = Runtime.getRuntime().availableProcessors() + 1; // executorService = Executors.newFixedThreadPool(threadCount); // channelMap = new ConcurrentHashMap<>(Broadcast.CHANNEL_INITIAL_CAPACITY); // channel = new DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>( // Channel.DEFAULT_CHANNEL_ID, // ChannelState.OPEN, // ChannelType.DEFAULT, // new PriorityBlockingQueue<>(Channel.MSG_QUEUE_INITIAL_CAPACITY, // new Comparator<WeakReference<ChannelPost>>() { // @Override // public int compare(WeakReference<ChannelPost> o1, WeakReference<ChannelPost> o2) { // ChannelPost post1 = o1.get(); // ChannelPost post2 = o2.get(); // if(post1 != null || post2 != null // || post1.getPriority() != null // || post2.getPriority() != null){ // return post1.getPriority().compareTo(post2.getPriority()); // }else{ // return 0; // } // } // }), // new ConcurrentHashMap<Integer,WeakReference<Object>>(Channel.SUBSCRIBER_INITIAL_CAPACITY)); // // channelMap.put(Channel.DEFAULT_CHANNEL_ID, channel); // broadcastCenter = new BroadcastCenter(channelMap, executorService); // } // // public static Broadcast getBroadcastCenter(){ // return broadcastCenter; // } // // public static void reboot(){ // JPostBootLock.lock(); // executorService = Executors.newFixedThreadPool(threadCount); // broadcastCenter.setExecutorService(executorService); // JPostBootLock.unlock(); // } // // public static void shutdown(){ // JPostBootLock.lock(); // executorService.shutdown(); // JPostBootLock.unlock(); // } // // public static void haltAndShutdown(){ // JPostBootLock.lock(); // executorService.shutdownNow(); // JPostBootLock.unlock(); // } // }
import com.mindorks.javajpost.JPost;
package tes.mindorks.jpost; /** * Created by janisharali on 30/09/16. */ public class Application { public static void main(String[] args){ System.out.println(".......................DEFAULT CHANNEL TEST START.............................."); TestDefaultChannel.test(); try { Thread.sleep(3000); System.out.println(".......................DEFAULT CHANNEL TEST END..............................");
// Path: java-jpost/src/main/java/com/mindorks/javajpost/JPost.java // public class JPost { // // private static ReentrantLock JPostBootLock = new ReentrantLock(); // // private static ConcurrentHashMap<Integer, Channel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>> channelMap; // // private static BroadcastCenter broadcastCenter; // // private static DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>> channel; // // private static int threadCount; // private static ExecutorService executorService; // // static { // init(); // } // // private static void init(){ // threadCount = Runtime.getRuntime().availableProcessors() + 1; // executorService = Executors.newFixedThreadPool(threadCount); // channelMap = new ConcurrentHashMap<>(Broadcast.CHANNEL_INITIAL_CAPACITY); // channel = new DefaultChannel<PriorityBlockingQueue<WeakReference<ChannelPost>>, // ConcurrentHashMap<Integer,WeakReference<Object>>>( // Channel.DEFAULT_CHANNEL_ID, // ChannelState.OPEN, // ChannelType.DEFAULT, // new PriorityBlockingQueue<>(Channel.MSG_QUEUE_INITIAL_CAPACITY, // new Comparator<WeakReference<ChannelPost>>() { // @Override // public int compare(WeakReference<ChannelPost> o1, WeakReference<ChannelPost> o2) { // ChannelPost post1 = o1.get(); // ChannelPost post2 = o2.get(); // if(post1 != null || post2 != null // || post1.getPriority() != null // || post2.getPriority() != null){ // return post1.getPriority().compareTo(post2.getPriority()); // }else{ // return 0; // } // } // }), // new ConcurrentHashMap<Integer,WeakReference<Object>>(Channel.SUBSCRIBER_INITIAL_CAPACITY)); // // channelMap.put(Channel.DEFAULT_CHANNEL_ID, channel); // broadcastCenter = new BroadcastCenter(channelMap, executorService); // } // // public static Broadcast getBroadcastCenter(){ // return broadcastCenter; // } // // public static void reboot(){ // JPostBootLock.lock(); // executorService = Executors.newFixedThreadPool(threadCount); // broadcastCenter.setExecutorService(executorService); // JPostBootLock.unlock(); // } // // public static void shutdown(){ // JPostBootLock.lock(); // executorService.shutdown(); // JPostBootLock.unlock(); // } // // public static void haltAndShutdown(){ // JPostBootLock.lock(); // executorService.shutdownNow(); // JPostBootLock.unlock(); // } // } // Path: src/main/java/tes/mindorks/jpost/Application.java import com.mindorks.javajpost.JPost; package tes.mindorks.jpost; /** * Created by janisharali on 30/09/16. */ public class Application { public static void main(String[] args){ System.out.println(".......................DEFAULT CHANNEL TEST START.............................."); TestDefaultChannel.test(); try { Thread.sleep(3000); System.out.println(".......................DEFAULT CHANNEL TEST END..............................");
JPost.shutdown();
janishar/JPost
jpost/src/main/java/com/mindorks/jpost/core/DefaultChannel.java
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/AlreadyExistsException.java // public class AlreadyExistsException extends Exception{ // // public AlreadyExistsException(String message) { // super(message); // } // // public String toString() { // return "AlreadyExistsException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/InvalidSubscriberException.java // public class InvalidSubscriberException extends Exception{ // // public InvalidSubscriberException(String message) { // super(message); // } // // public String toString() { // return "InvalidSubscriberException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // }
import com.mindorks.jpost.exceptions.AlreadyExistsException; import com.mindorks.jpost.exceptions.IllegalChannelStateException; import com.mindorks.jpost.exceptions.InvalidSubscriberException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue;
/* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public class DefaultChannel< Q extends PriorityBlockingQueue<WeakReference<ChannelPost>>, M extends ConcurrentHashMap<Integer,WeakReference<Object>>> extends AbstractChannel<Q,M> { public DefaultChannel(Integer channelId, ChannelState state, ChannelType type, Q postQueue, M subscriberMap) { super(channelId, state, type, postQueue, subscriberMap); } @Override
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/AlreadyExistsException.java // public class AlreadyExistsException extends Exception{ // // public AlreadyExistsException(String message) { // super(message); // } // // public String toString() { // return "AlreadyExistsException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/InvalidSubscriberException.java // public class InvalidSubscriberException extends Exception{ // // public InvalidSubscriberException(String message) { // super(message); // } // // public String toString() { // return "InvalidSubscriberException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // } // Path: jpost/src/main/java/com/mindorks/jpost/core/DefaultChannel.java import com.mindorks.jpost.exceptions.AlreadyExistsException; import com.mindorks.jpost.exceptions.IllegalChannelStateException; import com.mindorks.jpost.exceptions.InvalidSubscriberException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue; /* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public class DefaultChannel< Q extends PriorityBlockingQueue<WeakReference<ChannelPost>>, M extends ConcurrentHashMap<Integer,WeakReference<Object>>> extends AbstractChannel<Q,M> { public DefaultChannel(Integer channelId, ChannelState state, ChannelType type, Q postQueue, M subscriberMap) { super(channelId, state, type, postQueue, subscriberMap); } @Override
public <T> void broadcast(T msg) throws NullObjectException, IllegalChannelStateException {
janishar/JPost
jpost/src/main/java/com/mindorks/jpost/core/DefaultChannel.java
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/AlreadyExistsException.java // public class AlreadyExistsException extends Exception{ // // public AlreadyExistsException(String message) { // super(message); // } // // public String toString() { // return "AlreadyExistsException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/InvalidSubscriberException.java // public class InvalidSubscriberException extends Exception{ // // public InvalidSubscriberException(String message) { // super(message); // } // // public String toString() { // return "InvalidSubscriberException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // }
import com.mindorks.jpost.exceptions.AlreadyExistsException; import com.mindorks.jpost.exceptions.IllegalChannelStateException; import com.mindorks.jpost.exceptions.InvalidSubscriberException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue;
/* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public class DefaultChannel< Q extends PriorityBlockingQueue<WeakReference<ChannelPost>>, M extends ConcurrentHashMap<Integer,WeakReference<Object>>> extends AbstractChannel<Q,M> { public DefaultChannel(Integer channelId, ChannelState state, ChannelType type, Q postQueue, M subscriberMap) { super(channelId, state, type, postQueue, subscriberMap); } @Override
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/AlreadyExistsException.java // public class AlreadyExistsException extends Exception{ // // public AlreadyExistsException(String message) { // super(message); // } // // public String toString() { // return "AlreadyExistsException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/InvalidSubscriberException.java // public class InvalidSubscriberException extends Exception{ // // public InvalidSubscriberException(String message) { // super(message); // } // // public String toString() { // return "InvalidSubscriberException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // } // Path: jpost/src/main/java/com/mindorks/jpost/core/DefaultChannel.java import com.mindorks.jpost.exceptions.AlreadyExistsException; import com.mindorks.jpost.exceptions.IllegalChannelStateException; import com.mindorks.jpost.exceptions.InvalidSubscriberException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue; /* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public class DefaultChannel< Q extends PriorityBlockingQueue<WeakReference<ChannelPost>>, M extends ConcurrentHashMap<Integer,WeakReference<Object>>> extends AbstractChannel<Q,M> { public DefaultChannel(Integer channelId, ChannelState state, ChannelType type, Q postQueue, M subscriberMap) { super(channelId, state, type, postQueue, subscriberMap); } @Override
public <T> void broadcast(T msg) throws NullObjectException, IllegalChannelStateException {
janishar/JPost
jpost/src/main/java/com/mindorks/jpost/core/DefaultChannel.java
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/AlreadyExistsException.java // public class AlreadyExistsException extends Exception{ // // public AlreadyExistsException(String message) { // super(message); // } // // public String toString() { // return "AlreadyExistsException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/InvalidSubscriberException.java // public class InvalidSubscriberException extends Exception{ // // public InvalidSubscriberException(String message) { // super(message); // } // // public String toString() { // return "InvalidSubscriberException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // }
import com.mindorks.jpost.exceptions.AlreadyExistsException; import com.mindorks.jpost.exceptions.IllegalChannelStateException; import com.mindorks.jpost.exceptions.InvalidSubscriberException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue;
} } @Override public <T, P extends Post<?, ?>> boolean deliverMessage(T subscriber, OnMessage msgAnnotation, Method method, P post) { int channelId = msgAnnotation.channelId(); boolean isCommonReceiver = msgAnnotation.isCommonReceiver(); if (isCommonReceiver || getChannelId().equals(channelId)) { try { boolean methodFound = false; for (final Class paramClass : method.getParameterTypes()) { if (paramClass.equals(post.getMessage().getClass())) { methodFound = true; break; } } if (methodFound) { method.setAccessible(true); method.invoke(subscriber, post.getMessage()); } return true; } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } return false; } @Override public <T> T addSubscriber(T subscriber, Integer subscriberId )
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/AlreadyExistsException.java // public class AlreadyExistsException extends Exception{ // // public AlreadyExistsException(String message) { // super(message); // } // // public String toString() { // return "AlreadyExistsException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/InvalidSubscriberException.java // public class InvalidSubscriberException extends Exception{ // // public InvalidSubscriberException(String message) { // super(message); // } // // public String toString() { // return "InvalidSubscriberException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // } // Path: jpost/src/main/java/com/mindorks/jpost/core/DefaultChannel.java import com.mindorks.jpost.exceptions.AlreadyExistsException; import com.mindorks.jpost.exceptions.IllegalChannelStateException; import com.mindorks.jpost.exceptions.InvalidSubscriberException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue; } } @Override public <T, P extends Post<?, ?>> boolean deliverMessage(T subscriber, OnMessage msgAnnotation, Method method, P post) { int channelId = msgAnnotation.channelId(); boolean isCommonReceiver = msgAnnotation.isCommonReceiver(); if (isCommonReceiver || getChannelId().equals(channelId)) { try { boolean methodFound = false; for (final Class paramClass : method.getParameterTypes()) { if (paramClass.equals(post.getMessage().getClass())) { methodFound = true; break; } } if (methodFound) { method.setAccessible(true); method.invoke(subscriber, post.getMessage()); } return true; } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } return false; } @Override public <T> T addSubscriber(T subscriber, Integer subscriberId )
throws NullObjectException, AlreadyExistsException, IllegalChannelStateException {
janishar/JPost
jpost/src/main/java/com/mindorks/jpost/core/DefaultChannel.java
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/AlreadyExistsException.java // public class AlreadyExistsException extends Exception{ // // public AlreadyExistsException(String message) { // super(message); // } // // public String toString() { // return "AlreadyExistsException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/InvalidSubscriberException.java // public class InvalidSubscriberException extends Exception{ // // public InvalidSubscriberException(String message) { // super(message); // } // // public String toString() { // return "InvalidSubscriberException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // }
import com.mindorks.jpost.exceptions.AlreadyExistsException; import com.mindorks.jpost.exceptions.IllegalChannelStateException; import com.mindorks.jpost.exceptions.InvalidSubscriberException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue;
method.invoke(subscriber, post.getMessage()); } return true; } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } return false; } @Override public <T> T addSubscriber(T subscriber, Integer subscriberId ) throws NullObjectException, AlreadyExistsException, IllegalChannelStateException { if(super.getChannelState() != ChannelState.OPEN){ throw new IllegalChannelStateException("Channel with id " + super.getChannelId() + " is closed"); } if(subscriber == null){ throw new NullObjectException("subscriber is null"); } if(subscriberId == null){ throw new NullObjectException("subscriberId is null"); } if(super.getSubscriberMap().containsKey(subscriberId)){ throw new AlreadyExistsException("subscriber with subscriberId " + subscriberId + " already registered"); } super.getSubscriberMap().put(subscriberId, new WeakReference<Object>(subscriber)); return subscriber; } @Override
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/AlreadyExistsException.java // public class AlreadyExistsException extends Exception{ // // public AlreadyExistsException(String message) { // super(message); // } // // public String toString() { // return "AlreadyExistsException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/InvalidSubscriberException.java // public class InvalidSubscriberException extends Exception{ // // public InvalidSubscriberException(String message) { // super(message); // } // // public String toString() { // return "InvalidSubscriberException[" + super.getMessage() + "]"; // } // } // // Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // } // Path: jpost/src/main/java/com/mindorks/jpost/core/DefaultChannel.java import com.mindorks.jpost.exceptions.AlreadyExistsException; import com.mindorks.jpost.exceptions.IllegalChannelStateException; import com.mindorks.jpost.exceptions.InvalidSubscriberException; import com.mindorks.jpost.exceptions.NullObjectException; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue; method.invoke(subscriber, post.getMessage()); } return true; } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } return false; } @Override public <T> T addSubscriber(T subscriber, Integer subscriberId ) throws NullObjectException, AlreadyExistsException, IllegalChannelStateException { if(super.getChannelState() != ChannelState.OPEN){ throw new IllegalChannelStateException("Channel with id " + super.getChannelId() + " is closed"); } if(subscriber == null){ throw new NullObjectException("subscriber is null"); } if(subscriberId == null){ throw new NullObjectException("subscriberId is null"); } if(super.getSubscriberMap().containsKey(subscriberId)){ throw new AlreadyExistsException("subscriber with subscriberId " + subscriberId + " already registered"); } super.getSubscriberMap().put(subscriberId, new WeakReference<Object>(subscriber)); return subscriber; } @Override
public synchronized <T> void removeSubscriber(T subscriber) throws NullObjectException, InvalidSubscriberException {
janishar/JPost
jpost/src/main/java/com/mindorks/jpost/core/ChannelPost.java
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // }
import com.mindorks.jpost.exceptions.NullObjectException; import java.util.List;
public ChannelPost(T message, Integer channelId, Integer priority, boolean isSerialised, String className) { this.message = message; this.channelId = channelId; this.priority = priority; this.isSerialised = isSerialised; this.className = className; } @Override public void setMessage(T message){ this.message = message; } @Override public T getMessage() { return message; } @Override public void setPriority(Integer priority){ this.priority = priority; } @Override public Integer getPriority() { return priority; } @Override
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // } // Path: jpost/src/main/java/com/mindorks/jpost/core/ChannelPost.java import com.mindorks.jpost.exceptions.NullObjectException; import java.util.List; public ChannelPost(T message, Integer channelId, Integer priority, boolean isSerialised, String className) { this.message = message; this.channelId = channelId; this.priority = priority; this.isSerialised = isSerialised; this.className = className; } @Override public void setMessage(T message){ this.message = message; } @Override public T getMessage() { return message; } @Override public void setPriority(Integer priority){ this.priority = priority; } @Override public Integer getPriority() { return priority; } @Override
public V getSender() throws NullObjectException {
janishar/JPost
jpost/src/main/java/com/mindorks/jpost/core/Post.java
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // }
import com.mindorks.jpost.exceptions.NullObjectException;
/* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public interface Post<T, K> { int PRIORITY_LOW = 1; int PRIORITY_MEDIUM = 2; int PRIORITY_HIGH = 3; /** * * @param message */ void setMessage(T message); /** * * @return */ T getMessage(); /** * * @param priority */ void setPriority(Integer priority); /** * * @return */ Integer getPriority(); /** * * @return * @throws NullObjectException */
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/NullObjectException.java // public class NullObjectException extends Exception{ // // public NullObjectException(String message) { // super(message); // } // // public String toString() { // return "NullObjectException[" + super.getMessage() + "]"; // } // } // Path: jpost/src/main/java/com/mindorks/jpost/core/Post.java import com.mindorks.jpost.exceptions.NullObjectException; /* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 22/09/16. */ public interface Post<T, K> { int PRIORITY_LOW = 1; int PRIORITY_MEDIUM = 2; int PRIORITY_HIGH = 3; /** * * @param message */ void setMessage(T message); /** * * @return */ T getMessage(); /** * * @param priority */ void setPriority(Integer priority); /** * * @return */ Integer getPriority(); /** * * @return * @throws NullObjectException */
K getSender() throws NullObjectException;
janishar/JPost
jpost/src/main/java/com/mindorks/jpost/core/Broadcast.java
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // }
import com.mindorks.jpost.exceptions.*; import com.mindorks.jpost.exceptions.IllegalChannelStateException; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue;
/* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 23/09/16. */ public interface Broadcast<C extends Channel<? extends PriorityBlockingQueue<? extends WeakReference<? extends ChannelPost>>, ? extends ConcurrentHashMap<? extends Integer,? extends WeakReference<?>>>> { int CHANNEL_INITIAL_CAPACITY = 5; /** * * @param owner it is the owner of the private channel. * @param channelId unique int id assigned to the private channel. * @param <T> object casting to the owner class. * @return it returns an instance of the created PrivateChannel. * @throws AlreadyExistsException */ <T>C createPrivateChannel(T owner, Integer channelId) throws AlreadyExistsException; /** * * @param owner it is the owner of the private channel. * @param channelId unique int id assigned to the private channel. * @param subscriberId unique int id assigned to the subscriber for the private channel. * @param <T> object casting to the owner class. * @return it returns an instance of the created PrivateChannel. * @throws AlreadyExistsException */ <T>C createPrivateChannel(T owner, Integer channelId, Integer subscriberId) throws AlreadyExistsException; /** * * @param channelId unique int id assigned to the public channel. * @return it returns the instance of the created PublicChannel. * @throws AlreadyExistsException */ C createPublicChannel(Integer channelId) throws AlreadyExistsException; /** * * @param channelId it stops the public/private channel having channel id equal channelId. * No message can be send/received through this channel until it is restarted. */ void stopChannel(Integer channelId); /** * * @param channelId it open the channel with channel id. The sending/receiving messages through this channel can resumed. */ void reopenChannel(Integer channelId); /** * * @param channelId it stops the public/private channel having channel id equal channelId. * No message can be send/received through this channel after termination. * It removes the channel from the BroadcastCenter. */ void terminateChannel(Integer channelId); /** * * @param channelId unique id identifying a channel. * @return returns the channel having id as channel id. * @throws NoSuchChannelException * @throws NullObjectException */ C getChannel(Integer channelId) throws NoSuchChannelException, NullObjectException; /** * * @param channelId unique id identifying a public channel. * @param msg any object that has to be send through the public channel. * @param subscribers the list of specific subscribers subscribed to the public channel that has to be send the message. * If no subscriber is provided then the message is broadcast to all the subscribers of this channel. * @param <T> object cast of the msg. */ <T> void broadcast(Integer channelId, T msg, Integer... subscribers); /** * * @param registeredSubscriber it is the owner or the subscriber added to the private channel by th owner. * @param channelId unique id identifying a private channel. * @param msg any object that has to be send through the private channel. * @param subscribers the list of specific subscribers subscribed to the private channel that has to be send the message. * If no subscriber is provided then the message is broadcast to all the subscribers of this channel. * @param <V> object cast of the registeredSubscriber. * @param <T> object cast of the msg. */ <V, T> void broadcast(V registeredSubscriber, Integer channelId, T msg, Integer... subscribers); /** * * @param msg any object that has to be send through the center global channel. * It is send to all the subscriber of this channel. * @param <T> object cast of the msg. */ public <T> void broadcast(T msg); /** * * @param channelId unique id identifying a public channel. * @param msg any object that has to be send through the public channel asynchronously. * @param subscribers the list of specific subscribers subscribed to the public channel that has to be send the message. * If no subscriber is provided then the message is broadcast to all the subscribers of this channel. * @param <T> object cast of the msg. */ <T> void broadcastAsync(Integer channelId, T msg, Integer... subscribers)throws JPostNotRunningException; /** * * @param registeredSubscriber it is the owner or the subscriber added to the private channel by th owner. * @param channelId unique id identifying a private channel. * @param msg any object that has to be send through the private channel. * @param subscribers the list of specific subscribers subscribed to the private channel that has to be send the message asynchronously. * If no subscriber is provided then the message is broadcast to all the subscribers of this channel. * @param <V> object cast of the registeredSubscriber. * @param <T> object cast of the msg. */ <V, T> void broadcastAsync(V registeredSubscriber, Integer channelId, T msg, Integer... subscribers)throws JPostNotRunningException; /** * * @param msg any object that has to be send through the center global channel. * It is send to all the subscriber of this channel asynchronously. * @param <T> object cast of the msg. */ <T> void broadcastAsync(T msg)throws JPostNotRunningException; /** * * @param channelId unique id identifying a public channel. * @param subscriber subscriber that is subscribing to the public channel. * the subscriber is provided subscriber.hashCode() as the subscriber id. * @param <T> object cast of the subscriber. * @throws NoSuchChannelException * @throws AlreadyExistsException * @throws PermissionException * @throws IllegalChannelStateException * @throws NullObjectException */ <T> void addSubscriber(Integer channelId, T subscriber)
// Path: jpost/src/main/java/com/mindorks/jpost/exceptions/IllegalChannelStateException.java // public class IllegalChannelStateException extends Exception{ // // public IllegalChannelStateException(String message) { // super(message); // } // // public String toString() { // return "IllegalChannelStateException[" + super.getMessage() + "]"; // } // } // Path: jpost/src/main/java/com/mindorks/jpost/core/Broadcast.java import com.mindorks.jpost.exceptions.*; import com.mindorks.jpost.exceptions.IllegalChannelStateException; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.PriorityBlockingQueue; /* * Copyright (C) 2016 Janishar Ali Anwar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.mindorks.jpost.core; /** * Created by janisharali on 23/09/16. */ public interface Broadcast<C extends Channel<? extends PriorityBlockingQueue<? extends WeakReference<? extends ChannelPost>>, ? extends ConcurrentHashMap<? extends Integer,? extends WeakReference<?>>>> { int CHANNEL_INITIAL_CAPACITY = 5; /** * * @param owner it is the owner of the private channel. * @param channelId unique int id assigned to the private channel. * @param <T> object casting to the owner class. * @return it returns an instance of the created PrivateChannel. * @throws AlreadyExistsException */ <T>C createPrivateChannel(T owner, Integer channelId) throws AlreadyExistsException; /** * * @param owner it is the owner of the private channel. * @param channelId unique int id assigned to the private channel. * @param subscriberId unique int id assigned to the subscriber for the private channel. * @param <T> object casting to the owner class. * @return it returns an instance of the created PrivateChannel. * @throws AlreadyExistsException */ <T>C createPrivateChannel(T owner, Integer channelId, Integer subscriberId) throws AlreadyExistsException; /** * * @param channelId unique int id assigned to the public channel. * @return it returns the instance of the created PublicChannel. * @throws AlreadyExistsException */ C createPublicChannel(Integer channelId) throws AlreadyExistsException; /** * * @param channelId it stops the public/private channel having channel id equal channelId. * No message can be send/received through this channel until it is restarted. */ void stopChannel(Integer channelId); /** * * @param channelId it open the channel with channel id. The sending/receiving messages through this channel can resumed. */ void reopenChannel(Integer channelId); /** * * @param channelId it stops the public/private channel having channel id equal channelId. * No message can be send/received through this channel after termination. * It removes the channel from the BroadcastCenter. */ void terminateChannel(Integer channelId); /** * * @param channelId unique id identifying a channel. * @return returns the channel having id as channel id. * @throws NoSuchChannelException * @throws NullObjectException */ C getChannel(Integer channelId) throws NoSuchChannelException, NullObjectException; /** * * @param channelId unique id identifying a public channel. * @param msg any object that has to be send through the public channel. * @param subscribers the list of specific subscribers subscribed to the public channel that has to be send the message. * If no subscriber is provided then the message is broadcast to all the subscribers of this channel. * @param <T> object cast of the msg. */ <T> void broadcast(Integer channelId, T msg, Integer... subscribers); /** * * @param registeredSubscriber it is the owner or the subscriber added to the private channel by th owner. * @param channelId unique id identifying a private channel. * @param msg any object that has to be send through the private channel. * @param subscribers the list of specific subscribers subscribed to the private channel that has to be send the message. * If no subscriber is provided then the message is broadcast to all the subscribers of this channel. * @param <V> object cast of the registeredSubscriber. * @param <T> object cast of the msg. */ <V, T> void broadcast(V registeredSubscriber, Integer channelId, T msg, Integer... subscribers); /** * * @param msg any object that has to be send through the center global channel. * It is send to all the subscriber of this channel. * @param <T> object cast of the msg. */ public <T> void broadcast(T msg); /** * * @param channelId unique id identifying a public channel. * @param msg any object that has to be send through the public channel asynchronously. * @param subscribers the list of specific subscribers subscribed to the public channel that has to be send the message. * If no subscriber is provided then the message is broadcast to all the subscribers of this channel. * @param <T> object cast of the msg. */ <T> void broadcastAsync(Integer channelId, T msg, Integer... subscribers)throws JPostNotRunningException; /** * * @param registeredSubscriber it is the owner or the subscriber added to the private channel by th owner. * @param channelId unique id identifying a private channel. * @param msg any object that has to be send through the private channel. * @param subscribers the list of specific subscribers subscribed to the private channel that has to be send the message asynchronously. * If no subscriber is provided then the message is broadcast to all the subscribers of this channel. * @param <V> object cast of the registeredSubscriber. * @param <T> object cast of the msg. */ <V, T> void broadcastAsync(V registeredSubscriber, Integer channelId, T msg, Integer... subscribers)throws JPostNotRunningException; /** * * @param msg any object that has to be send through the center global channel. * It is send to all the subscriber of this channel asynchronously. * @param <T> object cast of the msg. */ <T> void broadcastAsync(T msg)throws JPostNotRunningException; /** * * @param channelId unique id identifying a public channel. * @param subscriber subscriber that is subscribing to the public channel. * the subscriber is provided subscriber.hashCode() as the subscriber id. * @param <T> object cast of the subscriber. * @throws NoSuchChannelException * @throws AlreadyExistsException * @throws PermissionException * @throws IllegalChannelStateException * @throws NullObjectException */ <T> void addSubscriber(Integer channelId, T subscriber)
throws NoSuchChannelException, AlreadyExistsException, PermissionException, IllegalChannelStateException, NullObjectException;
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/generator/OptionGenerator.java
// Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // }
import au.com.anthonybruno.generator.defaults.IntGenerator;
package au.com.anthonybruno.generator; public class OptionGenerator<T> implements Generator<T> { private final T[] options;
// Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // Path: src/main/java/au/com/anthonybruno/generator/OptionGenerator.java import au.com.anthonybruno.generator.defaults.IntGenerator; package au.com.anthonybruno.generator; public class OptionGenerator<T> implements Generator<T> { private final T[] options;
private final IntGenerator indexGenerator;
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/writer/fixedwidth/UnivocityFixedWidthWriter.java
// Path: src/main/java/au/com/anthonybruno/record/Record.java // public interface Record extends Iterable<Object> { // // Object get(int index); // // Object get(String fieldName); // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // }
import au.com.anthonybruno.record.Record; import au.com.anthonybruno.settings.FixedWidthSettings; import com.univocity.parsers.fixed.FixedWidthFields; import com.univocity.parsers.fixed.FixedWidthWriter; import com.univocity.parsers.fixed.FixedWidthWriterSettings; import java.io.Writer; import java.util.ArrayList; import java.util.List;
package au.com.anthonybruno.writer.fixedwidth; public class UnivocityFixedWidthWriter extends AbstractFixedWidthWriter { private FixedWidthWriter fixedWidthWriter;
// Path: src/main/java/au/com/anthonybruno/record/Record.java // public interface Record extends Iterable<Object> { // // Object get(int index); // // Object get(String fieldName); // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/UnivocityFixedWidthWriter.java import au.com.anthonybruno.record.Record; import au.com.anthonybruno.settings.FixedWidthSettings; import com.univocity.parsers.fixed.FixedWidthFields; import com.univocity.parsers.fixed.FixedWidthWriter; import com.univocity.parsers.fixed.FixedWidthWriterSettings; import java.io.Writer; import java.util.ArrayList; import java.util.List; package au.com.anthonybruno.writer.fixedwidth; public class UnivocityFixedWidthWriter extends AbstractFixedWidthWriter { private FixedWidthWriter fixedWidthWriter;
public UnivocityFixedWidthWriter(Writer writer, FixedWidthSettings settings) {
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/writer/fixedwidth/UnivocityFixedWidthWriter.java
// Path: src/main/java/au/com/anthonybruno/record/Record.java // public interface Record extends Iterable<Object> { // // Object get(int index); // // Object get(String fieldName); // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // }
import au.com.anthonybruno.record.Record; import au.com.anthonybruno.settings.FixedWidthSettings; import com.univocity.parsers.fixed.FixedWidthFields; import com.univocity.parsers.fixed.FixedWidthWriter; import com.univocity.parsers.fixed.FixedWidthWriterSettings; import java.io.Writer; import java.util.ArrayList; import java.util.List;
package au.com.anthonybruno.writer.fixedwidth; public class UnivocityFixedWidthWriter extends AbstractFixedWidthWriter { private FixedWidthWriter fixedWidthWriter; public UnivocityFixedWidthWriter(Writer writer, FixedWidthSettings settings) { super(writer, settings); FixedWidthFields fixedWidthFields = new FixedWidthFields(); settings.getFixedWidthFields().forEach((field) -> { fixedWidthFields.addField(field.getLength()); }); FixedWidthWriterSettings univocitySettings = new FixedWidthWriterSettings(fixedWidthFields); this.fixedWidthWriter = new FixedWidthWriter(writer, univocitySettings); } @Override public void writeRow(List<String> row) { fixedWidthWriter.writeRow(row); fixedWidthWriter.writeValuesToRow(); } @Override
// Path: src/main/java/au/com/anthonybruno/record/Record.java // public interface Record extends Iterable<Object> { // // Object get(int index); // // Object get(String fieldName); // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/UnivocityFixedWidthWriter.java import au.com.anthonybruno.record.Record; import au.com.anthonybruno.settings.FixedWidthSettings; import com.univocity.parsers.fixed.FixedWidthFields; import com.univocity.parsers.fixed.FixedWidthWriter; import com.univocity.parsers.fixed.FixedWidthWriterSettings; import java.io.Writer; import java.util.ArrayList; import java.util.List; package au.com.anthonybruno.writer.fixedwidth; public class UnivocityFixedWidthWriter extends AbstractFixedWidthWriter { private FixedWidthWriter fixedWidthWriter; public UnivocityFixedWidthWriter(Writer writer, FixedWidthSettings settings) { super(writer, settings); FixedWidthFields fixedWidthFields = new FixedWidthFields(); settings.getFixedWidthFields().forEach((field) -> { fixedWidthFields.addField(field.getLength()); }); FixedWidthWriterSettings univocitySettings = new FixedWidthWriterSettings(fixedWidthFields); this.fixedWidthWriter = new FixedWidthWriter(writer, univocitySettings); } @Override public void writeRow(List<String> row) { fixedWidthWriter.writeRow(row); fixedWidthWriter.writeValuesToRow(); } @Override
public void writeRecord(Record record) {
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/creator/FlatFileFactory.java
// Path: src/main/java/au/com/anthonybruno/record/factory/RecordFactory.java // public interface RecordFactory { // // RecordSupplier getRecordSupplier(); // } // // Path: src/main/java/au/com/anthonybruno/settings/FlatFileSettings.java // public class FlatFileSettings extends Settings { // // private final boolean includingHeaders; // // public FlatFileSettings(boolean includeHeaders) { // this.includingHeaders = includeHeaders; // } // // public boolean isIncludingHeaders() { // return includingHeaders; // } // }
import au.com.anthonybruno.record.factory.RecordFactory; import au.com.anthonybruno.settings.FlatFileSettings;
package au.com.anthonybruno.creator; public abstract class FlatFileFactory<T extends FlatFileSettings> implements FileFactory { protected final T settings;
// Path: src/main/java/au/com/anthonybruno/record/factory/RecordFactory.java // public interface RecordFactory { // // RecordSupplier getRecordSupplier(); // } // // Path: src/main/java/au/com/anthonybruno/settings/FlatFileSettings.java // public class FlatFileSettings extends Settings { // // private final boolean includingHeaders; // // public FlatFileSettings(boolean includeHeaders) { // this.includingHeaders = includeHeaders; // } // // public boolean isIncludingHeaders() { // return includingHeaders; // } // } // Path: src/main/java/au/com/anthonybruno/creator/FlatFileFactory.java import au.com.anthonybruno.record.factory.RecordFactory; import au.com.anthonybruno.settings.FlatFileSettings; package au.com.anthonybruno.creator; public abstract class FlatFileFactory<T extends FlatFileSettings> implements FileFactory { protected final T settings;
protected final RecordFactory recordFactory;
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/definition/StartDefinition.java
// Path: src/main/java/au/com/anthonybruno/generator/Generator.java // @FunctionalInterface // public interface Generator<T> { // // T generate(); // }
import au.com.anthonybruno.generator.Generator;
package au.com.anthonybruno.definition; /** * A class to specify the way that fields are configured, either through a class or specified individually. * * @author Anthony Bruno */ public interface StartDefinition { //FIXME: better name /** * Specifies a class that will be used to generate fields. * * @param c the class which the random data is to be generated for * * @return a RecordDefinition that allows the specification of the number of records to generate */ RecordDefinition use(Class<?> c); /** * Adds a field to be generated. * * @param name String that names the field * @param generator Generator object that creates random values for the field * * @return A FieldDefinition that allows more fields to be added */
// Path: src/main/java/au/com/anthonybruno/generator/Generator.java // @FunctionalInterface // public interface Generator<T> { // // T generate(); // } // Path: src/main/java/au/com/anthonybruno/definition/StartDefinition.java import au.com.anthonybruno.generator.Generator; package au.com.anthonybruno.definition; /** * A class to specify the way that fields are configured, either through a class or specified individually. * * @author Anthony Bruno */ public interface StartDefinition { //FIXME: better name /** * Specifies a class that will be used to generate fields. * * @param c the class which the random data is to be generated for * * @return a RecordDefinition that allows the specification of the number of records to generate */ RecordDefinition use(Class<?> c); /** * Adds a field to be generated. * * @param name String that names the field * @param generator Generator object that creates random values for the field * * @return A FieldDefinition that allows more fields to be added */
FieldDefinition addField(String name, Generator generator);
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/generator/FormattedGenerator.java
// Path: src/main/java/au/com/anthonybruno/generator/format/Formatter.java // @FunctionalInterface // public interface Formatter<T> { // // String format(T toFormat); // }
import au.com.anthonybruno.generator.format.Formatter;
package au.com.anthonybruno.generator; public class FormattedGenerator<T> implements Generator<String> { private final Generator<T> generator;
// Path: src/main/java/au/com/anthonybruno/generator/format/Formatter.java // @FunctionalInterface // public interface Formatter<T> { // // String format(T toFormat); // } // Path: src/main/java/au/com/anthonybruno/generator/FormattedGenerator.java import au.com.anthonybruno.generator.format.Formatter; package au.com.anthonybruno.generator; public class FormattedGenerator<T> implements Generator<String> { private final Generator<T> generator;
private final Formatter<T> formatter;
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/FixedWidthPojoGenTest.java
// Path: src/main/java/au/com/anthonybruno/settings/FixedWidthField.java // public class FixedWidthField { // // private final int length; // // public FixedWidthField(int length) { // this.length = length; // } // // public int getLength() { // return length; // } // // // public static List<FixedWidthField> create(int... lengths) { // List<FixedWidthField> out = new ArrayList<>(); // for (int length : lengths) { // out.add(new FixedWidthField(length)); // } // return out; // } // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // }
import au.com.anthonybruno.settings.FixedWidthField; import au.com.anthonybruno.settings.FixedWidthSettings; import com.univocity.parsers.fixed.FixedWidthFields; import com.univocity.parsers.fixed.FixedWidthParser; import com.univocity.parsers.fixed.FixedWidthParserSettings; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse;
package au.com.anthonybruno; public class FixedWidthPojoGenTest { private final int rows = 5;
// Path: src/main/java/au/com/anthonybruno/settings/FixedWidthField.java // public class FixedWidthField { // // private final int length; // // public FixedWidthField(int length) { // this.length = length; // } // // public int getLength() { // return length; // } // // // public static List<FixedWidthField> create(int... lengths) { // List<FixedWidthField> out = new ArrayList<>(); // for (int length : lengths) { // out.add(new FixedWidthField(length)); // } // return out; // } // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // Path: src/test/java/au/com/anthonybruno/FixedWidthPojoGenTest.java import au.com.anthonybruno.settings.FixedWidthField; import au.com.anthonybruno.settings.FixedWidthSettings; import com.univocity.parsers.fixed.FixedWidthFields; import com.univocity.parsers.fixed.FixedWidthParser; import com.univocity.parsers.fixed.FixedWidthParserSettings; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; package au.com.anthonybruno; public class FixedWidthPojoGenTest { private final int rows = 5;
private final List<FixedWidthField> fields = FixedWidthField.create(20, 20, 40);
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/FixedWidthPojoGenTest.java
// Path: src/main/java/au/com/anthonybruno/settings/FixedWidthField.java // public class FixedWidthField { // // private final int length; // // public FixedWidthField(int length) { // this.length = length; // } // // public int getLength() { // return length; // } // // // public static List<FixedWidthField> create(int... lengths) { // List<FixedWidthField> out = new ArrayList<>(); // for (int length : lengths) { // out.add(new FixedWidthField(length)); // } // return out; // } // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // }
import au.com.anthonybruno.settings.FixedWidthField; import au.com.anthonybruno.settings.FixedWidthSettings; import com.univocity.parsers.fixed.FixedWidthFields; import com.univocity.parsers.fixed.FixedWidthParser; import com.univocity.parsers.fixed.FixedWidthParserSettings; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse;
@Ignore("Parser seems to be randomly failing?") @Test public void fixedWidthFile() { File file = generateFixedWidthFile(); FixedWidthParser fixedWidthParser = createParser(); List<String[]> parsedResult = fixedWidthParser.parseAll(file); assertEquals(printRows(parsedResult), 5, parsedResult.size()); } private FixedWidthParser createParser() { FixedWidthFields fixedWidthFields = new FixedWidthFields(); fields.forEach(field -> { fixedWidthFields.addField(field.getLength()); }); FixedWidthParserSettings settings = new FixedWidthParserSettings(fixedWidthFields); return new FixedWidthParser(settings); } private String printRows(List<String[]> rows) { StringBuilder out = new StringBuilder(); rows.forEach((row) -> out.append(Arrays.toString(row)).append("\n")); return out.toString(); } private String generatePersonFixedWidth() { return Gen.start() .use(Person.class) .generate(rows)
// Path: src/main/java/au/com/anthonybruno/settings/FixedWidthField.java // public class FixedWidthField { // // private final int length; // // public FixedWidthField(int length) { // this.length = length; // } // // public int getLength() { // return length; // } // // // public static List<FixedWidthField> create(int... lengths) { // List<FixedWidthField> out = new ArrayList<>(); // for (int length : lengths) { // out.add(new FixedWidthField(length)); // } // return out; // } // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // Path: src/test/java/au/com/anthonybruno/FixedWidthPojoGenTest.java import au.com.anthonybruno.settings.FixedWidthField; import au.com.anthonybruno.settings.FixedWidthSettings; import com.univocity.parsers.fixed.FixedWidthFields; import com.univocity.parsers.fixed.FixedWidthParser; import com.univocity.parsers.fixed.FixedWidthParserSettings; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @Ignore("Parser seems to be randomly failing?") @Test public void fixedWidthFile() { File file = generateFixedWidthFile(); FixedWidthParser fixedWidthParser = createParser(); List<String[]> parsedResult = fixedWidthParser.parseAll(file); assertEquals(printRows(parsedResult), 5, parsedResult.size()); } private FixedWidthParser createParser() { FixedWidthFields fixedWidthFields = new FixedWidthFields(); fields.forEach(field -> { fixedWidthFields.addField(field.getLength()); }); FixedWidthParserSettings settings = new FixedWidthParserSettings(fixedWidthFields); return new FixedWidthParser(settings); } private String printRows(List<String[]> rows) { StringBuilder out = new StringBuilder(); rows.forEach((row) -> out.append(Arrays.toString(row)).append("\n")); return out.toString(); } private String generatePersonFixedWidth() { return Gen.start() .use(Person.class) .generate(rows)
.asFixedWidth(new FixedWidthSettings(false, fields))
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/definition/FieldData.java
// Path: src/main/java/au/com/anthonybruno/generator/Generator.java // @FunctionalInterface // public interface Generator<T> { // // T generate(); // }
import au.com.anthonybruno.generator.Generator;
package au.com.anthonybruno.definition; /** * FieldData - A class that holds the properties for name and generator * @author Anthony Bruno * */ public class FieldData { private final String name;
// Path: src/main/java/au/com/anthonybruno/generator/Generator.java // @FunctionalInterface // public interface Generator<T> { // // T generate(); // } // Path: src/main/java/au/com/anthonybruno/definition/FieldData.java import au.com.anthonybruno.generator.Generator; package au.com.anthonybruno.definition; /** * FieldData - A class that holds the properties for name and generator * @author Anthony Bruno * */ public class FieldData { private final String name;
private final Generator generator;
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/creator/FixedWidthFactory.java
// Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/factory/RecordFactory.java // public interface RecordFactory { // // RecordSupplier getRecordSupplier(); // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java // public class WriterFactory { // // public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { // return new UnivocityCsvWriter(writer, csvSettings); // } // // public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // return new UnivocityFixedWidthWriter(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/AbstractFixedWidthWriter.java // public abstract class AbstractFixedWidthWriter extends FlatFileWriter<FixedWidthSettings> { // // public AbstractFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // } // // }
import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.factory.RecordFactory; import au.com.anthonybruno.settings.FixedWidthSettings; import au.com.anthonybruno.utils.TextFile; import au.com.anthonybruno.writer.WriterFactory; import au.com.anthonybruno.writer.fixedwidth.AbstractFixedWidthWriter; import java.io.File; import java.io.StringWriter;
package au.com.anthonybruno.creator; public class FixedWidthFactory extends FlatFileFactory<FixedWidthSettings> { public FixedWidthFactory(FixedWidthSettings settings, RecordFactory recordFactory) { super(settings, recordFactory); } @Override public String createString(int numToGenerate) { StringWriter stringWriter = new StringWriter();
// Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/factory/RecordFactory.java // public interface RecordFactory { // // RecordSupplier getRecordSupplier(); // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java // public class WriterFactory { // // public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { // return new UnivocityCsvWriter(writer, csvSettings); // } // // public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // return new UnivocityFixedWidthWriter(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/AbstractFixedWidthWriter.java // public abstract class AbstractFixedWidthWriter extends FlatFileWriter<FixedWidthSettings> { // // public AbstractFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // } // // } // Path: src/main/java/au/com/anthonybruno/creator/FixedWidthFactory.java import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.factory.RecordFactory; import au.com.anthonybruno.settings.FixedWidthSettings; import au.com.anthonybruno.utils.TextFile; import au.com.anthonybruno.writer.WriterFactory; import au.com.anthonybruno.writer.fixedwidth.AbstractFixedWidthWriter; import java.io.File; import java.io.StringWriter; package au.com.anthonybruno.creator; public class FixedWidthFactory extends FlatFileFactory<FixedWidthSettings> { public FixedWidthFactory(FixedWidthSettings settings, RecordFactory recordFactory) { super(settings, recordFactory); } @Override public String createString(int numToGenerate) { StringWriter stringWriter = new StringWriter();
try (AbstractFixedWidthWriter fixedWidthWriter = WriterFactory.getDefaultFixedWidthWriter(stringWriter, settings)) {
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/creator/FixedWidthFactory.java
// Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/factory/RecordFactory.java // public interface RecordFactory { // // RecordSupplier getRecordSupplier(); // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java // public class WriterFactory { // // public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { // return new UnivocityCsvWriter(writer, csvSettings); // } // // public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // return new UnivocityFixedWidthWriter(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/AbstractFixedWidthWriter.java // public abstract class AbstractFixedWidthWriter extends FlatFileWriter<FixedWidthSettings> { // // public AbstractFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // } // // }
import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.factory.RecordFactory; import au.com.anthonybruno.settings.FixedWidthSettings; import au.com.anthonybruno.utils.TextFile; import au.com.anthonybruno.writer.WriterFactory; import au.com.anthonybruno.writer.fixedwidth.AbstractFixedWidthWriter; import java.io.File; import java.io.StringWriter;
package au.com.anthonybruno.creator; public class FixedWidthFactory extends FlatFileFactory<FixedWidthSettings> { public FixedWidthFactory(FixedWidthSettings settings, RecordFactory recordFactory) { super(settings, recordFactory); } @Override public String createString(int numToGenerate) { StringWriter stringWriter = new StringWriter();
// Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/factory/RecordFactory.java // public interface RecordFactory { // // RecordSupplier getRecordSupplier(); // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java // public class WriterFactory { // // public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { // return new UnivocityCsvWriter(writer, csvSettings); // } // // public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // return new UnivocityFixedWidthWriter(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/AbstractFixedWidthWriter.java // public abstract class AbstractFixedWidthWriter extends FlatFileWriter<FixedWidthSettings> { // // public AbstractFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // } // // } // Path: src/main/java/au/com/anthonybruno/creator/FixedWidthFactory.java import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.factory.RecordFactory; import au.com.anthonybruno.settings.FixedWidthSettings; import au.com.anthonybruno.utils.TextFile; import au.com.anthonybruno.writer.WriterFactory; import au.com.anthonybruno.writer.fixedwidth.AbstractFixedWidthWriter; import java.io.File; import java.io.StringWriter; package au.com.anthonybruno.creator; public class FixedWidthFactory extends FlatFileFactory<FixedWidthSettings> { public FixedWidthFactory(FixedWidthSettings settings, RecordFactory recordFactory) { super(settings, recordFactory); } @Override public String createString(int numToGenerate) { StringWriter stringWriter = new StringWriter();
try (AbstractFixedWidthWriter fixedWidthWriter = WriterFactory.getDefaultFixedWidthWriter(stringWriter, settings)) {
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/creator/FixedWidthFactory.java
// Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/factory/RecordFactory.java // public interface RecordFactory { // // RecordSupplier getRecordSupplier(); // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java // public class WriterFactory { // // public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { // return new UnivocityCsvWriter(writer, csvSettings); // } // // public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // return new UnivocityFixedWidthWriter(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/AbstractFixedWidthWriter.java // public abstract class AbstractFixedWidthWriter extends FlatFileWriter<FixedWidthSettings> { // // public AbstractFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // } // // }
import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.factory.RecordFactory; import au.com.anthonybruno.settings.FixedWidthSettings; import au.com.anthonybruno.utils.TextFile; import au.com.anthonybruno.writer.WriterFactory; import au.com.anthonybruno.writer.fixedwidth.AbstractFixedWidthWriter; import java.io.File; import java.io.StringWriter;
package au.com.anthonybruno.creator; public class FixedWidthFactory extends FlatFileFactory<FixedWidthSettings> { public FixedWidthFactory(FixedWidthSettings settings, RecordFactory recordFactory) { super(settings, recordFactory); } @Override public String createString(int numToGenerate) { StringWriter stringWriter = new StringWriter(); try (AbstractFixedWidthWriter fixedWidthWriter = WriterFactory.getDefaultFixedWidthWriter(stringWriter, settings)) { generateAndWriteValues(fixedWidthWriter, numToGenerate); } return stringWriter.toString(); } private void generateAndWriteValues(AbstractFixedWidthWriter writer, int numToGenerate) {
// Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/factory/RecordFactory.java // public interface RecordFactory { // // RecordSupplier getRecordSupplier(); // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java // public class WriterFactory { // // public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { // return new UnivocityCsvWriter(writer, csvSettings); // } // // public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // return new UnivocityFixedWidthWriter(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/AbstractFixedWidthWriter.java // public abstract class AbstractFixedWidthWriter extends FlatFileWriter<FixedWidthSettings> { // // public AbstractFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // } // // } // Path: src/main/java/au/com/anthonybruno/creator/FixedWidthFactory.java import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.factory.RecordFactory; import au.com.anthonybruno.settings.FixedWidthSettings; import au.com.anthonybruno.utils.TextFile; import au.com.anthonybruno.writer.WriterFactory; import au.com.anthonybruno.writer.fixedwidth.AbstractFixedWidthWriter; import java.io.File; import java.io.StringWriter; package au.com.anthonybruno.creator; public class FixedWidthFactory extends FlatFileFactory<FixedWidthSettings> { public FixedWidthFactory(FixedWidthSettings settings, RecordFactory recordFactory) { super(settings, recordFactory); } @Override public String createString(int numToGenerate) { StringWriter stringWriter = new StringWriter(); try (AbstractFixedWidthWriter fixedWidthWriter = WriterFactory.getDefaultFixedWidthWriter(stringWriter, settings)) { generateAndWriteValues(fixedWidthWriter, numToGenerate); } return stringWriter.toString(); } private void generateAndWriteValues(AbstractFixedWidthWriter writer, int numToGenerate) {
RecordSupplier recordSupplier = recordFactory.getRecordSupplier();
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/creator/FixedWidthFactory.java
// Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/factory/RecordFactory.java // public interface RecordFactory { // // RecordSupplier getRecordSupplier(); // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java // public class WriterFactory { // // public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { // return new UnivocityCsvWriter(writer, csvSettings); // } // // public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // return new UnivocityFixedWidthWriter(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/AbstractFixedWidthWriter.java // public abstract class AbstractFixedWidthWriter extends FlatFileWriter<FixedWidthSettings> { // // public AbstractFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // } // // }
import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.factory.RecordFactory; import au.com.anthonybruno.settings.FixedWidthSettings; import au.com.anthonybruno.utils.TextFile; import au.com.anthonybruno.writer.WriterFactory; import au.com.anthonybruno.writer.fixedwidth.AbstractFixedWidthWriter; import java.io.File; import java.io.StringWriter;
package au.com.anthonybruno.creator; public class FixedWidthFactory extends FlatFileFactory<FixedWidthSettings> { public FixedWidthFactory(FixedWidthSettings settings, RecordFactory recordFactory) { super(settings, recordFactory); } @Override public String createString(int numToGenerate) { StringWriter stringWriter = new StringWriter(); try (AbstractFixedWidthWriter fixedWidthWriter = WriterFactory.getDefaultFixedWidthWriter(stringWriter, settings)) { generateAndWriteValues(fixedWidthWriter, numToGenerate); } return stringWriter.toString(); } private void generateAndWriteValues(AbstractFixedWidthWriter writer, int numToGenerate) { RecordSupplier recordSupplier = recordFactory.getRecordSupplier(); if (settings.isIncludingHeaders()) { writer.writeRow(recordSupplier.getFields()); } recordSupplier.supplyRecords(numToGenerate) .forEach(record -> { writer.writeRecord(record); }); } @Override public File createFile(File file, int numToGenerate) {
// Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/factory/RecordFactory.java // public interface RecordFactory { // // RecordSupplier getRecordSupplier(); // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java // public class WriterFactory { // // public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { // return new UnivocityCsvWriter(writer, csvSettings); // } // // public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // return new UnivocityFixedWidthWriter(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/AbstractFixedWidthWriter.java // public abstract class AbstractFixedWidthWriter extends FlatFileWriter<FixedWidthSettings> { // // public AbstractFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // } // // } // Path: src/main/java/au/com/anthonybruno/creator/FixedWidthFactory.java import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.factory.RecordFactory; import au.com.anthonybruno.settings.FixedWidthSettings; import au.com.anthonybruno.utils.TextFile; import au.com.anthonybruno.writer.WriterFactory; import au.com.anthonybruno.writer.fixedwidth.AbstractFixedWidthWriter; import java.io.File; import java.io.StringWriter; package au.com.anthonybruno.creator; public class FixedWidthFactory extends FlatFileFactory<FixedWidthSettings> { public FixedWidthFactory(FixedWidthSettings settings, RecordFactory recordFactory) { super(settings, recordFactory); } @Override public String createString(int numToGenerate) { StringWriter stringWriter = new StringWriter(); try (AbstractFixedWidthWriter fixedWidthWriter = WriterFactory.getDefaultFixedWidthWriter(stringWriter, settings)) { generateAndWriteValues(fixedWidthWriter, numToGenerate); } return stringWriter.toString(); } private void generateAndWriteValues(AbstractFixedWidthWriter writer, int numToGenerate) { RecordSupplier recordSupplier = recordFactory.getRecordSupplier(); if (settings.isIncludingHeaders()) { writer.writeRow(recordSupplier.getFields()); } recordSupplier.supplyRecords(numToGenerate) .forEach(record -> { writer.writeRecord(record); }); } @Override public File createFile(File file, int numToGenerate) {
try (AbstractFixedWidthWriter fixedWidthWriter = WriterFactory.getDefaultFixedWidthWriter(new TextFile(file).getWriter(), settings)) {
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java
// Path: src/main/java/au/com/anthonybruno/Gen.java // public class Gen implements FileTypeDefinition, ResultDefinition, StartDefinition, RecordDefinition, FieldDefinition { // // private int numToGenerate; // private FileFactory fileFactory; // // private Class<?> useClass; // private List<FieldData> fields = new ArrayList<>(); // // public static StartDefinition start() { // return new Gen(); // } // // private Gen() { // // } // // // @Override // public RecordDefinition use(Class<?> c) { // useClass = c; // return this; // } // // @Override // public FieldDefinition addField(String name, Generator generator) { // ArgumentUtils.isNotNull(generator, "Can not add '" + name + "' field with null generator"); // fields.add(new FieldData(name, generator)); // return this; // } // // @Override // public ResultDefinition asCsv() { // return asCsv(new CsvSettings.Builder().build()); // } // // @Override // public ResultDefinition asCsv(CsvSettings csvSettings) { // fileFactory = new CsvFactory(csvSettings, createRecordFactory()); // return this; // } // // @Override // public ResultDefinition asFixedWidth(FixedWidthSettings fixedWidthSettings) { // fileFactory = new FixedWidthFactory(fixedWidthSettings, createRecordFactory()); // return this; // } // // @Override // public File toFile(File file) { // return fileFactory.createFile(file, numToGenerate); // } // // @Override // public File toFile(String path) { // return toFile(new File(path)); // } // // @Override // public String toStringForm() { // checkSetup(); // return fileFactory.createString(numToGenerate); // } // // @Override // public FileTypeDefinition generate(int num) { // this.numToGenerate = num; // return this; // } // // private RecordFactory createRecordFactory() { // if (useClass != null) { // return new ClassRecordFactory(useClass); // } else if (!fields.isEmpty()){ // return new FieldsRecordFactory(fields); // } else { // throw new IllegalStateException("No fields or class added to generator"); // } // } // // private void checkSetup() { // if (useClass == null && fields.isEmpty()) { // throw new IllegalStateException("No generation fields or class specified! Please utilise the #use or #addField methods!"); // } // // if (fileFactory == null) { // throw new IllegalStateException("No file type specified! Use one of the 'as' methods such as #asCsv()"); // } // // if (numToGenerate <= 0) { // throw new IllegalStateException("Need to specify a positive non-zero number of records to generate!"); // } // } // // // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // }
import au.com.anthonybruno.Gen; import au.com.anthonybruno.settings.CsvSettings; import com.univocity.parsers.csv.CsvParser; import com.univocity.parsers.csv.CsvParserSettings; import org.junit.Test; import java.io.StringReader; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import static junit.framework.TestCase.assertFalse; import static org.junit.Assert.*;
continue; } if (!names.contains(row[0])) { fail("Name column value is not in list! Result: '" + row[0] + " 'List: " + names); } } } @Test public void agesInRange() { String result = generateAnnotatedPersonCsv(); CsvParser csvParser = new CsvParser(new CsvParserSettings()); boolean firstRow = true; for (String[] row : csvParser.iterate(new StringReader(result))) { if (firstRow) { firstRow = false; continue; } int age = Integer.parseInt(row[1]); assertTrue(age + "",age <= maxAge); assertTrue(age + "",age >= minAge); } } @Test(expected = IllegalStateException.class) public void generateMultivalued() {
// Path: src/main/java/au/com/anthonybruno/Gen.java // public class Gen implements FileTypeDefinition, ResultDefinition, StartDefinition, RecordDefinition, FieldDefinition { // // private int numToGenerate; // private FileFactory fileFactory; // // private Class<?> useClass; // private List<FieldData> fields = new ArrayList<>(); // // public static StartDefinition start() { // return new Gen(); // } // // private Gen() { // // } // // // @Override // public RecordDefinition use(Class<?> c) { // useClass = c; // return this; // } // // @Override // public FieldDefinition addField(String name, Generator generator) { // ArgumentUtils.isNotNull(generator, "Can not add '" + name + "' field with null generator"); // fields.add(new FieldData(name, generator)); // return this; // } // // @Override // public ResultDefinition asCsv() { // return asCsv(new CsvSettings.Builder().build()); // } // // @Override // public ResultDefinition asCsv(CsvSettings csvSettings) { // fileFactory = new CsvFactory(csvSettings, createRecordFactory()); // return this; // } // // @Override // public ResultDefinition asFixedWidth(FixedWidthSettings fixedWidthSettings) { // fileFactory = new FixedWidthFactory(fixedWidthSettings, createRecordFactory()); // return this; // } // // @Override // public File toFile(File file) { // return fileFactory.createFile(file, numToGenerate); // } // // @Override // public File toFile(String path) { // return toFile(new File(path)); // } // // @Override // public String toStringForm() { // checkSetup(); // return fileFactory.createString(numToGenerate); // } // // @Override // public FileTypeDefinition generate(int num) { // this.numToGenerate = num; // return this; // } // // private RecordFactory createRecordFactory() { // if (useClass != null) { // return new ClassRecordFactory(useClass); // } else if (!fields.isEmpty()){ // return new FieldsRecordFactory(fields); // } else { // throw new IllegalStateException("No fields or class added to generator"); // } // } // // private void checkSetup() { // if (useClass == null && fields.isEmpty()) { // throw new IllegalStateException("No generation fields or class specified! Please utilise the #use or #addField methods!"); // } // // if (fileFactory == null) { // throw new IllegalStateException("No file type specified! Use one of the 'as' methods such as #asCsv()"); // } // // if (numToGenerate <= 0) { // throw new IllegalStateException("Need to specify a positive non-zero number of records to generate!"); // } // } // // // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java import au.com.anthonybruno.Gen; import au.com.anthonybruno.settings.CsvSettings; import com.univocity.parsers.csv.CsvParser; import com.univocity.parsers.csv.CsvParserSettings; import org.junit.Test; import java.io.StringReader; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import static junit.framework.TestCase.assertFalse; import static org.junit.Assert.*; continue; } if (!names.contains(row[0])) { fail("Name column value is not in list! Result: '" + row[0] + " 'List: " + names); } } } @Test public void agesInRange() { String result = generateAnnotatedPersonCsv(); CsvParser csvParser = new CsvParser(new CsvParserSettings()); boolean firstRow = true; for (String[] row : csvParser.iterate(new StringReader(result))) { if (firstRow) { firstRow = false; continue; } int age = Integer.parseInt(row[1]); assertTrue(age + "",age <= maxAge); assertTrue(age + "",age >= minAge); } } @Test(expected = IllegalStateException.class) public void generateMultivalued() {
Gen.start()
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java
// Path: src/main/java/au/com/anthonybruno/Gen.java // public class Gen implements FileTypeDefinition, ResultDefinition, StartDefinition, RecordDefinition, FieldDefinition { // // private int numToGenerate; // private FileFactory fileFactory; // // private Class<?> useClass; // private List<FieldData> fields = new ArrayList<>(); // // public static StartDefinition start() { // return new Gen(); // } // // private Gen() { // // } // // // @Override // public RecordDefinition use(Class<?> c) { // useClass = c; // return this; // } // // @Override // public FieldDefinition addField(String name, Generator generator) { // ArgumentUtils.isNotNull(generator, "Can not add '" + name + "' field with null generator"); // fields.add(new FieldData(name, generator)); // return this; // } // // @Override // public ResultDefinition asCsv() { // return asCsv(new CsvSettings.Builder().build()); // } // // @Override // public ResultDefinition asCsv(CsvSettings csvSettings) { // fileFactory = new CsvFactory(csvSettings, createRecordFactory()); // return this; // } // // @Override // public ResultDefinition asFixedWidth(FixedWidthSettings fixedWidthSettings) { // fileFactory = new FixedWidthFactory(fixedWidthSettings, createRecordFactory()); // return this; // } // // @Override // public File toFile(File file) { // return fileFactory.createFile(file, numToGenerate); // } // // @Override // public File toFile(String path) { // return toFile(new File(path)); // } // // @Override // public String toStringForm() { // checkSetup(); // return fileFactory.createString(numToGenerate); // } // // @Override // public FileTypeDefinition generate(int num) { // this.numToGenerate = num; // return this; // } // // private RecordFactory createRecordFactory() { // if (useClass != null) { // return new ClassRecordFactory(useClass); // } else if (!fields.isEmpty()){ // return new FieldsRecordFactory(fields); // } else { // throw new IllegalStateException("No fields or class added to generator"); // } // } // // private void checkSetup() { // if (useClass == null && fields.isEmpty()) { // throw new IllegalStateException("No generation fields or class specified! Please utilise the #use or #addField methods!"); // } // // if (fileFactory == null) { // throw new IllegalStateException("No file type specified! Use one of the 'as' methods such as #asCsv()"); // } // // if (numToGenerate <= 0) { // throw new IllegalStateException("Need to specify a positive non-zero number of records to generate!"); // } // } // // // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // }
import au.com.anthonybruno.Gen; import au.com.anthonybruno.settings.CsvSettings; import com.univocity.parsers.csv.CsvParser; import com.univocity.parsers.csv.CsvParserSettings; import org.junit.Test; import java.io.StringReader; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import static junit.framework.TestCase.assertFalse; import static org.junit.Assert.*;
CsvParser csvParser = new CsvParser(new CsvParserSettings()); boolean firstRow = true; for (String[] row : csvParser.iterate(new StringReader(result))) { if (firstRow) { firstRow = false; continue; } int age = Integer.parseInt(row[1]); assertTrue(age + "",age <= maxAge); assertTrue(age + "",age >= minAge); } } @Test(expected = IllegalStateException.class) public void generateMultivalued() { Gen.start() .use(UnsupportedTypeClass.class) .generate(5) .asCsv() .toStringForm(); } private String generateAnnotatedPersonCsv() { return Gen.start() .use(AnnotatedPerson.class) .generate(5)
// Path: src/main/java/au/com/anthonybruno/Gen.java // public class Gen implements FileTypeDefinition, ResultDefinition, StartDefinition, RecordDefinition, FieldDefinition { // // private int numToGenerate; // private FileFactory fileFactory; // // private Class<?> useClass; // private List<FieldData> fields = new ArrayList<>(); // // public static StartDefinition start() { // return new Gen(); // } // // private Gen() { // // } // // // @Override // public RecordDefinition use(Class<?> c) { // useClass = c; // return this; // } // // @Override // public FieldDefinition addField(String name, Generator generator) { // ArgumentUtils.isNotNull(generator, "Can not add '" + name + "' field with null generator"); // fields.add(new FieldData(name, generator)); // return this; // } // // @Override // public ResultDefinition asCsv() { // return asCsv(new CsvSettings.Builder().build()); // } // // @Override // public ResultDefinition asCsv(CsvSettings csvSettings) { // fileFactory = new CsvFactory(csvSettings, createRecordFactory()); // return this; // } // // @Override // public ResultDefinition asFixedWidth(FixedWidthSettings fixedWidthSettings) { // fileFactory = new FixedWidthFactory(fixedWidthSettings, createRecordFactory()); // return this; // } // // @Override // public File toFile(File file) { // return fileFactory.createFile(file, numToGenerate); // } // // @Override // public File toFile(String path) { // return toFile(new File(path)); // } // // @Override // public String toStringForm() { // checkSetup(); // return fileFactory.createString(numToGenerate); // } // // @Override // public FileTypeDefinition generate(int num) { // this.numToGenerate = num; // return this; // } // // private RecordFactory createRecordFactory() { // if (useClass != null) { // return new ClassRecordFactory(useClass); // } else if (!fields.isEmpty()){ // return new FieldsRecordFactory(fields); // } else { // throw new IllegalStateException("No fields or class added to generator"); // } // } // // private void checkSetup() { // if (useClass == null && fields.isEmpty()) { // throw new IllegalStateException("No generation fields or class specified! Please utilise the #use or #addField methods!"); // } // // if (fileFactory == null) { // throw new IllegalStateException("No file type specified! Use one of the 'as' methods such as #asCsv()"); // } // // if (numToGenerate <= 0) { // throw new IllegalStateException("Need to specify a positive non-zero number of records to generate!"); // } // } // // // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java import au.com.anthonybruno.Gen; import au.com.anthonybruno.settings.CsvSettings; import com.univocity.parsers.csv.CsvParser; import com.univocity.parsers.csv.CsvParserSettings; import org.junit.Test; import java.io.StringReader; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import static junit.framework.TestCase.assertFalse; import static org.junit.Assert.*; CsvParser csvParser = new CsvParser(new CsvParserSettings()); boolean firstRow = true; for (String[] row : csvParser.iterate(new StringReader(result))) { if (firstRow) { firstRow = false; continue; } int age = Integer.parseInt(row[1]); assertTrue(age + "",age <= maxAge); assertTrue(age + "",age >= minAge); } } @Test(expected = IllegalStateException.class) public void generateMultivalued() { Gen.start() .use(UnsupportedTypeClass.class) .generate(5) .asCsv() .toStringForm(); } private String generateAnnotatedPersonCsv() { return Gen.start() .use(AnnotatedPerson.class) .generate(5)
.asCsv(new CsvSettings(true))
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/annotated/AnnotatedPerson.java
// Path: src/main/java/au/com/anthonybruno/generator/Generator.java // @FunctionalInterface // public interface Generator<T> { // // T generate(); // } // // Path: src/main/java/au/com/anthonybruno/generator/OptionGenerator.java // public class OptionGenerator<T> implements Generator<T> { // // private final T[] options; // private final IntGenerator indexGenerator; // // public OptionGenerator(T... options) { // this.options = options; // this.indexGenerator = new IntGenerator(0, options.length); // } // // // @Override // public T generate() { // return options[indexGenerator.generate()]; // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int maxAge = 80; // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int minAge = 18;
import au.com.anthonybruno.annotation.Generation; import au.com.anthonybruno.annotation.Range; import au.com.anthonybruno.generator.Generator; import au.com.anthonybruno.generator.OptionGenerator; import au.com.anthonybruno.generator.defaults.IntGenerator; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.maxAge; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.minAge;
package au.com.anthonybruno.annotated; public class AnnotatedPerson { @Generation(NameGenerator.class) private final String name;
// Path: src/main/java/au/com/anthonybruno/generator/Generator.java // @FunctionalInterface // public interface Generator<T> { // // T generate(); // } // // Path: src/main/java/au/com/anthonybruno/generator/OptionGenerator.java // public class OptionGenerator<T> implements Generator<T> { // // private final T[] options; // private final IntGenerator indexGenerator; // // public OptionGenerator(T... options) { // this.options = options; // this.indexGenerator = new IntGenerator(0, options.length); // } // // // @Override // public T generate() { // return options[indexGenerator.generate()]; // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int maxAge = 80; // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int minAge = 18; // Path: src/test/java/au/com/anthonybruno/annotated/AnnotatedPerson.java import au.com.anthonybruno.annotation.Generation; import au.com.anthonybruno.annotation.Range; import au.com.anthonybruno.generator.Generator; import au.com.anthonybruno.generator.OptionGenerator; import au.com.anthonybruno.generator.defaults.IntGenerator; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.maxAge; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.minAge; package au.com.anthonybruno.annotated; public class AnnotatedPerson { @Generation(NameGenerator.class) private final String name;
@Range(min=minAge, max=maxAge)
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/annotated/AnnotatedPerson.java
// Path: src/main/java/au/com/anthonybruno/generator/Generator.java // @FunctionalInterface // public interface Generator<T> { // // T generate(); // } // // Path: src/main/java/au/com/anthonybruno/generator/OptionGenerator.java // public class OptionGenerator<T> implements Generator<T> { // // private final T[] options; // private final IntGenerator indexGenerator; // // public OptionGenerator(T... options) { // this.options = options; // this.indexGenerator = new IntGenerator(0, options.length); // } // // // @Override // public T generate() { // return options[indexGenerator.generate()]; // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int maxAge = 80; // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int minAge = 18;
import au.com.anthonybruno.annotation.Generation; import au.com.anthonybruno.annotation.Range; import au.com.anthonybruno.generator.Generator; import au.com.anthonybruno.generator.OptionGenerator; import au.com.anthonybruno.generator.defaults.IntGenerator; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.maxAge; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.minAge;
package au.com.anthonybruno.annotated; public class AnnotatedPerson { @Generation(NameGenerator.class) private final String name;
// Path: src/main/java/au/com/anthonybruno/generator/Generator.java // @FunctionalInterface // public interface Generator<T> { // // T generate(); // } // // Path: src/main/java/au/com/anthonybruno/generator/OptionGenerator.java // public class OptionGenerator<T> implements Generator<T> { // // private final T[] options; // private final IntGenerator indexGenerator; // // public OptionGenerator(T... options) { // this.options = options; // this.indexGenerator = new IntGenerator(0, options.length); // } // // // @Override // public T generate() { // return options[indexGenerator.generate()]; // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int maxAge = 80; // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int minAge = 18; // Path: src/test/java/au/com/anthonybruno/annotated/AnnotatedPerson.java import au.com.anthonybruno.annotation.Generation; import au.com.anthonybruno.annotation.Range; import au.com.anthonybruno.generator.Generator; import au.com.anthonybruno.generator.OptionGenerator; import au.com.anthonybruno.generator.defaults.IntGenerator; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.maxAge; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.minAge; package au.com.anthonybruno.annotated; public class AnnotatedPerson { @Generation(NameGenerator.class) private final String name;
@Range(min=minAge, max=maxAge)
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/annotated/AnnotatedPerson.java
// Path: src/main/java/au/com/anthonybruno/generator/Generator.java // @FunctionalInterface // public interface Generator<T> { // // T generate(); // } // // Path: src/main/java/au/com/anthonybruno/generator/OptionGenerator.java // public class OptionGenerator<T> implements Generator<T> { // // private final T[] options; // private final IntGenerator indexGenerator; // // public OptionGenerator(T... options) { // this.options = options; // this.indexGenerator = new IntGenerator(0, options.length); // } // // // @Override // public T generate() { // return options[indexGenerator.generate()]; // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int maxAge = 80; // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int minAge = 18;
import au.com.anthonybruno.annotation.Generation; import au.com.anthonybruno.annotation.Range; import au.com.anthonybruno.generator.Generator; import au.com.anthonybruno.generator.OptionGenerator; import au.com.anthonybruno.generator.defaults.IntGenerator; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.maxAge; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.minAge;
package au.com.anthonybruno.annotated; public class AnnotatedPerson { @Generation(NameGenerator.class) private final String name; @Range(min=minAge, max=maxAge)
// Path: src/main/java/au/com/anthonybruno/generator/Generator.java // @FunctionalInterface // public interface Generator<T> { // // T generate(); // } // // Path: src/main/java/au/com/anthonybruno/generator/OptionGenerator.java // public class OptionGenerator<T> implements Generator<T> { // // private final T[] options; // private final IntGenerator indexGenerator; // // public OptionGenerator(T... options) { // this.options = options; // this.indexGenerator = new IntGenerator(0, options.length); // } // // // @Override // public T generate() { // return options[indexGenerator.generate()]; // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int maxAge = 80; // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int minAge = 18; // Path: src/test/java/au/com/anthonybruno/annotated/AnnotatedPerson.java import au.com.anthonybruno.annotation.Generation; import au.com.anthonybruno.annotation.Range; import au.com.anthonybruno.generator.Generator; import au.com.anthonybruno.generator.OptionGenerator; import au.com.anthonybruno.generator.defaults.IntGenerator; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.maxAge; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.minAge; package au.com.anthonybruno.annotated; public class AnnotatedPerson { @Generation(NameGenerator.class) private final String name; @Range(min=minAge, max=maxAge)
@Generation(value = IntGenerator.class, name="yearsSinceBirth")
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/annotated/AnnotatedPerson.java
// Path: src/main/java/au/com/anthonybruno/generator/Generator.java // @FunctionalInterface // public interface Generator<T> { // // T generate(); // } // // Path: src/main/java/au/com/anthonybruno/generator/OptionGenerator.java // public class OptionGenerator<T> implements Generator<T> { // // private final T[] options; // private final IntGenerator indexGenerator; // // public OptionGenerator(T... options) { // this.options = options; // this.indexGenerator = new IntGenerator(0, options.length); // } // // // @Override // public T generate() { // return options[indexGenerator.generate()]; // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int maxAge = 80; // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int minAge = 18;
import au.com.anthonybruno.annotation.Generation; import au.com.anthonybruno.annotation.Range; import au.com.anthonybruno.generator.Generator; import au.com.anthonybruno.generator.OptionGenerator; import au.com.anthonybruno.generator.defaults.IntGenerator; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.maxAge; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.minAge;
package au.com.anthonybruno.annotated; public class AnnotatedPerson { @Generation(NameGenerator.class) private final String name; @Range(min=minAge, max=maxAge) @Generation(value = IntGenerator.class, name="yearsSinceBirth") private final int age; @Generation(GenderGenerator.class) private final String gender; public AnnotatedPerson(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; }
// Path: src/main/java/au/com/anthonybruno/generator/Generator.java // @FunctionalInterface // public interface Generator<T> { // // T generate(); // } // // Path: src/main/java/au/com/anthonybruno/generator/OptionGenerator.java // public class OptionGenerator<T> implements Generator<T> { // // private final T[] options; // private final IntGenerator indexGenerator; // // public OptionGenerator(T... options) { // this.options = options; // this.indexGenerator = new IntGenerator(0, options.length); // } // // // @Override // public T generate() { // return options[indexGenerator.generate()]; // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int maxAge = 80; // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int minAge = 18; // Path: src/test/java/au/com/anthonybruno/annotated/AnnotatedPerson.java import au.com.anthonybruno.annotation.Generation; import au.com.anthonybruno.annotation.Range; import au.com.anthonybruno.generator.Generator; import au.com.anthonybruno.generator.OptionGenerator; import au.com.anthonybruno.generator.defaults.IntGenerator; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.maxAge; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.minAge; package au.com.anthonybruno.annotated; public class AnnotatedPerson { @Generation(NameGenerator.class) private final String name; @Range(min=minAge, max=maxAge) @Generation(value = IntGenerator.class, name="yearsSinceBirth") private final int age; @Generation(GenderGenerator.class) private final String gender; public AnnotatedPerson(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; }
public static class NameGenerator implements Generator<String> {
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/annotated/AnnotatedPerson.java
// Path: src/main/java/au/com/anthonybruno/generator/Generator.java // @FunctionalInterface // public interface Generator<T> { // // T generate(); // } // // Path: src/main/java/au/com/anthonybruno/generator/OptionGenerator.java // public class OptionGenerator<T> implements Generator<T> { // // private final T[] options; // private final IntGenerator indexGenerator; // // public OptionGenerator(T... options) { // this.options = options; // this.indexGenerator = new IntGenerator(0, options.length); // } // // // @Override // public T generate() { // return options[indexGenerator.generate()]; // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int maxAge = 80; // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int minAge = 18;
import au.com.anthonybruno.annotation.Generation; import au.com.anthonybruno.annotation.Range; import au.com.anthonybruno.generator.Generator; import au.com.anthonybruno.generator.OptionGenerator; import au.com.anthonybruno.generator.defaults.IntGenerator; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.maxAge; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.minAge;
package au.com.anthonybruno.annotated; public class AnnotatedPerson { @Generation(NameGenerator.class) private final String name; @Range(min=minAge, max=maxAge) @Generation(value = IntGenerator.class, name="yearsSinceBirth") private final int age; @Generation(GenderGenerator.class) private final String gender; public AnnotatedPerson(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; } public static class NameGenerator implements Generator<String> { private static final String[] names = {"Olivia", "Charlotte", "Mia", "Ava", "Amelia", "Emily", "Sofia", "Ruby"}; private static final int namesLength = names.length; @Override public String generate() { int randIndex = ThreadLocalRandom.current().nextInt(0, namesLength); return names[randIndex]; } public static List<String> getNames() { return Arrays.asList(names); } } public static class GenderGenerator implements Generator<String> {
// Path: src/main/java/au/com/anthonybruno/generator/Generator.java // @FunctionalInterface // public interface Generator<T> { // // T generate(); // } // // Path: src/main/java/au/com/anthonybruno/generator/OptionGenerator.java // public class OptionGenerator<T> implements Generator<T> { // // private final T[] options; // private final IntGenerator indexGenerator; // // public OptionGenerator(T... options) { // this.options = options; // this.indexGenerator = new IntGenerator(0, options.length); // } // // // @Override // public T generate() { // return options[indexGenerator.generate()]; // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int maxAge = 80; // // Path: src/test/java/au/com/anthonybruno/annotated/GeneratorAnnotationTest.java // public static final int minAge = 18; // Path: src/test/java/au/com/anthonybruno/annotated/AnnotatedPerson.java import au.com.anthonybruno.annotation.Generation; import au.com.anthonybruno.annotation.Range; import au.com.anthonybruno.generator.Generator; import au.com.anthonybruno.generator.OptionGenerator; import au.com.anthonybruno.generator.defaults.IntGenerator; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.maxAge; import static au.com.anthonybruno.annotated.GeneratorAnnotationTest.minAge; package au.com.anthonybruno.annotated; public class AnnotatedPerson { @Generation(NameGenerator.class) private final String name; @Range(min=minAge, max=maxAge) @Generation(value = IntGenerator.class, name="yearsSinceBirth") private final int age; @Generation(GenderGenerator.class) private final String gender; public AnnotatedPerson(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; } public static class NameGenerator implements Generator<String> { private static final String[] names = {"Olivia", "Charlotte", "Mia", "Ava", "Amelia", "Emily", "Sofia", "Ruby"}; private static final int namesLength = names.length; @Override public String generate() { int randIndex = ThreadLocalRandom.current().nextInt(0, namesLength); return names[randIndex]; } public static List<String> getNames() { return Arrays.asList(names); } } public static class GenderGenerator implements Generator<String> {
private final OptionGenerator<String> optionGenerator = new OptionGenerator<>("Female");
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/annotated/IndexedTest.java
// Path: src/main/java/au/com/anthonybruno/Gen.java // public class Gen implements FileTypeDefinition, ResultDefinition, StartDefinition, RecordDefinition, FieldDefinition { // // private int numToGenerate; // private FileFactory fileFactory; // // private Class<?> useClass; // private List<FieldData> fields = new ArrayList<>(); // // public static StartDefinition start() { // return new Gen(); // } // // private Gen() { // // } // // // @Override // public RecordDefinition use(Class<?> c) { // useClass = c; // return this; // } // // @Override // public FieldDefinition addField(String name, Generator generator) { // ArgumentUtils.isNotNull(generator, "Can not add '" + name + "' field with null generator"); // fields.add(new FieldData(name, generator)); // return this; // } // // @Override // public ResultDefinition asCsv() { // return asCsv(new CsvSettings.Builder().build()); // } // // @Override // public ResultDefinition asCsv(CsvSettings csvSettings) { // fileFactory = new CsvFactory(csvSettings, createRecordFactory()); // return this; // } // // @Override // public ResultDefinition asFixedWidth(FixedWidthSettings fixedWidthSettings) { // fileFactory = new FixedWidthFactory(fixedWidthSettings, createRecordFactory()); // return this; // } // // @Override // public File toFile(File file) { // return fileFactory.createFile(file, numToGenerate); // } // // @Override // public File toFile(String path) { // return toFile(new File(path)); // } // // @Override // public String toStringForm() { // checkSetup(); // return fileFactory.createString(numToGenerate); // } // // @Override // public FileTypeDefinition generate(int num) { // this.numToGenerate = num; // return this; // } // // private RecordFactory createRecordFactory() { // if (useClass != null) { // return new ClassRecordFactory(useClass); // } else if (!fields.isEmpty()){ // return new FieldsRecordFactory(fields); // } else { // throw new IllegalStateException("No fields or class added to generator"); // } // } // // private void checkSetup() { // if (useClass == null && fields.isEmpty()) { // throw new IllegalStateException("No generation fields or class specified! Please utilise the #use or #addField methods!"); // } // // if (fileFactory == null) { // throw new IllegalStateException("No file type specified! Use one of the 'as' methods such as #asCsv()"); // } // // if (numToGenerate <= 0) { // throw new IllegalStateException("Need to specify a positive non-zero number of records to generate!"); // } // } // // // }
import au.com.anthonybruno.Gen; import au.com.anthonybruno.annotation.Index; import org.junit.Test; import static org.junit.Assert.assertArrayEquals;
package au.com.anthonybruno.annotated; public class IndexedTest { @Test public void generateCsv() {
// Path: src/main/java/au/com/anthonybruno/Gen.java // public class Gen implements FileTypeDefinition, ResultDefinition, StartDefinition, RecordDefinition, FieldDefinition { // // private int numToGenerate; // private FileFactory fileFactory; // // private Class<?> useClass; // private List<FieldData> fields = new ArrayList<>(); // // public static StartDefinition start() { // return new Gen(); // } // // private Gen() { // // } // // // @Override // public RecordDefinition use(Class<?> c) { // useClass = c; // return this; // } // // @Override // public FieldDefinition addField(String name, Generator generator) { // ArgumentUtils.isNotNull(generator, "Can not add '" + name + "' field with null generator"); // fields.add(new FieldData(name, generator)); // return this; // } // // @Override // public ResultDefinition asCsv() { // return asCsv(new CsvSettings.Builder().build()); // } // // @Override // public ResultDefinition asCsv(CsvSettings csvSettings) { // fileFactory = new CsvFactory(csvSettings, createRecordFactory()); // return this; // } // // @Override // public ResultDefinition asFixedWidth(FixedWidthSettings fixedWidthSettings) { // fileFactory = new FixedWidthFactory(fixedWidthSettings, createRecordFactory()); // return this; // } // // @Override // public File toFile(File file) { // return fileFactory.createFile(file, numToGenerate); // } // // @Override // public File toFile(String path) { // return toFile(new File(path)); // } // // @Override // public String toStringForm() { // checkSetup(); // return fileFactory.createString(numToGenerate); // } // // @Override // public FileTypeDefinition generate(int num) { // this.numToGenerate = num; // return this; // } // // private RecordFactory createRecordFactory() { // if (useClass != null) { // return new ClassRecordFactory(useClass); // } else if (!fields.isEmpty()){ // return new FieldsRecordFactory(fields); // } else { // throw new IllegalStateException("No fields or class added to generator"); // } // } // // private void checkSetup() { // if (useClass == null && fields.isEmpty()) { // throw new IllegalStateException("No generation fields or class specified! Please utilise the #use or #addField methods!"); // } // // if (fileFactory == null) { // throw new IllegalStateException("No file type specified! Use one of the 'as' methods such as #asCsv()"); // } // // if (numToGenerate <= 0) { // throw new IllegalStateException("Need to specify a positive non-zero number of records to generate!"); // } // } // // // } // Path: src/test/java/au/com/anthonybruno/annotated/IndexedTest.java import au.com.anthonybruno.Gen; import au.com.anthonybruno.annotation.Index; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; package au.com.anthonybruno.annotated; public class IndexedTest { @Test public void generateCsv() {
String generated = Gen.start()
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/CsvPojoGenTest.java
// Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // }
import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.utils.TextFile; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.*;
assertNotEquals("Values generated were not random ", 1, values.size()); } @Test public void secondColumnIsRandomised() { String result = generatePersonCsv(); Set<Integer> values = new HashSet<>(); for (String line : result.split("\n")) { int value = Integer.parseInt(line.split(delimiter)[1]); values.add(value); } assertNotEquals("Values generated were not random ", 1, values.size()); } @Test public void containsHeaders() { String result = generatePersonCsvWithHeaders(); String[] headerRows = result.split("\n")[0].split(","); assertEquals("name", headerRows[0]); assertEquals("age", headerRows[1]); assertEquals("birthday", headerRows[2]); } @Test public void createFile() { File file = generatePersonCsvFile(); assertNotNull(file);
// Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // } // Path: src/test/java/au/com/anthonybruno/CsvPojoGenTest.java import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.utils.TextFile; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.*; assertNotEquals("Values generated were not random ", 1, values.size()); } @Test public void secondColumnIsRandomised() { String result = generatePersonCsv(); Set<Integer> values = new HashSet<>(); for (String line : result.split("\n")) { int value = Integer.parseInt(line.split(delimiter)[1]); values.add(value); } assertNotEquals("Values generated were not random ", 1, values.size()); } @Test public void containsHeaders() { String result = generatePersonCsvWithHeaders(); String[] headerRows = result.split("\n")[0].split(","); assertEquals("name", headerRows[0]); assertEquals("age", headerRows[1]); assertEquals("birthday", headerRows[2]); } @Test public void createFile() { File file = generatePersonCsvFile(); assertNotNull(file);
TextFile readFile = new TextFile(file);
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/CsvPojoGenTest.java
// Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // }
import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.utils.TextFile; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.*;
for (String line : result.split("\n")) { int value = Integer.parseInt(line.split(delimiter)[1]); values.add(value); } assertNotEquals("Values generated were not random ", 1, values.size()); } @Test public void containsHeaders() { String result = generatePersonCsvWithHeaders(); String[] headerRows = result.split("\n")[0].split(","); assertEquals("name", headerRows[0]); assertEquals("age", headerRows[1]); assertEquals("birthday", headerRows[2]); } @Test public void createFile() { File file = generatePersonCsvFile(); assertNotNull(file); TextFile readFile = new TextFile(file); assertTrue(!readFile.getText().isEmpty()); } @Test public void generateCsvWithTabs() {
// Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // } // Path: src/test/java/au/com/anthonybruno/CsvPojoGenTest.java import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.utils.TextFile; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.*; for (String line : result.split("\n")) { int value = Integer.parseInt(line.split(delimiter)[1]); values.add(value); } assertNotEquals("Values generated were not random ", 1, values.size()); } @Test public void containsHeaders() { String result = generatePersonCsvWithHeaders(); String[] headerRows = result.split("\n")[0].split(","); assertEquals("name", headerRows[0]); assertEquals("age", headerRows[1]); assertEquals("birthday", headerRows[2]); } @Test public void createFile() { File file = generatePersonCsvFile(); assertNotNull(file); TextFile readFile = new TextFile(file); assertTrue(!readFile.getText().isEmpty()); } @Test public void generateCsvWithTabs() {
CsvSettings csvSettings = new CsvSettings.Builder().setDelimiter('\t').build();
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/creator/CsvFactory.java
// Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/factory/RecordFactory.java // public interface RecordFactory { // // RecordSupplier getRecordSupplier(); // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java // public class WriterFactory { // // public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { // return new UnivocityCsvWriter(writer, csvSettings); // } // // public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // return new UnivocityFixedWidthWriter(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/AbstractCsvWriter.java // public abstract class AbstractCsvWriter extends FlatFileWriter<CsvSettings> { // // public AbstractCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // } // }
import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.factory.RecordFactory; import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.utils.TextFile; import au.com.anthonybruno.writer.WriterFactory; import au.com.anthonybruno.writer.csv.AbstractCsvWriter; import java.io.File; import java.io.StringWriter;
package au.com.anthonybruno.creator; public class CsvFactory extends FlatFileFactory<CsvSettings> { public CsvFactory(CsvSettings settings, RecordFactory recordFactory) { super(settings, recordFactory); } @Override public String createString(int rowsToGenerate) { StringWriter stringWriter = new StringWriter();
// Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/factory/RecordFactory.java // public interface RecordFactory { // // RecordSupplier getRecordSupplier(); // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java // public class WriterFactory { // // public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { // return new UnivocityCsvWriter(writer, csvSettings); // } // // public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // return new UnivocityFixedWidthWriter(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/AbstractCsvWriter.java // public abstract class AbstractCsvWriter extends FlatFileWriter<CsvSettings> { // // public AbstractCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // } // } // Path: src/main/java/au/com/anthonybruno/creator/CsvFactory.java import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.factory.RecordFactory; import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.utils.TextFile; import au.com.anthonybruno.writer.WriterFactory; import au.com.anthonybruno.writer.csv.AbstractCsvWriter; import java.io.File; import java.io.StringWriter; package au.com.anthonybruno.creator; public class CsvFactory extends FlatFileFactory<CsvSettings> { public CsvFactory(CsvSettings settings, RecordFactory recordFactory) { super(settings, recordFactory); } @Override public String createString(int rowsToGenerate) { StringWriter stringWriter = new StringWriter();
try (AbstractCsvWriter csvWriter = WriterFactory.getDefaultCsvWriter(stringWriter, settings)) {
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/creator/CsvFactory.java
// Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/factory/RecordFactory.java // public interface RecordFactory { // // RecordSupplier getRecordSupplier(); // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java // public class WriterFactory { // // public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { // return new UnivocityCsvWriter(writer, csvSettings); // } // // public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // return new UnivocityFixedWidthWriter(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/AbstractCsvWriter.java // public abstract class AbstractCsvWriter extends FlatFileWriter<CsvSettings> { // // public AbstractCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // } // }
import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.factory.RecordFactory; import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.utils.TextFile; import au.com.anthonybruno.writer.WriterFactory; import au.com.anthonybruno.writer.csv.AbstractCsvWriter; import java.io.File; import java.io.StringWriter;
package au.com.anthonybruno.creator; public class CsvFactory extends FlatFileFactory<CsvSettings> { public CsvFactory(CsvSettings settings, RecordFactory recordFactory) { super(settings, recordFactory); } @Override public String createString(int rowsToGenerate) { StringWriter stringWriter = new StringWriter();
// Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/factory/RecordFactory.java // public interface RecordFactory { // // RecordSupplier getRecordSupplier(); // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java // public class WriterFactory { // // public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { // return new UnivocityCsvWriter(writer, csvSettings); // } // // public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // return new UnivocityFixedWidthWriter(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/AbstractCsvWriter.java // public abstract class AbstractCsvWriter extends FlatFileWriter<CsvSettings> { // // public AbstractCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // } // } // Path: src/main/java/au/com/anthonybruno/creator/CsvFactory.java import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.factory.RecordFactory; import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.utils.TextFile; import au.com.anthonybruno.writer.WriterFactory; import au.com.anthonybruno.writer.csv.AbstractCsvWriter; import java.io.File; import java.io.StringWriter; package au.com.anthonybruno.creator; public class CsvFactory extends FlatFileFactory<CsvSettings> { public CsvFactory(CsvSettings settings, RecordFactory recordFactory) { super(settings, recordFactory); } @Override public String createString(int rowsToGenerate) { StringWriter stringWriter = new StringWriter();
try (AbstractCsvWriter csvWriter = WriterFactory.getDefaultCsvWriter(stringWriter, settings)) {
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/creator/CsvFactory.java
// Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/factory/RecordFactory.java // public interface RecordFactory { // // RecordSupplier getRecordSupplier(); // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java // public class WriterFactory { // // public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { // return new UnivocityCsvWriter(writer, csvSettings); // } // // public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // return new UnivocityFixedWidthWriter(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/AbstractCsvWriter.java // public abstract class AbstractCsvWriter extends FlatFileWriter<CsvSettings> { // // public AbstractCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // } // }
import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.factory.RecordFactory; import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.utils.TextFile; import au.com.anthonybruno.writer.WriterFactory; import au.com.anthonybruno.writer.csv.AbstractCsvWriter; import java.io.File; import java.io.StringWriter;
package au.com.anthonybruno.creator; public class CsvFactory extends FlatFileFactory<CsvSettings> { public CsvFactory(CsvSettings settings, RecordFactory recordFactory) { super(settings, recordFactory); } @Override public String createString(int rowsToGenerate) { StringWriter stringWriter = new StringWriter(); try (AbstractCsvWriter csvWriter = WriterFactory.getDefaultCsvWriter(stringWriter, settings)) { writeValues(csvWriter, rowsToGenerate); } return stringWriter.toString(); } private void writeValues(AbstractCsvWriter writer, int rowsToGenerate) {
// Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/factory/RecordFactory.java // public interface RecordFactory { // // RecordSupplier getRecordSupplier(); // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java // public class WriterFactory { // // public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { // return new UnivocityCsvWriter(writer, csvSettings); // } // // public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // return new UnivocityFixedWidthWriter(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/AbstractCsvWriter.java // public abstract class AbstractCsvWriter extends FlatFileWriter<CsvSettings> { // // public AbstractCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // } // } // Path: src/main/java/au/com/anthonybruno/creator/CsvFactory.java import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.factory.RecordFactory; import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.utils.TextFile; import au.com.anthonybruno.writer.WriterFactory; import au.com.anthonybruno.writer.csv.AbstractCsvWriter; import java.io.File; import java.io.StringWriter; package au.com.anthonybruno.creator; public class CsvFactory extends FlatFileFactory<CsvSettings> { public CsvFactory(CsvSettings settings, RecordFactory recordFactory) { super(settings, recordFactory); } @Override public String createString(int rowsToGenerate) { StringWriter stringWriter = new StringWriter(); try (AbstractCsvWriter csvWriter = WriterFactory.getDefaultCsvWriter(stringWriter, settings)) { writeValues(csvWriter, rowsToGenerate); } return stringWriter.toString(); } private void writeValues(AbstractCsvWriter writer, int rowsToGenerate) {
RecordSupplier records = recordFactory.getRecordSupplier();
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/creator/CsvFactory.java
// Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/factory/RecordFactory.java // public interface RecordFactory { // // RecordSupplier getRecordSupplier(); // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java // public class WriterFactory { // // public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { // return new UnivocityCsvWriter(writer, csvSettings); // } // // public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // return new UnivocityFixedWidthWriter(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/AbstractCsvWriter.java // public abstract class AbstractCsvWriter extends FlatFileWriter<CsvSettings> { // // public AbstractCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // } // }
import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.factory.RecordFactory; import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.utils.TextFile; import au.com.anthonybruno.writer.WriterFactory; import au.com.anthonybruno.writer.csv.AbstractCsvWriter; import java.io.File; import java.io.StringWriter;
package au.com.anthonybruno.creator; public class CsvFactory extends FlatFileFactory<CsvSettings> { public CsvFactory(CsvSettings settings, RecordFactory recordFactory) { super(settings, recordFactory); } @Override public String createString(int rowsToGenerate) { StringWriter stringWriter = new StringWriter(); try (AbstractCsvWriter csvWriter = WriterFactory.getDefaultCsvWriter(stringWriter, settings)) { writeValues(csvWriter, rowsToGenerate); } return stringWriter.toString(); } private void writeValues(AbstractCsvWriter writer, int rowsToGenerate) { RecordSupplier records = recordFactory.getRecordSupplier(); if (settings.isIncludingHeaders()) { writer.writeRow(records.getFields()); } records.supplyRecords(rowsToGenerate) .forEach(record -> { writer.writeRecord(record); }); } @Override public File createFile(File file, int rowsToGenerate) {
// Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/factory/RecordFactory.java // public interface RecordFactory { // // RecordSupplier getRecordSupplier(); // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/utils/TextFile.java // public class TextFile { // // public static final Charset DEFAULT_ENCODING = Charset.forName("utf-8"); // // private final File file; // private final Lazy<String> text; // private final Charset encoding; // // public TextFile(File file) { // this(file, DEFAULT_ENCODING); // } // // public TextFile(File file, Charset encoding) { // if (!file.exists()) { // throw new IllegalArgumentException(file + " does not exist."); // } // this.file = file; // this.text = new Lazy<>(() -> readTextFromFile(file)); // this.encoding = encoding; // } // // public Writer getWriter() { // try { // return new FileWriter(file); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // // public String getText() { // return text.get(); // } // // private String readTextFromFile(File file) { // BufferedReader reader; // try { // reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); // } catch (FileNotFoundException e) { // throw new IllegalArgumentException(e); // } // StringBuilder stringBuilder = new StringBuilder(); // reader.lines().forEach((line) -> stringBuilder.append(line).append("\n")); // return stringBuilder.toString(); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java // public class WriterFactory { // // public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { // return new UnivocityCsvWriter(writer, csvSettings); // } // // public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // return new UnivocityFixedWidthWriter(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/AbstractCsvWriter.java // public abstract class AbstractCsvWriter extends FlatFileWriter<CsvSettings> { // // public AbstractCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // } // } // Path: src/main/java/au/com/anthonybruno/creator/CsvFactory.java import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.factory.RecordFactory; import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.utils.TextFile; import au.com.anthonybruno.writer.WriterFactory; import au.com.anthonybruno.writer.csv.AbstractCsvWriter; import java.io.File; import java.io.StringWriter; package au.com.anthonybruno.creator; public class CsvFactory extends FlatFileFactory<CsvSettings> { public CsvFactory(CsvSettings settings, RecordFactory recordFactory) { super(settings, recordFactory); } @Override public String createString(int rowsToGenerate) { StringWriter stringWriter = new StringWriter(); try (AbstractCsvWriter csvWriter = WriterFactory.getDefaultCsvWriter(stringWriter, settings)) { writeValues(csvWriter, rowsToGenerate); } return stringWriter.toString(); } private void writeValues(AbstractCsvWriter writer, int rowsToGenerate) { RecordSupplier records = recordFactory.getRecordSupplier(); if (settings.isIncludingHeaders()) { writer.writeRow(records.getFields()); } records.supplyRecords(rowsToGenerate) .forEach(record -> { writer.writeRecord(record); }); } @Override public File createFile(File file, int rowsToGenerate) {
try (AbstractCsvWriter csvWriter = WriterFactory.getDefaultCsvWriter(new TextFile(file).getWriter(), settings)) {
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/definition/FileTypeDefinition.java
// Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // }
import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.settings.FixedWidthSettings;
package au.com.anthonybruno.definition; /** * Defines the file format of the generated data. * * @author Anthony Bruno */ public interface FileTypeDefinition { /** * Sets the format to csv. * * @return a ResultDefinition object to specify how the generated data is saved. */ ResultDefinition asCsv(); /** * Sets the format to csv with configuration options given by the specified settings object. * * @param settings a CsvSettings object which configures how the csv is created such as whether or include a heading row. * * @return a ResultDefinition object to specify how the generated data is saved. */
// Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // Path: src/main/java/au/com/anthonybruno/definition/FileTypeDefinition.java import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.settings.FixedWidthSettings; package au.com.anthonybruno.definition; /** * Defines the file format of the generated data. * * @author Anthony Bruno */ public interface FileTypeDefinition { /** * Sets the format to csv. * * @return a ResultDefinition object to specify how the generated data is saved. */ ResultDefinition asCsv(); /** * Sets the format to csv with configuration options given by the specified settings object. * * @param settings a CsvSettings object which configures how the csv is created such as whether or include a heading row. * * @return a ResultDefinition object to specify how the generated data is saved. */
ResultDefinition asCsv(CsvSettings settings);
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/definition/FileTypeDefinition.java
// Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // }
import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.settings.FixedWidthSettings;
package au.com.anthonybruno.definition; /** * Defines the file format of the generated data. * * @author Anthony Bruno */ public interface FileTypeDefinition { /** * Sets the format to csv. * * @return a ResultDefinition object to specify how the generated data is saved. */ ResultDefinition asCsv(); /** * Sets the format to csv with configuration options given by the specified settings object. * * @param settings a CsvSettings object which configures how the csv is created such as whether or include a heading row. * * @return a ResultDefinition object to specify how the generated data is saved. */ ResultDefinition asCsv(CsvSettings settings); /** * Sets the format to be fixed width with configuration options given by the specified settings object. * * @param fixedWidthSettings a FixedWidthSettings object that specifies the fixed width desired * * @return a ResultDefinition object to specify how the generated data is saved. */
// Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // Path: src/main/java/au/com/anthonybruno/definition/FileTypeDefinition.java import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.settings.FixedWidthSettings; package au.com.anthonybruno.definition; /** * Defines the file format of the generated data. * * @author Anthony Bruno */ public interface FileTypeDefinition { /** * Sets the format to csv. * * @return a ResultDefinition object to specify how the generated data is saved. */ ResultDefinition asCsv(); /** * Sets the format to csv with configuration options given by the specified settings object. * * @param settings a CsvSettings object which configures how the csv is created such as whether or include a heading row. * * @return a ResultDefinition object to specify how the generated data is saved. */ ResultDefinition asCsv(CsvSettings settings); /** * Sets the format to be fixed width with configuration options given by the specified settings object. * * @param fixedWidthSettings a FixedWidthSettings object that specifies the fixed width desired * * @return a ResultDefinition object to specify how the generated data is saved. */
ResultDefinition asFixedWidth(FixedWidthSettings fixedWidthSettings);
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/generator/PrimitiveGeneratorsTest.java
// Path: src/main/java/au/com/anthonybruno/generator/defaults/BooleanGenerator.java // public class BooleanGenerator implements Generator<Boolean> { // // @Override // public Boolean generate() { // return ThreadLocalRandom.current().nextBoolean(); // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/StringGenerator.java // public class StringGenerator implements Generator<String> { // // private final CharGenerator charGenerator = new CharGenerator(); // // @Override // public String generate() { // StringBuilder stringBuilder = new StringBuilder(); // ThreadLocalRandom random = ThreadLocalRandom.current(); // int length = random.nextInt(2, 10); // for (int i = 0; i < length; i++) { // stringBuilder.append(charGenerator.generate()); // } // return stringBuilder.toString(); // } // }
import au.com.anthonybruno.generator.defaults.BooleanGenerator; import au.com.anthonybruno.generator.defaults.StringGenerator; import org.junit.Test; import java.util.HashSet; import java.util.Set; import static junit.framework.TestCase.assertTrue;
package au.com.anthonybruno.generator; public class PrimitiveGeneratorsTest { @Test public void stringGeneration() {
// Path: src/main/java/au/com/anthonybruno/generator/defaults/BooleanGenerator.java // public class BooleanGenerator implements Generator<Boolean> { // // @Override // public Boolean generate() { // return ThreadLocalRandom.current().nextBoolean(); // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/StringGenerator.java // public class StringGenerator implements Generator<String> { // // private final CharGenerator charGenerator = new CharGenerator(); // // @Override // public String generate() { // StringBuilder stringBuilder = new StringBuilder(); // ThreadLocalRandom random = ThreadLocalRandom.current(); // int length = random.nextInt(2, 10); // for (int i = 0; i < length; i++) { // stringBuilder.append(charGenerator.generate()); // } // return stringBuilder.toString(); // } // } // Path: src/test/java/au/com/anthonybruno/generator/PrimitiveGeneratorsTest.java import au.com.anthonybruno.generator.defaults.BooleanGenerator; import au.com.anthonybruno.generator.defaults.StringGenerator; import org.junit.Test; import java.util.HashSet; import java.util.Set; import static junit.framework.TestCase.assertTrue; package au.com.anthonybruno.generator; public class PrimitiveGeneratorsTest { @Test public void stringGeneration() {
StringGenerator generator = new StringGenerator();
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/generator/PrimitiveGeneratorsTest.java
// Path: src/main/java/au/com/anthonybruno/generator/defaults/BooleanGenerator.java // public class BooleanGenerator implements Generator<Boolean> { // // @Override // public Boolean generate() { // return ThreadLocalRandom.current().nextBoolean(); // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/StringGenerator.java // public class StringGenerator implements Generator<String> { // // private final CharGenerator charGenerator = new CharGenerator(); // // @Override // public String generate() { // StringBuilder stringBuilder = new StringBuilder(); // ThreadLocalRandom random = ThreadLocalRandom.current(); // int length = random.nextInt(2, 10); // for (int i = 0; i < length; i++) { // stringBuilder.append(charGenerator.generate()); // } // return stringBuilder.toString(); // } // }
import au.com.anthonybruno.generator.defaults.BooleanGenerator; import au.com.anthonybruno.generator.defaults.StringGenerator; import org.junit.Test; import java.util.HashSet; import java.util.Set; import static junit.framework.TestCase.assertTrue;
package au.com.anthonybruno.generator; public class PrimitiveGeneratorsTest { @Test public void stringGeneration() { StringGenerator generator = new StringGenerator(); int numValues = 100000; Set<String> set = new HashSet<>(); for (int i = 0; i < numValues; i++) { String value = generator.generate(); set.add(value); } assertTrue(set.size() + "", set.size() >= 90000); //ensure most values generated are random } @Test public void booleanGenerator() {
// Path: src/main/java/au/com/anthonybruno/generator/defaults/BooleanGenerator.java // public class BooleanGenerator implements Generator<Boolean> { // // @Override // public Boolean generate() { // return ThreadLocalRandom.current().nextBoolean(); // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/StringGenerator.java // public class StringGenerator implements Generator<String> { // // private final CharGenerator charGenerator = new CharGenerator(); // // @Override // public String generate() { // StringBuilder stringBuilder = new StringBuilder(); // ThreadLocalRandom random = ThreadLocalRandom.current(); // int length = random.nextInt(2, 10); // for (int i = 0; i < length; i++) { // stringBuilder.append(charGenerator.generate()); // } // return stringBuilder.toString(); // } // } // Path: src/test/java/au/com/anthonybruno/generator/PrimitiveGeneratorsTest.java import au.com.anthonybruno.generator.defaults.BooleanGenerator; import au.com.anthonybruno.generator.defaults.StringGenerator; import org.junit.Test; import java.util.HashSet; import java.util.Set; import static junit.framework.TestCase.assertTrue; package au.com.anthonybruno.generator; public class PrimitiveGeneratorsTest { @Test public void stringGeneration() { StringGenerator generator = new StringGenerator(); int numValues = 100000; Set<String> set = new HashSet<>(); for (int i = 0; i < numValues; i++) { String value = generator.generate(); set.add(value); } assertTrue(set.size() + "", set.size() >= 90000); //ensure most values generated are random } @Test public void booleanGenerator() {
BooleanGenerator generator = new BooleanGenerator();
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/writer/WriterFactory.java
// Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/AbstractCsvWriter.java // public abstract class AbstractCsvWriter extends FlatFileWriter<CsvSettings> { // // public AbstractCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/UnivocityCsvWriter.java // public class UnivocityCsvWriter extends AbstractCsvWriter { // // private final CsvWriter csvWriter; // // public UnivocityCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // CsvWriterSettings csvWriterSettings = new CsvWriterSettings(); // csvWriterSettings.getFormat().setDelimiter(settings.getDelimiter()); // this.csvWriter = new CsvWriter(writer, csvWriterSettings); // } // // @Override // public void writeRow(List<String> row) { // for (String value : row) { // csvWriter.addValue(value); // } // csvWriter.writeValuesToRow(); // } // // @Override // public void close() { // csvWriter.close(); // } // // @Override // public void writeRecord(Record record) { // List<String> values = new ArrayList<>(); // record.forEach((value) -> { // values.add(value.toString()); // }); // writeRow(values); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/AbstractFixedWidthWriter.java // public abstract class AbstractFixedWidthWriter extends FlatFileWriter<FixedWidthSettings> { // // public AbstractFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/UnivocityFixedWidthWriter.java // public class UnivocityFixedWidthWriter extends AbstractFixedWidthWriter { // // private FixedWidthWriter fixedWidthWriter; // // // public UnivocityFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // FixedWidthFields fixedWidthFields = new FixedWidthFields(); // settings.getFixedWidthFields().forEach((field) -> { // fixedWidthFields.addField(field.getLength()); // }); // FixedWidthWriterSettings univocitySettings = new FixedWidthWriterSettings(fixedWidthFields); // this.fixedWidthWriter = new FixedWidthWriter(writer, univocitySettings); // } // // @Override // public void writeRow(List<String> row) { // fixedWidthWriter.writeRow(row); // fixedWidthWriter.writeValuesToRow(); // } // // @Override // public void writeRecord(Record record) { // List<String> values = new ArrayList<>(); // record.forEach((value) -> { // values.add(value.toString()); // }); // writeRow(values); // } // // @Override // public void close() { // fixedWidthWriter.close(); // } // }
import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.settings.FixedWidthSettings; import au.com.anthonybruno.writer.csv.AbstractCsvWriter; import au.com.anthonybruno.writer.csv.UnivocityCsvWriter; import au.com.anthonybruno.writer.fixedwidth.AbstractFixedWidthWriter; import au.com.anthonybruno.writer.fixedwidth.UnivocityFixedWidthWriter; import java.io.Writer;
package au.com.anthonybruno.writer; public class WriterFactory { public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) {
// Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/AbstractCsvWriter.java // public abstract class AbstractCsvWriter extends FlatFileWriter<CsvSettings> { // // public AbstractCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/UnivocityCsvWriter.java // public class UnivocityCsvWriter extends AbstractCsvWriter { // // private final CsvWriter csvWriter; // // public UnivocityCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // CsvWriterSettings csvWriterSettings = new CsvWriterSettings(); // csvWriterSettings.getFormat().setDelimiter(settings.getDelimiter()); // this.csvWriter = new CsvWriter(writer, csvWriterSettings); // } // // @Override // public void writeRow(List<String> row) { // for (String value : row) { // csvWriter.addValue(value); // } // csvWriter.writeValuesToRow(); // } // // @Override // public void close() { // csvWriter.close(); // } // // @Override // public void writeRecord(Record record) { // List<String> values = new ArrayList<>(); // record.forEach((value) -> { // values.add(value.toString()); // }); // writeRow(values); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/AbstractFixedWidthWriter.java // public abstract class AbstractFixedWidthWriter extends FlatFileWriter<FixedWidthSettings> { // // public AbstractFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/UnivocityFixedWidthWriter.java // public class UnivocityFixedWidthWriter extends AbstractFixedWidthWriter { // // private FixedWidthWriter fixedWidthWriter; // // // public UnivocityFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // FixedWidthFields fixedWidthFields = new FixedWidthFields(); // settings.getFixedWidthFields().forEach((field) -> { // fixedWidthFields.addField(field.getLength()); // }); // FixedWidthWriterSettings univocitySettings = new FixedWidthWriterSettings(fixedWidthFields); // this.fixedWidthWriter = new FixedWidthWriter(writer, univocitySettings); // } // // @Override // public void writeRow(List<String> row) { // fixedWidthWriter.writeRow(row); // fixedWidthWriter.writeValuesToRow(); // } // // @Override // public void writeRecord(Record record) { // List<String> values = new ArrayList<>(); // record.forEach((value) -> { // values.add(value.toString()); // }); // writeRow(values); // } // // @Override // public void close() { // fixedWidthWriter.close(); // } // } // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.settings.FixedWidthSettings; import au.com.anthonybruno.writer.csv.AbstractCsvWriter; import au.com.anthonybruno.writer.csv.UnivocityCsvWriter; import au.com.anthonybruno.writer.fixedwidth.AbstractFixedWidthWriter; import au.com.anthonybruno.writer.fixedwidth.UnivocityFixedWidthWriter; import java.io.Writer; package au.com.anthonybruno.writer; public class WriterFactory { public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) {
return new UnivocityCsvWriter(writer, csvSettings);
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/writer/WriterFactory.java
// Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/AbstractCsvWriter.java // public abstract class AbstractCsvWriter extends FlatFileWriter<CsvSettings> { // // public AbstractCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/UnivocityCsvWriter.java // public class UnivocityCsvWriter extends AbstractCsvWriter { // // private final CsvWriter csvWriter; // // public UnivocityCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // CsvWriterSettings csvWriterSettings = new CsvWriterSettings(); // csvWriterSettings.getFormat().setDelimiter(settings.getDelimiter()); // this.csvWriter = new CsvWriter(writer, csvWriterSettings); // } // // @Override // public void writeRow(List<String> row) { // for (String value : row) { // csvWriter.addValue(value); // } // csvWriter.writeValuesToRow(); // } // // @Override // public void close() { // csvWriter.close(); // } // // @Override // public void writeRecord(Record record) { // List<String> values = new ArrayList<>(); // record.forEach((value) -> { // values.add(value.toString()); // }); // writeRow(values); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/AbstractFixedWidthWriter.java // public abstract class AbstractFixedWidthWriter extends FlatFileWriter<FixedWidthSettings> { // // public AbstractFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/UnivocityFixedWidthWriter.java // public class UnivocityFixedWidthWriter extends AbstractFixedWidthWriter { // // private FixedWidthWriter fixedWidthWriter; // // // public UnivocityFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // FixedWidthFields fixedWidthFields = new FixedWidthFields(); // settings.getFixedWidthFields().forEach((field) -> { // fixedWidthFields.addField(field.getLength()); // }); // FixedWidthWriterSettings univocitySettings = new FixedWidthWriterSettings(fixedWidthFields); // this.fixedWidthWriter = new FixedWidthWriter(writer, univocitySettings); // } // // @Override // public void writeRow(List<String> row) { // fixedWidthWriter.writeRow(row); // fixedWidthWriter.writeValuesToRow(); // } // // @Override // public void writeRecord(Record record) { // List<String> values = new ArrayList<>(); // record.forEach((value) -> { // values.add(value.toString()); // }); // writeRow(values); // } // // @Override // public void close() { // fixedWidthWriter.close(); // } // }
import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.settings.FixedWidthSettings; import au.com.anthonybruno.writer.csv.AbstractCsvWriter; import au.com.anthonybruno.writer.csv.UnivocityCsvWriter; import au.com.anthonybruno.writer.fixedwidth.AbstractFixedWidthWriter; import au.com.anthonybruno.writer.fixedwidth.UnivocityFixedWidthWriter; import java.io.Writer;
package au.com.anthonybruno.writer; public class WriterFactory { public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { return new UnivocityCsvWriter(writer, csvSettings); }
// Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/AbstractCsvWriter.java // public abstract class AbstractCsvWriter extends FlatFileWriter<CsvSettings> { // // public AbstractCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/UnivocityCsvWriter.java // public class UnivocityCsvWriter extends AbstractCsvWriter { // // private final CsvWriter csvWriter; // // public UnivocityCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // CsvWriterSettings csvWriterSettings = new CsvWriterSettings(); // csvWriterSettings.getFormat().setDelimiter(settings.getDelimiter()); // this.csvWriter = new CsvWriter(writer, csvWriterSettings); // } // // @Override // public void writeRow(List<String> row) { // for (String value : row) { // csvWriter.addValue(value); // } // csvWriter.writeValuesToRow(); // } // // @Override // public void close() { // csvWriter.close(); // } // // @Override // public void writeRecord(Record record) { // List<String> values = new ArrayList<>(); // record.forEach((value) -> { // values.add(value.toString()); // }); // writeRow(values); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/AbstractFixedWidthWriter.java // public abstract class AbstractFixedWidthWriter extends FlatFileWriter<FixedWidthSettings> { // // public AbstractFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/UnivocityFixedWidthWriter.java // public class UnivocityFixedWidthWriter extends AbstractFixedWidthWriter { // // private FixedWidthWriter fixedWidthWriter; // // // public UnivocityFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // FixedWidthFields fixedWidthFields = new FixedWidthFields(); // settings.getFixedWidthFields().forEach((field) -> { // fixedWidthFields.addField(field.getLength()); // }); // FixedWidthWriterSettings univocitySettings = new FixedWidthWriterSettings(fixedWidthFields); // this.fixedWidthWriter = new FixedWidthWriter(writer, univocitySettings); // } // // @Override // public void writeRow(List<String> row) { // fixedWidthWriter.writeRow(row); // fixedWidthWriter.writeValuesToRow(); // } // // @Override // public void writeRecord(Record record) { // List<String> values = new ArrayList<>(); // record.forEach((value) -> { // values.add(value.toString()); // }); // writeRow(values); // } // // @Override // public void close() { // fixedWidthWriter.close(); // } // } // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.settings.FixedWidthSettings; import au.com.anthonybruno.writer.csv.AbstractCsvWriter; import au.com.anthonybruno.writer.csv.UnivocityCsvWriter; import au.com.anthonybruno.writer.fixedwidth.AbstractFixedWidthWriter; import au.com.anthonybruno.writer.fixedwidth.UnivocityFixedWidthWriter; import java.io.Writer; package au.com.anthonybruno.writer; public class WriterFactory { public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { return new UnivocityCsvWriter(writer, csvSettings); }
public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) {
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/writer/WriterFactory.java
// Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/AbstractCsvWriter.java // public abstract class AbstractCsvWriter extends FlatFileWriter<CsvSettings> { // // public AbstractCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/UnivocityCsvWriter.java // public class UnivocityCsvWriter extends AbstractCsvWriter { // // private final CsvWriter csvWriter; // // public UnivocityCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // CsvWriterSettings csvWriterSettings = new CsvWriterSettings(); // csvWriterSettings.getFormat().setDelimiter(settings.getDelimiter()); // this.csvWriter = new CsvWriter(writer, csvWriterSettings); // } // // @Override // public void writeRow(List<String> row) { // for (String value : row) { // csvWriter.addValue(value); // } // csvWriter.writeValuesToRow(); // } // // @Override // public void close() { // csvWriter.close(); // } // // @Override // public void writeRecord(Record record) { // List<String> values = new ArrayList<>(); // record.forEach((value) -> { // values.add(value.toString()); // }); // writeRow(values); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/AbstractFixedWidthWriter.java // public abstract class AbstractFixedWidthWriter extends FlatFileWriter<FixedWidthSettings> { // // public AbstractFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/UnivocityFixedWidthWriter.java // public class UnivocityFixedWidthWriter extends AbstractFixedWidthWriter { // // private FixedWidthWriter fixedWidthWriter; // // // public UnivocityFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // FixedWidthFields fixedWidthFields = new FixedWidthFields(); // settings.getFixedWidthFields().forEach((field) -> { // fixedWidthFields.addField(field.getLength()); // }); // FixedWidthWriterSettings univocitySettings = new FixedWidthWriterSettings(fixedWidthFields); // this.fixedWidthWriter = new FixedWidthWriter(writer, univocitySettings); // } // // @Override // public void writeRow(List<String> row) { // fixedWidthWriter.writeRow(row); // fixedWidthWriter.writeValuesToRow(); // } // // @Override // public void writeRecord(Record record) { // List<String> values = new ArrayList<>(); // record.forEach((value) -> { // values.add(value.toString()); // }); // writeRow(values); // } // // @Override // public void close() { // fixedWidthWriter.close(); // } // }
import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.settings.FixedWidthSettings; import au.com.anthonybruno.writer.csv.AbstractCsvWriter; import au.com.anthonybruno.writer.csv.UnivocityCsvWriter; import au.com.anthonybruno.writer.fixedwidth.AbstractFixedWidthWriter; import au.com.anthonybruno.writer.fixedwidth.UnivocityFixedWidthWriter; import java.io.Writer;
package au.com.anthonybruno.writer; public class WriterFactory { public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { return new UnivocityCsvWriter(writer, csvSettings); }
// Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/AbstractCsvWriter.java // public abstract class AbstractCsvWriter extends FlatFileWriter<CsvSettings> { // // public AbstractCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/UnivocityCsvWriter.java // public class UnivocityCsvWriter extends AbstractCsvWriter { // // private final CsvWriter csvWriter; // // public UnivocityCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // CsvWriterSettings csvWriterSettings = new CsvWriterSettings(); // csvWriterSettings.getFormat().setDelimiter(settings.getDelimiter()); // this.csvWriter = new CsvWriter(writer, csvWriterSettings); // } // // @Override // public void writeRow(List<String> row) { // for (String value : row) { // csvWriter.addValue(value); // } // csvWriter.writeValuesToRow(); // } // // @Override // public void close() { // csvWriter.close(); // } // // @Override // public void writeRecord(Record record) { // List<String> values = new ArrayList<>(); // record.forEach((value) -> { // values.add(value.toString()); // }); // writeRow(values); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/AbstractFixedWidthWriter.java // public abstract class AbstractFixedWidthWriter extends FlatFileWriter<FixedWidthSettings> { // // public AbstractFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/UnivocityFixedWidthWriter.java // public class UnivocityFixedWidthWriter extends AbstractFixedWidthWriter { // // private FixedWidthWriter fixedWidthWriter; // // // public UnivocityFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // FixedWidthFields fixedWidthFields = new FixedWidthFields(); // settings.getFixedWidthFields().forEach((field) -> { // fixedWidthFields.addField(field.getLength()); // }); // FixedWidthWriterSettings univocitySettings = new FixedWidthWriterSettings(fixedWidthFields); // this.fixedWidthWriter = new FixedWidthWriter(writer, univocitySettings); // } // // @Override // public void writeRow(List<String> row) { // fixedWidthWriter.writeRow(row); // fixedWidthWriter.writeValuesToRow(); // } // // @Override // public void writeRecord(Record record) { // List<String> values = new ArrayList<>(); // record.forEach((value) -> { // values.add(value.toString()); // }); // writeRow(values); // } // // @Override // public void close() { // fixedWidthWriter.close(); // } // } // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.settings.FixedWidthSettings; import au.com.anthonybruno.writer.csv.AbstractCsvWriter; import au.com.anthonybruno.writer.csv.UnivocityCsvWriter; import au.com.anthonybruno.writer.fixedwidth.AbstractFixedWidthWriter; import au.com.anthonybruno.writer.fixedwidth.UnivocityFixedWidthWriter; import java.io.Writer; package au.com.anthonybruno.writer; public class WriterFactory { public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { return new UnivocityCsvWriter(writer, csvSettings); }
public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) {
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/writer/WriterFactory.java
// Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/AbstractCsvWriter.java // public abstract class AbstractCsvWriter extends FlatFileWriter<CsvSettings> { // // public AbstractCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/UnivocityCsvWriter.java // public class UnivocityCsvWriter extends AbstractCsvWriter { // // private final CsvWriter csvWriter; // // public UnivocityCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // CsvWriterSettings csvWriterSettings = new CsvWriterSettings(); // csvWriterSettings.getFormat().setDelimiter(settings.getDelimiter()); // this.csvWriter = new CsvWriter(writer, csvWriterSettings); // } // // @Override // public void writeRow(List<String> row) { // for (String value : row) { // csvWriter.addValue(value); // } // csvWriter.writeValuesToRow(); // } // // @Override // public void close() { // csvWriter.close(); // } // // @Override // public void writeRecord(Record record) { // List<String> values = new ArrayList<>(); // record.forEach((value) -> { // values.add(value.toString()); // }); // writeRow(values); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/AbstractFixedWidthWriter.java // public abstract class AbstractFixedWidthWriter extends FlatFileWriter<FixedWidthSettings> { // // public AbstractFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/UnivocityFixedWidthWriter.java // public class UnivocityFixedWidthWriter extends AbstractFixedWidthWriter { // // private FixedWidthWriter fixedWidthWriter; // // // public UnivocityFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // FixedWidthFields fixedWidthFields = new FixedWidthFields(); // settings.getFixedWidthFields().forEach((field) -> { // fixedWidthFields.addField(field.getLength()); // }); // FixedWidthWriterSettings univocitySettings = new FixedWidthWriterSettings(fixedWidthFields); // this.fixedWidthWriter = new FixedWidthWriter(writer, univocitySettings); // } // // @Override // public void writeRow(List<String> row) { // fixedWidthWriter.writeRow(row); // fixedWidthWriter.writeValuesToRow(); // } // // @Override // public void writeRecord(Record record) { // List<String> values = new ArrayList<>(); // record.forEach((value) -> { // values.add(value.toString()); // }); // writeRow(values); // } // // @Override // public void close() { // fixedWidthWriter.close(); // } // }
import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.settings.FixedWidthSettings; import au.com.anthonybruno.writer.csv.AbstractCsvWriter; import au.com.anthonybruno.writer.csv.UnivocityCsvWriter; import au.com.anthonybruno.writer.fixedwidth.AbstractFixedWidthWriter; import au.com.anthonybruno.writer.fixedwidth.UnivocityFixedWidthWriter; import java.io.Writer;
package au.com.anthonybruno.writer; public class WriterFactory { public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { return new UnivocityCsvWriter(writer, csvSettings); } public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) {
// Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // // Path: src/main/java/au/com/anthonybruno/settings/FixedWidthSettings.java // public class FixedWidthSettings extends FlatFileSettings { // // private final List<FixedWidthField> fixedWidthFields; // // public FixedWidthSettings(boolean includeHeaders, List<FixedWidthField> fields) { // super(includeHeaders); // this.fixedWidthFields = fields; // } // // public List<FixedWidthField> getFixedWidthFields() { // return fixedWidthFields; // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/AbstractCsvWriter.java // public abstract class AbstractCsvWriter extends FlatFileWriter<CsvSettings> { // // public AbstractCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/csv/UnivocityCsvWriter.java // public class UnivocityCsvWriter extends AbstractCsvWriter { // // private final CsvWriter csvWriter; // // public UnivocityCsvWriter(Writer writer, CsvSettings settings) { // super(writer, settings); // CsvWriterSettings csvWriterSettings = new CsvWriterSettings(); // csvWriterSettings.getFormat().setDelimiter(settings.getDelimiter()); // this.csvWriter = new CsvWriter(writer, csvWriterSettings); // } // // @Override // public void writeRow(List<String> row) { // for (String value : row) { // csvWriter.addValue(value); // } // csvWriter.writeValuesToRow(); // } // // @Override // public void close() { // csvWriter.close(); // } // // @Override // public void writeRecord(Record record) { // List<String> values = new ArrayList<>(); // record.forEach((value) -> { // values.add(value.toString()); // }); // writeRow(values); // } // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/AbstractFixedWidthWriter.java // public abstract class AbstractFixedWidthWriter extends FlatFileWriter<FixedWidthSettings> { // // public AbstractFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // } // // } // // Path: src/main/java/au/com/anthonybruno/writer/fixedwidth/UnivocityFixedWidthWriter.java // public class UnivocityFixedWidthWriter extends AbstractFixedWidthWriter { // // private FixedWidthWriter fixedWidthWriter; // // // public UnivocityFixedWidthWriter(Writer writer, FixedWidthSettings settings) { // super(writer, settings); // FixedWidthFields fixedWidthFields = new FixedWidthFields(); // settings.getFixedWidthFields().forEach((field) -> { // fixedWidthFields.addField(field.getLength()); // }); // FixedWidthWriterSettings univocitySettings = new FixedWidthWriterSettings(fixedWidthFields); // this.fixedWidthWriter = new FixedWidthWriter(writer, univocitySettings); // } // // @Override // public void writeRow(List<String> row) { // fixedWidthWriter.writeRow(row); // fixedWidthWriter.writeValuesToRow(); // } // // @Override // public void writeRecord(Record record) { // List<String> values = new ArrayList<>(); // record.forEach((value) -> { // values.add(value.toString()); // }); // writeRow(values); // } // // @Override // public void close() { // fixedWidthWriter.close(); // } // } // Path: src/main/java/au/com/anthonybruno/writer/WriterFactory.java import au.com.anthonybruno.settings.CsvSettings; import au.com.anthonybruno.settings.FixedWidthSettings; import au.com.anthonybruno.writer.csv.AbstractCsvWriter; import au.com.anthonybruno.writer.csv.UnivocityCsvWriter; import au.com.anthonybruno.writer.fixedwidth.AbstractFixedWidthWriter; import au.com.anthonybruno.writer.fixedwidth.UnivocityFixedWidthWriter; import java.io.Writer; package au.com.anthonybruno.writer; public class WriterFactory { public static AbstractCsvWriter getDefaultCsvWriter(Writer writer, CsvSettings csvSettings) { return new UnivocityCsvWriter(writer, csvSettings); } public static AbstractFixedWidthWriter getDefaultFixedWidthWriter(Writer writer, FixedWidthSettings settings) {
return new UnivocityFixedWidthWriter(writer, settings);
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/writer/csv/UnivocityCsvWriter.java
// Path: src/main/java/au/com/anthonybruno/record/Record.java // public interface Record extends Iterable<Object> { // // Object get(int index); // // Object get(String fieldName); // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // }
import au.com.anthonybruno.record.Record; import au.com.anthonybruno.settings.CsvSettings; import com.univocity.parsers.csv.CsvWriter; import com.univocity.parsers.csv.CsvWriterSettings; import java.io.Writer; import java.util.ArrayList; import java.util.List;
package au.com.anthonybruno.writer.csv; public class UnivocityCsvWriter extends AbstractCsvWriter { private final CsvWriter csvWriter;
// Path: src/main/java/au/com/anthonybruno/record/Record.java // public interface Record extends Iterable<Object> { // // Object get(int index); // // Object get(String fieldName); // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // Path: src/main/java/au/com/anthonybruno/writer/csv/UnivocityCsvWriter.java import au.com.anthonybruno.record.Record; import au.com.anthonybruno.settings.CsvSettings; import com.univocity.parsers.csv.CsvWriter; import com.univocity.parsers.csv.CsvWriterSettings; import java.io.Writer; import java.util.ArrayList; import java.util.List; package au.com.anthonybruno.writer.csv; public class UnivocityCsvWriter extends AbstractCsvWriter { private final CsvWriter csvWriter;
public UnivocityCsvWriter(Writer writer, CsvSettings settings) {
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/writer/csv/UnivocityCsvWriter.java
// Path: src/main/java/au/com/anthonybruno/record/Record.java // public interface Record extends Iterable<Object> { // // Object get(int index); // // Object get(String fieldName); // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // }
import au.com.anthonybruno.record.Record; import au.com.anthonybruno.settings.CsvSettings; import com.univocity.parsers.csv.CsvWriter; import com.univocity.parsers.csv.CsvWriterSettings; import java.io.Writer; import java.util.ArrayList; import java.util.List;
package au.com.anthonybruno.writer.csv; public class UnivocityCsvWriter extends AbstractCsvWriter { private final CsvWriter csvWriter; public UnivocityCsvWriter(Writer writer, CsvSettings settings) { super(writer, settings); CsvWriterSettings csvWriterSettings = new CsvWriterSettings(); csvWriterSettings.getFormat().setDelimiter(settings.getDelimiter()); this.csvWriter = new CsvWriter(writer, csvWriterSettings); } @Override public void writeRow(List<String> row) { for (String value : row) { csvWriter.addValue(value); } csvWriter.writeValuesToRow(); } @Override public void close() { csvWriter.close(); } @Override
// Path: src/main/java/au/com/anthonybruno/record/Record.java // public interface Record extends Iterable<Object> { // // Object get(int index); // // Object get(String fieldName); // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // Path: src/main/java/au/com/anthonybruno/writer/csv/UnivocityCsvWriter.java import au.com.anthonybruno.record.Record; import au.com.anthonybruno.settings.CsvSettings; import com.univocity.parsers.csv.CsvWriter; import com.univocity.parsers.csv.CsvWriterSettings; import java.io.Writer; import java.util.ArrayList; import java.util.List; package au.com.anthonybruno.writer.csv; public class UnivocityCsvWriter extends AbstractCsvWriter { private final CsvWriter csvWriter; public UnivocityCsvWriter(Writer writer, CsvSettings settings) { super(writer, settings); CsvWriterSettings csvWriterSettings = new CsvWriterSettings(); csvWriterSettings.getFormat().setDelimiter(settings.getDelimiter()); this.csvWriter = new CsvWriter(writer, csvWriterSettings); } @Override public void writeRow(List<String> row) { for (String value : row) { csvWriter.addValue(value); } csvWriter.writeValuesToRow(); } @Override public void close() { csvWriter.close(); } @Override
public void writeRecord(Record record) {
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/generator/DateGeneratorTest.java
// Path: src/main/java/au/com/anthonybruno/generator/defaults/DateGenerator.java // public class DateGenerator extends RangedGenerator<Date> { // // private final LongGenerator longGenerator; // // public DateGenerator(){ // this(Date.from(Instant.EPOCH),Date.from(Instant.now())); // } // // public DateGenerator(Date min, Date max) { // super(min, max); // longGenerator = new LongGenerator(min.getTime(), max.getTime()); // } // // @Override // public Date generate() { // return Date.from(Instant.ofEpochMilli(longGenerator.generate())); // } // } // // Path: src/main/java/au/com/anthonybruno/generator/format/DateFormatter.java // public class DateFormatter implements Formatter<Date> { // // private final DateFormat dateFormat; // // public DateFormatter(DateFormat dateFormat) { // this.dateFormat = dateFormat; // } // // @Override // public String format(Date toFormat) { // return dateFormat.format(toFormat); // } // }
import au.com.anthonybruno.generator.defaults.DateGenerator; import au.com.anthonybruno.generator.format.DateFormatter; import org.junit.Test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Set; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.fail;
package au.com.anthonybruno.generator; public class DateGeneratorTest { @Test public void dateGeneration() throws Exception {
// Path: src/main/java/au/com/anthonybruno/generator/defaults/DateGenerator.java // public class DateGenerator extends RangedGenerator<Date> { // // private final LongGenerator longGenerator; // // public DateGenerator(){ // this(Date.from(Instant.EPOCH),Date.from(Instant.now())); // } // // public DateGenerator(Date min, Date max) { // super(min, max); // longGenerator = new LongGenerator(min.getTime(), max.getTime()); // } // // @Override // public Date generate() { // return Date.from(Instant.ofEpochMilli(longGenerator.generate())); // } // } // // Path: src/main/java/au/com/anthonybruno/generator/format/DateFormatter.java // public class DateFormatter implements Formatter<Date> { // // private final DateFormat dateFormat; // // public DateFormatter(DateFormat dateFormat) { // this.dateFormat = dateFormat; // } // // @Override // public String format(Date toFormat) { // return dateFormat.format(toFormat); // } // } // Path: src/test/java/au/com/anthonybruno/generator/DateGeneratorTest.java import au.com.anthonybruno.generator.defaults.DateGenerator; import au.com.anthonybruno.generator.format.DateFormatter; import org.junit.Test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Set; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.fail; package au.com.anthonybruno.generator; public class DateGeneratorTest { @Test public void dateGeneration() throws Exception {
DateGenerator generator = new DateGenerator();
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/generator/DateGeneratorTest.java
// Path: src/main/java/au/com/anthonybruno/generator/defaults/DateGenerator.java // public class DateGenerator extends RangedGenerator<Date> { // // private final LongGenerator longGenerator; // // public DateGenerator(){ // this(Date.from(Instant.EPOCH),Date.from(Instant.now())); // } // // public DateGenerator(Date min, Date max) { // super(min, max); // longGenerator = new LongGenerator(min.getTime(), max.getTime()); // } // // @Override // public Date generate() { // return Date.from(Instant.ofEpochMilli(longGenerator.generate())); // } // } // // Path: src/main/java/au/com/anthonybruno/generator/format/DateFormatter.java // public class DateFormatter implements Formatter<Date> { // // private final DateFormat dateFormat; // // public DateFormatter(DateFormat dateFormat) { // this.dateFormat = dateFormat; // } // // @Override // public String format(Date toFormat) { // return dateFormat.format(toFormat); // } // }
import au.com.anthonybruno.generator.defaults.DateGenerator; import au.com.anthonybruno.generator.format.DateFormatter; import org.junit.Test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Set; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.fail;
package au.com.anthonybruno.generator; public class DateGeneratorTest { @Test public void dateGeneration() throws Exception { DateGenerator generator = new DateGenerator(); int numValues = 100000; Set<Date> set = new HashSet<>(); for (int i = 0; i < numValues; i++) { Date value = generator.generate(); set.add(value); } assertTrue(set.size() + "", set.size() >= 90000); //ensure most values generated are random } @Test public void formattedDateGeneration() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy/MM/dd");
// Path: src/main/java/au/com/anthonybruno/generator/defaults/DateGenerator.java // public class DateGenerator extends RangedGenerator<Date> { // // private final LongGenerator longGenerator; // // public DateGenerator(){ // this(Date.from(Instant.EPOCH),Date.from(Instant.now())); // } // // public DateGenerator(Date min, Date max) { // super(min, max); // longGenerator = new LongGenerator(min.getTime(), max.getTime()); // } // // @Override // public Date generate() { // return Date.from(Instant.ofEpochMilli(longGenerator.generate())); // } // } // // Path: src/main/java/au/com/anthonybruno/generator/format/DateFormatter.java // public class DateFormatter implements Formatter<Date> { // // private final DateFormat dateFormat; // // public DateFormatter(DateFormat dateFormat) { // this.dateFormat = dateFormat; // } // // @Override // public String format(Date toFormat) { // return dateFormat.format(toFormat); // } // } // Path: src/test/java/au/com/anthonybruno/generator/DateGeneratorTest.java import au.com.anthonybruno.generator.defaults.DateGenerator; import au.com.anthonybruno.generator.format.DateFormatter; import org.junit.Test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Set; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.fail; package au.com.anthonybruno.generator; public class DateGeneratorTest { @Test public void dateGeneration() throws Exception { DateGenerator generator = new DateGenerator(); int numValues = 100000; Set<Date> set = new HashSet<>(); for (int i = 0; i < numValues; i++) { Date value = generator.generate(); set.add(value); } assertTrue(set.size() + "", set.size() >= 90000); //ensure most values generated are random } @Test public void formattedDateGeneration() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy/MM/dd");
DateFormatter dateFormatter = new DateFormatter(simpleDateFormat);
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/record/factory/FieldsRecordFactory.java
// Path: src/main/java/au/com/anthonybruno/definition/FieldData.java // public class FieldData { // // private final String name; // private final Generator generator; // // /** // * FieldData Constructor creates a FieldData object with the parameters name and generator // * // * @param name A String to give the generator a name // * @param generator a Generator object to choose a generator type // */ // public FieldData(String name, Generator generator) { // this.name = name; // this.generator = generator; // } // // /** // * this getter method returns the field name // * // * @return a String which is the specific name given to this field // */ // public String getName() { // return name; // } // // /** // * this getter method returns the classes' generator object // * // * @return the generator object // */ // public Generator getGenerator() { // return generator; // } // } // // Path: src/main/java/au/com/anthonybruno/record/DefaultRecordSupplier.java // public class DefaultRecordSupplier implements RecordSupplier { // // // private final List<String> fields; // private final Supplier<Record> recordSupplier; // // public DefaultRecordSupplier(List<String> fields, Supplier<Record> recordSupplier) { // this.fields = Collections.unmodifiableList(fields); // this.recordSupplier = recordSupplier; // // } // // @Override // public List<String> getFields() { // return fields; // } // // @Override // public Stream<Record> supplyRecords(int numToGenerate) { // return Stream.generate(recordSupplier).limit(numToGenerate); // } // // } // // Path: src/main/java/au/com/anthonybruno/record/Record.java // public interface Record extends Iterable<Object> { // // Object get(int index); // // Object get(String fieldName); // } // // Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/RowRecord.java // public class RowRecord implements Record { // // private final List<Object> rows; // // public RowRecord(List<Object> rows) { // this.rows = rows; // } // // @Override // public Object get(int index) { // return rows.get(index); // } // // @Override // public Object get(String fieldName) { // throw new NotImplementedException(); // } // // @Override // public Iterator<Object> iterator() { // return rows.iterator(); // } // }
import au.com.anthonybruno.definition.FieldData; import au.com.anthonybruno.record.DefaultRecordSupplier; import au.com.anthonybruno.record.Record; import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.RowRecord; import java.util.List; import java.util.stream.Collectors;
package au.com.anthonybruno.record.factory; public class FieldsRecordFactory implements RecordFactory { private final List<FieldData> fields; public FieldsRecordFactory(List<FieldData> fields) { this.fields = fields; } @Override
// Path: src/main/java/au/com/anthonybruno/definition/FieldData.java // public class FieldData { // // private final String name; // private final Generator generator; // // /** // * FieldData Constructor creates a FieldData object with the parameters name and generator // * // * @param name A String to give the generator a name // * @param generator a Generator object to choose a generator type // */ // public FieldData(String name, Generator generator) { // this.name = name; // this.generator = generator; // } // // /** // * this getter method returns the field name // * // * @return a String which is the specific name given to this field // */ // public String getName() { // return name; // } // // /** // * this getter method returns the classes' generator object // * // * @return the generator object // */ // public Generator getGenerator() { // return generator; // } // } // // Path: src/main/java/au/com/anthonybruno/record/DefaultRecordSupplier.java // public class DefaultRecordSupplier implements RecordSupplier { // // // private final List<String> fields; // private final Supplier<Record> recordSupplier; // // public DefaultRecordSupplier(List<String> fields, Supplier<Record> recordSupplier) { // this.fields = Collections.unmodifiableList(fields); // this.recordSupplier = recordSupplier; // // } // // @Override // public List<String> getFields() { // return fields; // } // // @Override // public Stream<Record> supplyRecords(int numToGenerate) { // return Stream.generate(recordSupplier).limit(numToGenerate); // } // // } // // Path: src/main/java/au/com/anthonybruno/record/Record.java // public interface Record extends Iterable<Object> { // // Object get(int index); // // Object get(String fieldName); // } // // Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/RowRecord.java // public class RowRecord implements Record { // // private final List<Object> rows; // // public RowRecord(List<Object> rows) { // this.rows = rows; // } // // @Override // public Object get(int index) { // return rows.get(index); // } // // @Override // public Object get(String fieldName) { // throw new NotImplementedException(); // } // // @Override // public Iterator<Object> iterator() { // return rows.iterator(); // } // } // Path: src/main/java/au/com/anthonybruno/record/factory/FieldsRecordFactory.java import au.com.anthonybruno.definition.FieldData; import au.com.anthonybruno.record.DefaultRecordSupplier; import au.com.anthonybruno.record.Record; import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.RowRecord; import java.util.List; import java.util.stream.Collectors; package au.com.anthonybruno.record.factory; public class FieldsRecordFactory implements RecordFactory { private final List<FieldData> fields; public FieldsRecordFactory(List<FieldData> fields) { this.fields = fields; } @Override
public RecordSupplier getRecordSupplier() {
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/record/factory/FieldsRecordFactory.java
// Path: src/main/java/au/com/anthonybruno/definition/FieldData.java // public class FieldData { // // private final String name; // private final Generator generator; // // /** // * FieldData Constructor creates a FieldData object with the parameters name and generator // * // * @param name A String to give the generator a name // * @param generator a Generator object to choose a generator type // */ // public FieldData(String name, Generator generator) { // this.name = name; // this.generator = generator; // } // // /** // * this getter method returns the field name // * // * @return a String which is the specific name given to this field // */ // public String getName() { // return name; // } // // /** // * this getter method returns the classes' generator object // * // * @return the generator object // */ // public Generator getGenerator() { // return generator; // } // } // // Path: src/main/java/au/com/anthonybruno/record/DefaultRecordSupplier.java // public class DefaultRecordSupplier implements RecordSupplier { // // // private final List<String> fields; // private final Supplier<Record> recordSupplier; // // public DefaultRecordSupplier(List<String> fields, Supplier<Record> recordSupplier) { // this.fields = Collections.unmodifiableList(fields); // this.recordSupplier = recordSupplier; // // } // // @Override // public List<String> getFields() { // return fields; // } // // @Override // public Stream<Record> supplyRecords(int numToGenerate) { // return Stream.generate(recordSupplier).limit(numToGenerate); // } // // } // // Path: src/main/java/au/com/anthonybruno/record/Record.java // public interface Record extends Iterable<Object> { // // Object get(int index); // // Object get(String fieldName); // } // // Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/RowRecord.java // public class RowRecord implements Record { // // private final List<Object> rows; // // public RowRecord(List<Object> rows) { // this.rows = rows; // } // // @Override // public Object get(int index) { // return rows.get(index); // } // // @Override // public Object get(String fieldName) { // throw new NotImplementedException(); // } // // @Override // public Iterator<Object> iterator() { // return rows.iterator(); // } // }
import au.com.anthonybruno.definition.FieldData; import au.com.anthonybruno.record.DefaultRecordSupplier; import au.com.anthonybruno.record.Record; import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.RowRecord; import java.util.List; import java.util.stream.Collectors;
package au.com.anthonybruno.record.factory; public class FieldsRecordFactory implements RecordFactory { private final List<FieldData> fields; public FieldsRecordFactory(List<FieldData> fields) { this.fields = fields; } @Override public RecordSupplier getRecordSupplier() { List<String> fieldNames = fields.stream() .map(FieldData::getName) .collect(Collectors.toList());
// Path: src/main/java/au/com/anthonybruno/definition/FieldData.java // public class FieldData { // // private final String name; // private final Generator generator; // // /** // * FieldData Constructor creates a FieldData object with the parameters name and generator // * // * @param name A String to give the generator a name // * @param generator a Generator object to choose a generator type // */ // public FieldData(String name, Generator generator) { // this.name = name; // this.generator = generator; // } // // /** // * this getter method returns the field name // * // * @return a String which is the specific name given to this field // */ // public String getName() { // return name; // } // // /** // * this getter method returns the classes' generator object // * // * @return the generator object // */ // public Generator getGenerator() { // return generator; // } // } // // Path: src/main/java/au/com/anthonybruno/record/DefaultRecordSupplier.java // public class DefaultRecordSupplier implements RecordSupplier { // // // private final List<String> fields; // private final Supplier<Record> recordSupplier; // // public DefaultRecordSupplier(List<String> fields, Supplier<Record> recordSupplier) { // this.fields = Collections.unmodifiableList(fields); // this.recordSupplier = recordSupplier; // // } // // @Override // public List<String> getFields() { // return fields; // } // // @Override // public Stream<Record> supplyRecords(int numToGenerate) { // return Stream.generate(recordSupplier).limit(numToGenerate); // } // // } // // Path: src/main/java/au/com/anthonybruno/record/Record.java // public interface Record extends Iterable<Object> { // // Object get(int index); // // Object get(String fieldName); // } // // Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/RowRecord.java // public class RowRecord implements Record { // // private final List<Object> rows; // // public RowRecord(List<Object> rows) { // this.rows = rows; // } // // @Override // public Object get(int index) { // return rows.get(index); // } // // @Override // public Object get(String fieldName) { // throw new NotImplementedException(); // } // // @Override // public Iterator<Object> iterator() { // return rows.iterator(); // } // } // Path: src/main/java/au/com/anthonybruno/record/factory/FieldsRecordFactory.java import au.com.anthonybruno.definition.FieldData; import au.com.anthonybruno.record.DefaultRecordSupplier; import au.com.anthonybruno.record.Record; import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.RowRecord; import java.util.List; import java.util.stream.Collectors; package au.com.anthonybruno.record.factory; public class FieldsRecordFactory implements RecordFactory { private final List<FieldData> fields; public FieldsRecordFactory(List<FieldData> fields) { this.fields = fields; } @Override public RecordSupplier getRecordSupplier() { List<String> fieldNames = fields.stream() .map(FieldData::getName) .collect(Collectors.toList());
return new DefaultRecordSupplier(fieldNames, () -> generateRecord());
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/record/factory/FieldsRecordFactory.java
// Path: src/main/java/au/com/anthonybruno/definition/FieldData.java // public class FieldData { // // private final String name; // private final Generator generator; // // /** // * FieldData Constructor creates a FieldData object with the parameters name and generator // * // * @param name A String to give the generator a name // * @param generator a Generator object to choose a generator type // */ // public FieldData(String name, Generator generator) { // this.name = name; // this.generator = generator; // } // // /** // * this getter method returns the field name // * // * @return a String which is the specific name given to this field // */ // public String getName() { // return name; // } // // /** // * this getter method returns the classes' generator object // * // * @return the generator object // */ // public Generator getGenerator() { // return generator; // } // } // // Path: src/main/java/au/com/anthonybruno/record/DefaultRecordSupplier.java // public class DefaultRecordSupplier implements RecordSupplier { // // // private final List<String> fields; // private final Supplier<Record> recordSupplier; // // public DefaultRecordSupplier(List<String> fields, Supplier<Record> recordSupplier) { // this.fields = Collections.unmodifiableList(fields); // this.recordSupplier = recordSupplier; // // } // // @Override // public List<String> getFields() { // return fields; // } // // @Override // public Stream<Record> supplyRecords(int numToGenerate) { // return Stream.generate(recordSupplier).limit(numToGenerate); // } // // } // // Path: src/main/java/au/com/anthonybruno/record/Record.java // public interface Record extends Iterable<Object> { // // Object get(int index); // // Object get(String fieldName); // } // // Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/RowRecord.java // public class RowRecord implements Record { // // private final List<Object> rows; // // public RowRecord(List<Object> rows) { // this.rows = rows; // } // // @Override // public Object get(int index) { // return rows.get(index); // } // // @Override // public Object get(String fieldName) { // throw new NotImplementedException(); // } // // @Override // public Iterator<Object> iterator() { // return rows.iterator(); // } // }
import au.com.anthonybruno.definition.FieldData; import au.com.anthonybruno.record.DefaultRecordSupplier; import au.com.anthonybruno.record.Record; import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.RowRecord; import java.util.List; import java.util.stream.Collectors;
package au.com.anthonybruno.record.factory; public class FieldsRecordFactory implements RecordFactory { private final List<FieldData> fields; public FieldsRecordFactory(List<FieldData> fields) { this.fields = fields; } @Override public RecordSupplier getRecordSupplier() { List<String> fieldNames = fields.stream() .map(FieldData::getName) .collect(Collectors.toList()); return new DefaultRecordSupplier(fieldNames, () -> generateRecord()); }
// Path: src/main/java/au/com/anthonybruno/definition/FieldData.java // public class FieldData { // // private final String name; // private final Generator generator; // // /** // * FieldData Constructor creates a FieldData object with the parameters name and generator // * // * @param name A String to give the generator a name // * @param generator a Generator object to choose a generator type // */ // public FieldData(String name, Generator generator) { // this.name = name; // this.generator = generator; // } // // /** // * this getter method returns the field name // * // * @return a String which is the specific name given to this field // */ // public String getName() { // return name; // } // // /** // * this getter method returns the classes' generator object // * // * @return the generator object // */ // public Generator getGenerator() { // return generator; // } // } // // Path: src/main/java/au/com/anthonybruno/record/DefaultRecordSupplier.java // public class DefaultRecordSupplier implements RecordSupplier { // // // private final List<String> fields; // private final Supplier<Record> recordSupplier; // // public DefaultRecordSupplier(List<String> fields, Supplier<Record> recordSupplier) { // this.fields = Collections.unmodifiableList(fields); // this.recordSupplier = recordSupplier; // // } // // @Override // public List<String> getFields() { // return fields; // } // // @Override // public Stream<Record> supplyRecords(int numToGenerate) { // return Stream.generate(recordSupplier).limit(numToGenerate); // } // // } // // Path: src/main/java/au/com/anthonybruno/record/Record.java // public interface Record extends Iterable<Object> { // // Object get(int index); // // Object get(String fieldName); // } // // Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/RowRecord.java // public class RowRecord implements Record { // // private final List<Object> rows; // // public RowRecord(List<Object> rows) { // this.rows = rows; // } // // @Override // public Object get(int index) { // return rows.get(index); // } // // @Override // public Object get(String fieldName) { // throw new NotImplementedException(); // } // // @Override // public Iterator<Object> iterator() { // return rows.iterator(); // } // } // Path: src/main/java/au/com/anthonybruno/record/factory/FieldsRecordFactory.java import au.com.anthonybruno.definition.FieldData; import au.com.anthonybruno.record.DefaultRecordSupplier; import au.com.anthonybruno.record.Record; import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.RowRecord; import java.util.List; import java.util.stream.Collectors; package au.com.anthonybruno.record.factory; public class FieldsRecordFactory implements RecordFactory { private final List<FieldData> fields; public FieldsRecordFactory(List<FieldData> fields) { this.fields = fields; } @Override public RecordSupplier getRecordSupplier() { List<String> fieldNames = fields.stream() .map(FieldData::getName) .collect(Collectors.toList()); return new DefaultRecordSupplier(fieldNames, () -> generateRecord()); }
private Record generateRecord() {
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/record/factory/FieldsRecordFactory.java
// Path: src/main/java/au/com/anthonybruno/definition/FieldData.java // public class FieldData { // // private final String name; // private final Generator generator; // // /** // * FieldData Constructor creates a FieldData object with the parameters name and generator // * // * @param name A String to give the generator a name // * @param generator a Generator object to choose a generator type // */ // public FieldData(String name, Generator generator) { // this.name = name; // this.generator = generator; // } // // /** // * this getter method returns the field name // * // * @return a String which is the specific name given to this field // */ // public String getName() { // return name; // } // // /** // * this getter method returns the classes' generator object // * // * @return the generator object // */ // public Generator getGenerator() { // return generator; // } // } // // Path: src/main/java/au/com/anthonybruno/record/DefaultRecordSupplier.java // public class DefaultRecordSupplier implements RecordSupplier { // // // private final List<String> fields; // private final Supplier<Record> recordSupplier; // // public DefaultRecordSupplier(List<String> fields, Supplier<Record> recordSupplier) { // this.fields = Collections.unmodifiableList(fields); // this.recordSupplier = recordSupplier; // // } // // @Override // public List<String> getFields() { // return fields; // } // // @Override // public Stream<Record> supplyRecords(int numToGenerate) { // return Stream.generate(recordSupplier).limit(numToGenerate); // } // // } // // Path: src/main/java/au/com/anthonybruno/record/Record.java // public interface Record extends Iterable<Object> { // // Object get(int index); // // Object get(String fieldName); // } // // Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/RowRecord.java // public class RowRecord implements Record { // // private final List<Object> rows; // // public RowRecord(List<Object> rows) { // this.rows = rows; // } // // @Override // public Object get(int index) { // return rows.get(index); // } // // @Override // public Object get(String fieldName) { // throw new NotImplementedException(); // } // // @Override // public Iterator<Object> iterator() { // return rows.iterator(); // } // }
import au.com.anthonybruno.definition.FieldData; import au.com.anthonybruno.record.DefaultRecordSupplier; import au.com.anthonybruno.record.Record; import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.RowRecord; import java.util.List; import java.util.stream.Collectors;
package au.com.anthonybruno.record.factory; public class FieldsRecordFactory implements RecordFactory { private final List<FieldData> fields; public FieldsRecordFactory(List<FieldData> fields) { this.fields = fields; } @Override public RecordSupplier getRecordSupplier() { List<String> fieldNames = fields.stream() .map(FieldData::getName) .collect(Collectors.toList()); return new DefaultRecordSupplier(fieldNames, () -> generateRecord()); } private Record generateRecord() { List<Object> data = fields.stream() .map(fieldData -> fieldData.getGenerator().generate()) .collect(Collectors.toList());
// Path: src/main/java/au/com/anthonybruno/definition/FieldData.java // public class FieldData { // // private final String name; // private final Generator generator; // // /** // * FieldData Constructor creates a FieldData object with the parameters name and generator // * // * @param name A String to give the generator a name // * @param generator a Generator object to choose a generator type // */ // public FieldData(String name, Generator generator) { // this.name = name; // this.generator = generator; // } // // /** // * this getter method returns the field name // * // * @return a String which is the specific name given to this field // */ // public String getName() { // return name; // } // // /** // * this getter method returns the classes' generator object // * // * @return the generator object // */ // public Generator getGenerator() { // return generator; // } // } // // Path: src/main/java/au/com/anthonybruno/record/DefaultRecordSupplier.java // public class DefaultRecordSupplier implements RecordSupplier { // // // private final List<String> fields; // private final Supplier<Record> recordSupplier; // // public DefaultRecordSupplier(List<String> fields, Supplier<Record> recordSupplier) { // this.fields = Collections.unmodifiableList(fields); // this.recordSupplier = recordSupplier; // // } // // @Override // public List<String> getFields() { // return fields; // } // // @Override // public Stream<Record> supplyRecords(int numToGenerate) { // return Stream.generate(recordSupplier).limit(numToGenerate); // } // // } // // Path: src/main/java/au/com/anthonybruno/record/Record.java // public interface Record extends Iterable<Object> { // // Object get(int index); // // Object get(String fieldName); // } // // Path: src/main/java/au/com/anthonybruno/record/RecordSupplier.java // public interface RecordSupplier { // // List<String> getFields(); // // Stream<Record> supplyRecords(int numToGenerate); // // } // // Path: src/main/java/au/com/anthonybruno/record/RowRecord.java // public class RowRecord implements Record { // // private final List<Object> rows; // // public RowRecord(List<Object> rows) { // this.rows = rows; // } // // @Override // public Object get(int index) { // return rows.get(index); // } // // @Override // public Object get(String fieldName) { // throw new NotImplementedException(); // } // // @Override // public Iterator<Object> iterator() { // return rows.iterator(); // } // } // Path: src/main/java/au/com/anthonybruno/record/factory/FieldsRecordFactory.java import au.com.anthonybruno.definition.FieldData; import au.com.anthonybruno.record.DefaultRecordSupplier; import au.com.anthonybruno.record.Record; import au.com.anthonybruno.record.RecordSupplier; import au.com.anthonybruno.record.RowRecord; import java.util.List; import java.util.stream.Collectors; package au.com.anthonybruno.record.factory; public class FieldsRecordFactory implements RecordFactory { private final List<FieldData> fields; public FieldsRecordFactory(List<FieldData> fields) { this.fields = fields; } @Override public RecordSupplier getRecordSupplier() { List<String> fieldNames = fields.stream() .map(FieldData::getName) .collect(Collectors.toList()); return new DefaultRecordSupplier(fieldNames, () -> generateRecord()); } private Record generateRecord() { List<Object> data = fields.stream() .map(fieldData -> fieldData.getGenerator().generate()) .collect(Collectors.toList());
return new RowRecord(data);
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/AddFieldsTest.java
// Path: src/main/java/au/com/anthonybruno/definition/RecordDefinition.java // public interface RecordDefinition { // // // /** // * Specifies how many records will be generated. // * // * @param num the int defining how many rows will be generated // * @return A {@link FileTypeDefinition} which allows the specification of the type of file to create // */ // FileTypeDefinition generate(int num); // } // // Path: src/main/java/au/com/anthonybruno/definition/StartDefinition.java // public interface StartDefinition { //FIXME: better name // // /** // * Specifies a class that will be used to generate fields. // * // * @param c the class which the random data is to be generated for // * // * @return a RecordDefinition that allows the specification of the number of records to generate // */ // RecordDefinition use(Class<?> c); // // /** // * Adds a field to be generated. // * // * @param name String that names the field // * @param generator Generator object that creates random values for the field // * // * @return A FieldDefinition that allows more fields to be added // */ // FieldDefinition addField(String name, Generator generator); // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/StringGenerator.java // public class StringGenerator implements Generator<String> { // // private final CharGenerator charGenerator = new CharGenerator(); // // @Override // public String generate() { // StringBuilder stringBuilder = new StringBuilder(); // ThreadLocalRandom random = ThreadLocalRandom.current(); // int length = random.nextInt(2, 10); // for (int i = 0; i < length; i++) { // stringBuilder.append(charGenerator.generate()); // } // return stringBuilder.toString(); // } // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // }
import au.com.anthonybruno.definition.RecordDefinition; import au.com.anthonybruno.definition.StartDefinition; import au.com.anthonybruno.generator.defaults.IntGenerator; import au.com.anthonybruno.generator.defaults.StringGenerator; import au.com.anthonybruno.settings.CsvSettings; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse;
package au.com.anthonybruno; public class AddFieldsTest { private final int rowsToGenerate = 5; @Test public void generateSingleFieldNotEmpty() { String result = generateSingleFieldCsv(); assertFalse(result.isEmpty()); } @Test public void generateSingleFieldsCorrectAmountOfRows() { String result = generateSingleFieldCsv(); assertEquals(rowsToGenerate, result.split("\n").length); } @Test public void generateLotsOfFields() {
// Path: src/main/java/au/com/anthonybruno/definition/RecordDefinition.java // public interface RecordDefinition { // // // /** // * Specifies how many records will be generated. // * // * @param num the int defining how many rows will be generated // * @return A {@link FileTypeDefinition} which allows the specification of the type of file to create // */ // FileTypeDefinition generate(int num); // } // // Path: src/main/java/au/com/anthonybruno/definition/StartDefinition.java // public interface StartDefinition { //FIXME: better name // // /** // * Specifies a class that will be used to generate fields. // * // * @param c the class which the random data is to be generated for // * // * @return a RecordDefinition that allows the specification of the number of records to generate // */ // RecordDefinition use(Class<?> c); // // /** // * Adds a field to be generated. // * // * @param name String that names the field // * @param generator Generator object that creates random values for the field // * // * @return A FieldDefinition that allows more fields to be added // */ // FieldDefinition addField(String name, Generator generator); // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/StringGenerator.java // public class StringGenerator implements Generator<String> { // // private final CharGenerator charGenerator = new CharGenerator(); // // @Override // public String generate() { // StringBuilder stringBuilder = new StringBuilder(); // ThreadLocalRandom random = ThreadLocalRandom.current(); // int length = random.nextInt(2, 10); // for (int i = 0; i < length; i++) { // stringBuilder.append(charGenerator.generate()); // } // return stringBuilder.toString(); // } // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // Path: src/test/java/au/com/anthonybruno/AddFieldsTest.java import au.com.anthonybruno.definition.RecordDefinition; import au.com.anthonybruno.definition.StartDefinition; import au.com.anthonybruno.generator.defaults.IntGenerator; import au.com.anthonybruno.generator.defaults.StringGenerator; import au.com.anthonybruno.settings.CsvSettings; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; package au.com.anthonybruno; public class AddFieldsTest { private final int rowsToGenerate = 5; @Test public void generateSingleFieldNotEmpty() { String result = generateSingleFieldCsv(); assertFalse(result.isEmpty()); } @Test public void generateSingleFieldsCorrectAmountOfRows() { String result = generateSingleFieldCsv(); assertEquals(rowsToGenerate, result.split("\n").length); } @Test public void generateLotsOfFields() {
StartDefinition fieldDefinition = Gen.start();
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/AddFieldsTest.java
// Path: src/main/java/au/com/anthonybruno/definition/RecordDefinition.java // public interface RecordDefinition { // // // /** // * Specifies how many records will be generated. // * // * @param num the int defining how many rows will be generated // * @return A {@link FileTypeDefinition} which allows the specification of the type of file to create // */ // FileTypeDefinition generate(int num); // } // // Path: src/main/java/au/com/anthonybruno/definition/StartDefinition.java // public interface StartDefinition { //FIXME: better name // // /** // * Specifies a class that will be used to generate fields. // * // * @param c the class which the random data is to be generated for // * // * @return a RecordDefinition that allows the specification of the number of records to generate // */ // RecordDefinition use(Class<?> c); // // /** // * Adds a field to be generated. // * // * @param name String that names the field // * @param generator Generator object that creates random values for the field // * // * @return A FieldDefinition that allows more fields to be added // */ // FieldDefinition addField(String name, Generator generator); // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/StringGenerator.java // public class StringGenerator implements Generator<String> { // // private final CharGenerator charGenerator = new CharGenerator(); // // @Override // public String generate() { // StringBuilder stringBuilder = new StringBuilder(); // ThreadLocalRandom random = ThreadLocalRandom.current(); // int length = random.nextInt(2, 10); // for (int i = 0; i < length; i++) { // stringBuilder.append(charGenerator.generate()); // } // return stringBuilder.toString(); // } // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // }
import au.com.anthonybruno.definition.RecordDefinition; import au.com.anthonybruno.definition.StartDefinition; import au.com.anthonybruno.generator.defaults.IntGenerator; import au.com.anthonybruno.generator.defaults.StringGenerator; import au.com.anthonybruno.settings.CsvSettings; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse;
package au.com.anthonybruno; public class AddFieldsTest { private final int rowsToGenerate = 5; @Test public void generateSingleFieldNotEmpty() { String result = generateSingleFieldCsv(); assertFalse(result.isEmpty()); } @Test public void generateSingleFieldsCorrectAmountOfRows() { String result = generateSingleFieldCsv(); assertEquals(rowsToGenerate, result.split("\n").length); } @Test public void generateLotsOfFields() { StartDefinition fieldDefinition = Gen.start();
// Path: src/main/java/au/com/anthonybruno/definition/RecordDefinition.java // public interface RecordDefinition { // // // /** // * Specifies how many records will be generated. // * // * @param num the int defining how many rows will be generated // * @return A {@link FileTypeDefinition} which allows the specification of the type of file to create // */ // FileTypeDefinition generate(int num); // } // // Path: src/main/java/au/com/anthonybruno/definition/StartDefinition.java // public interface StartDefinition { //FIXME: better name // // /** // * Specifies a class that will be used to generate fields. // * // * @param c the class which the random data is to be generated for // * // * @return a RecordDefinition that allows the specification of the number of records to generate // */ // RecordDefinition use(Class<?> c); // // /** // * Adds a field to be generated. // * // * @param name String that names the field // * @param generator Generator object that creates random values for the field // * // * @return A FieldDefinition that allows more fields to be added // */ // FieldDefinition addField(String name, Generator generator); // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/StringGenerator.java // public class StringGenerator implements Generator<String> { // // private final CharGenerator charGenerator = new CharGenerator(); // // @Override // public String generate() { // StringBuilder stringBuilder = new StringBuilder(); // ThreadLocalRandom random = ThreadLocalRandom.current(); // int length = random.nextInt(2, 10); // for (int i = 0; i < length; i++) { // stringBuilder.append(charGenerator.generate()); // } // return stringBuilder.toString(); // } // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // Path: src/test/java/au/com/anthonybruno/AddFieldsTest.java import au.com.anthonybruno.definition.RecordDefinition; import au.com.anthonybruno.definition.StartDefinition; import au.com.anthonybruno.generator.defaults.IntGenerator; import au.com.anthonybruno.generator.defaults.StringGenerator; import au.com.anthonybruno.settings.CsvSettings; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; package au.com.anthonybruno; public class AddFieldsTest { private final int rowsToGenerate = 5; @Test public void generateSingleFieldNotEmpty() { String result = generateSingleFieldCsv(); assertFalse(result.isEmpty()); } @Test public void generateSingleFieldsCorrectAmountOfRows() { String result = generateSingleFieldCsv(); assertEquals(rowsToGenerate, result.split("\n").length); } @Test public void generateLotsOfFields() { StartDefinition fieldDefinition = Gen.start();
RecordDefinition recordDefinition = null;
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/AddFieldsTest.java
// Path: src/main/java/au/com/anthonybruno/definition/RecordDefinition.java // public interface RecordDefinition { // // // /** // * Specifies how many records will be generated. // * // * @param num the int defining how many rows will be generated // * @return A {@link FileTypeDefinition} which allows the specification of the type of file to create // */ // FileTypeDefinition generate(int num); // } // // Path: src/main/java/au/com/anthonybruno/definition/StartDefinition.java // public interface StartDefinition { //FIXME: better name // // /** // * Specifies a class that will be used to generate fields. // * // * @param c the class which the random data is to be generated for // * // * @return a RecordDefinition that allows the specification of the number of records to generate // */ // RecordDefinition use(Class<?> c); // // /** // * Adds a field to be generated. // * // * @param name String that names the field // * @param generator Generator object that creates random values for the field // * // * @return A FieldDefinition that allows more fields to be added // */ // FieldDefinition addField(String name, Generator generator); // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/StringGenerator.java // public class StringGenerator implements Generator<String> { // // private final CharGenerator charGenerator = new CharGenerator(); // // @Override // public String generate() { // StringBuilder stringBuilder = new StringBuilder(); // ThreadLocalRandom random = ThreadLocalRandom.current(); // int length = random.nextInt(2, 10); // for (int i = 0; i < length; i++) { // stringBuilder.append(charGenerator.generate()); // } // return stringBuilder.toString(); // } // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // }
import au.com.anthonybruno.definition.RecordDefinition; import au.com.anthonybruno.definition.StartDefinition; import au.com.anthonybruno.generator.defaults.IntGenerator; import au.com.anthonybruno.generator.defaults.StringGenerator; import au.com.anthonybruno.settings.CsvSettings; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse;
package au.com.anthonybruno; public class AddFieldsTest { private final int rowsToGenerate = 5; @Test public void generateSingleFieldNotEmpty() { String result = generateSingleFieldCsv(); assertFalse(result.isEmpty()); } @Test public void generateSingleFieldsCorrectAmountOfRows() { String result = generateSingleFieldCsv(); assertEquals(rowsToGenerate, result.split("\n").length); } @Test public void generateLotsOfFields() { StartDefinition fieldDefinition = Gen.start(); RecordDefinition recordDefinition = null; for (int i = 0; i < 100; i++) {
// Path: src/main/java/au/com/anthonybruno/definition/RecordDefinition.java // public interface RecordDefinition { // // // /** // * Specifies how many records will be generated. // * // * @param num the int defining how many rows will be generated // * @return A {@link FileTypeDefinition} which allows the specification of the type of file to create // */ // FileTypeDefinition generate(int num); // } // // Path: src/main/java/au/com/anthonybruno/definition/StartDefinition.java // public interface StartDefinition { //FIXME: better name // // /** // * Specifies a class that will be used to generate fields. // * // * @param c the class which the random data is to be generated for // * // * @return a RecordDefinition that allows the specification of the number of records to generate // */ // RecordDefinition use(Class<?> c); // // /** // * Adds a field to be generated. // * // * @param name String that names the field // * @param generator Generator object that creates random values for the field // * // * @return A FieldDefinition that allows more fields to be added // */ // FieldDefinition addField(String name, Generator generator); // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/StringGenerator.java // public class StringGenerator implements Generator<String> { // // private final CharGenerator charGenerator = new CharGenerator(); // // @Override // public String generate() { // StringBuilder stringBuilder = new StringBuilder(); // ThreadLocalRandom random = ThreadLocalRandom.current(); // int length = random.nextInt(2, 10); // for (int i = 0; i < length; i++) { // stringBuilder.append(charGenerator.generate()); // } // return stringBuilder.toString(); // } // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // Path: src/test/java/au/com/anthonybruno/AddFieldsTest.java import au.com.anthonybruno.definition.RecordDefinition; import au.com.anthonybruno.definition.StartDefinition; import au.com.anthonybruno.generator.defaults.IntGenerator; import au.com.anthonybruno.generator.defaults.StringGenerator; import au.com.anthonybruno.settings.CsvSettings; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; package au.com.anthonybruno; public class AddFieldsTest { private final int rowsToGenerate = 5; @Test public void generateSingleFieldNotEmpty() { String result = generateSingleFieldCsv(); assertFalse(result.isEmpty()); } @Test public void generateSingleFieldsCorrectAmountOfRows() { String result = generateSingleFieldCsv(); assertEquals(rowsToGenerate, result.split("\n").length); } @Test public void generateLotsOfFields() { StartDefinition fieldDefinition = Gen.start(); RecordDefinition recordDefinition = null; for (int i = 0; i < 100; i++) {
recordDefinition = fieldDefinition.addField("Field " + i, new StringGenerator());
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/AddFieldsTest.java
// Path: src/main/java/au/com/anthonybruno/definition/RecordDefinition.java // public interface RecordDefinition { // // // /** // * Specifies how many records will be generated. // * // * @param num the int defining how many rows will be generated // * @return A {@link FileTypeDefinition} which allows the specification of the type of file to create // */ // FileTypeDefinition generate(int num); // } // // Path: src/main/java/au/com/anthonybruno/definition/StartDefinition.java // public interface StartDefinition { //FIXME: better name // // /** // * Specifies a class that will be used to generate fields. // * // * @param c the class which the random data is to be generated for // * // * @return a RecordDefinition that allows the specification of the number of records to generate // */ // RecordDefinition use(Class<?> c); // // /** // * Adds a field to be generated. // * // * @param name String that names the field // * @param generator Generator object that creates random values for the field // * // * @return A FieldDefinition that allows more fields to be added // */ // FieldDefinition addField(String name, Generator generator); // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/StringGenerator.java // public class StringGenerator implements Generator<String> { // // private final CharGenerator charGenerator = new CharGenerator(); // // @Override // public String generate() { // StringBuilder stringBuilder = new StringBuilder(); // ThreadLocalRandom random = ThreadLocalRandom.current(); // int length = random.nextInt(2, 10); // for (int i = 0; i < length; i++) { // stringBuilder.append(charGenerator.generate()); // } // return stringBuilder.toString(); // } // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // }
import au.com.anthonybruno.definition.RecordDefinition; import au.com.anthonybruno.definition.StartDefinition; import au.com.anthonybruno.generator.defaults.IntGenerator; import au.com.anthonybruno.generator.defaults.StringGenerator; import au.com.anthonybruno.settings.CsvSettings; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse;
package au.com.anthonybruno; public class AddFieldsTest { private final int rowsToGenerate = 5; @Test public void generateSingleFieldNotEmpty() { String result = generateSingleFieldCsv(); assertFalse(result.isEmpty()); } @Test public void generateSingleFieldsCorrectAmountOfRows() { String result = generateSingleFieldCsv(); assertEquals(rowsToGenerate, result.split("\n").length); } @Test public void generateLotsOfFields() { StartDefinition fieldDefinition = Gen.start(); RecordDefinition recordDefinition = null; for (int i = 0; i < 100; i++) { recordDefinition = fieldDefinition.addField("Field " + i, new StringGenerator()); } String result = recordDefinition.generate(1000).asCsv().toStringForm(); String firstLine = result.substring(0, result.indexOf("\n")); assertEquals(100, firstLine.split(",").length); } @Test(expected = IllegalArgumentException.class) public void addNullGenerator() { Gen.start().addField("bad", null).generate(5).asCsv().toStringForm(); } @Test(expected = IllegalStateException.class) public void tryToGenerateNegativeRows() {
// Path: src/main/java/au/com/anthonybruno/definition/RecordDefinition.java // public interface RecordDefinition { // // // /** // * Specifies how many records will be generated. // * // * @param num the int defining how many rows will be generated // * @return A {@link FileTypeDefinition} which allows the specification of the type of file to create // */ // FileTypeDefinition generate(int num); // } // // Path: src/main/java/au/com/anthonybruno/definition/StartDefinition.java // public interface StartDefinition { //FIXME: better name // // /** // * Specifies a class that will be used to generate fields. // * // * @param c the class which the random data is to be generated for // * // * @return a RecordDefinition that allows the specification of the number of records to generate // */ // RecordDefinition use(Class<?> c); // // /** // * Adds a field to be generated. // * // * @param name String that names the field // * @param generator Generator object that creates random values for the field // * // * @return A FieldDefinition that allows more fields to be added // */ // FieldDefinition addField(String name, Generator generator); // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/StringGenerator.java // public class StringGenerator implements Generator<String> { // // private final CharGenerator charGenerator = new CharGenerator(); // // @Override // public String generate() { // StringBuilder stringBuilder = new StringBuilder(); // ThreadLocalRandom random = ThreadLocalRandom.current(); // int length = random.nextInt(2, 10); // for (int i = 0; i < length; i++) { // stringBuilder.append(charGenerator.generate()); // } // return stringBuilder.toString(); // } // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // Path: src/test/java/au/com/anthonybruno/AddFieldsTest.java import au.com.anthonybruno.definition.RecordDefinition; import au.com.anthonybruno.definition.StartDefinition; import au.com.anthonybruno.generator.defaults.IntGenerator; import au.com.anthonybruno.generator.defaults.StringGenerator; import au.com.anthonybruno.settings.CsvSettings; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; package au.com.anthonybruno; public class AddFieldsTest { private final int rowsToGenerate = 5; @Test public void generateSingleFieldNotEmpty() { String result = generateSingleFieldCsv(); assertFalse(result.isEmpty()); } @Test public void generateSingleFieldsCorrectAmountOfRows() { String result = generateSingleFieldCsv(); assertEquals(rowsToGenerate, result.split("\n").length); } @Test public void generateLotsOfFields() { StartDefinition fieldDefinition = Gen.start(); RecordDefinition recordDefinition = null; for (int i = 0; i < 100; i++) { recordDefinition = fieldDefinition.addField("Field " + i, new StringGenerator()); } String result = recordDefinition.generate(1000).asCsv().toStringForm(); String firstLine = result.substring(0, result.indexOf("\n")); assertEquals(100, firstLine.split(",").length); } @Test(expected = IllegalArgumentException.class) public void addNullGenerator() { Gen.start().addField("bad", null).generate(5).asCsv().toStringForm(); } @Test(expected = IllegalStateException.class) public void tryToGenerateNegativeRows() {
Gen.start().addField("bad", new IntGenerator()).generate(-1).asCsv().toStringForm();
AussieGuy0/SDgen
src/test/java/au/com/anthonybruno/AddFieldsTest.java
// Path: src/main/java/au/com/anthonybruno/definition/RecordDefinition.java // public interface RecordDefinition { // // // /** // * Specifies how many records will be generated. // * // * @param num the int defining how many rows will be generated // * @return A {@link FileTypeDefinition} which allows the specification of the type of file to create // */ // FileTypeDefinition generate(int num); // } // // Path: src/main/java/au/com/anthonybruno/definition/StartDefinition.java // public interface StartDefinition { //FIXME: better name // // /** // * Specifies a class that will be used to generate fields. // * // * @param c the class which the random data is to be generated for // * // * @return a RecordDefinition that allows the specification of the number of records to generate // */ // RecordDefinition use(Class<?> c); // // /** // * Adds a field to be generated. // * // * @param name String that names the field // * @param generator Generator object that creates random values for the field // * // * @return A FieldDefinition that allows more fields to be added // */ // FieldDefinition addField(String name, Generator generator); // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/StringGenerator.java // public class StringGenerator implements Generator<String> { // // private final CharGenerator charGenerator = new CharGenerator(); // // @Override // public String generate() { // StringBuilder stringBuilder = new StringBuilder(); // ThreadLocalRandom random = ThreadLocalRandom.current(); // int length = random.nextInt(2, 10); // for (int i = 0; i < length; i++) { // stringBuilder.append(charGenerator.generate()); // } // return stringBuilder.toString(); // } // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // }
import au.com.anthonybruno.definition.RecordDefinition; import au.com.anthonybruno.definition.StartDefinition; import au.com.anthonybruno.generator.defaults.IntGenerator; import au.com.anthonybruno.generator.defaults.StringGenerator; import au.com.anthonybruno.settings.CsvSettings; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse;
assertEquals(rowsToGenerate, result.split("\n").length); } @Test public void generateLotsOfFields() { StartDefinition fieldDefinition = Gen.start(); RecordDefinition recordDefinition = null; for (int i = 0; i < 100; i++) { recordDefinition = fieldDefinition.addField("Field " + i, new StringGenerator()); } String result = recordDefinition.generate(1000).asCsv().toStringForm(); String firstLine = result.substring(0, result.indexOf("\n")); assertEquals(100, firstLine.split(",").length); } @Test(expected = IllegalArgumentException.class) public void addNullGenerator() { Gen.start().addField("bad", null).generate(5).asCsv().toStringForm(); } @Test(expected = IllegalStateException.class) public void tryToGenerateNegativeRows() { Gen.start().addField("bad", new IntGenerator()).generate(-1).asCsv().toStringForm(); } public String generateSingleFieldCsv() { return Gen.start() .addField("Name", new StringGenerator()) .generate(rowsToGenerate)
// Path: src/main/java/au/com/anthonybruno/definition/RecordDefinition.java // public interface RecordDefinition { // // // /** // * Specifies how many records will be generated. // * // * @param num the int defining how many rows will be generated // * @return A {@link FileTypeDefinition} which allows the specification of the type of file to create // */ // FileTypeDefinition generate(int num); // } // // Path: src/main/java/au/com/anthonybruno/definition/StartDefinition.java // public interface StartDefinition { //FIXME: better name // // /** // * Specifies a class that will be used to generate fields. // * // * @param c the class which the random data is to be generated for // * // * @return a RecordDefinition that allows the specification of the number of records to generate // */ // RecordDefinition use(Class<?> c); // // /** // * Adds a field to be generated. // * // * @param name String that names the field // * @param generator Generator object that creates random values for the field // * // * @return A FieldDefinition that allows more fields to be added // */ // FieldDefinition addField(String name, Generator generator); // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/IntGenerator.java // public class IntGenerator extends RangedGenerator<Integer> { // // public IntGenerator() { // this(Integer.MIN_VALUE, Integer.MAX_VALUE); // } // // public IntGenerator(int min, int max) { // super(min, max); // } // // @Override // public Integer generate() { // return ThreadLocalRandom.current().nextInt(min, max); // } // } // // Path: src/main/java/au/com/anthonybruno/generator/defaults/StringGenerator.java // public class StringGenerator implements Generator<String> { // // private final CharGenerator charGenerator = new CharGenerator(); // // @Override // public String generate() { // StringBuilder stringBuilder = new StringBuilder(); // ThreadLocalRandom random = ThreadLocalRandom.current(); // int length = random.nextInt(2, 10); // for (int i = 0; i < length; i++) { // stringBuilder.append(charGenerator.generate()); // } // return stringBuilder.toString(); // } // } // // Path: src/main/java/au/com/anthonybruno/settings/CsvSettings.java // public class CsvSettings extends FlatFileSettings { // // public static final char DEFAULT_DELIMITER = ','; // // private final char delimiter; // // public CsvSettings(boolean includeHeaders) { // this(includeHeaders, DEFAULT_DELIMITER); // } // // public CsvSettings(boolean includeHeaders, char delimiter) { // super(includeHeaders); // this.delimiter = delimiter; // } // // public char getDelimiter() { // return delimiter; // } // // public static class Builder { // private char delimiter = DEFAULT_DELIMITER; // private boolean includeHeaders = true; // // public Builder setDelimiter(char delimiter) { // this.delimiter = delimiter; // return this; // } // // public Builder setIncludeHeaders(boolean includeHeaders) { // this.includeHeaders = includeHeaders; // return this; // } // // public CsvSettings build() { // return new CsvSettings(includeHeaders, delimiter); // } // } // // } // Path: src/test/java/au/com/anthonybruno/AddFieldsTest.java import au.com.anthonybruno.definition.RecordDefinition; import au.com.anthonybruno.definition.StartDefinition; import au.com.anthonybruno.generator.defaults.IntGenerator; import au.com.anthonybruno.generator.defaults.StringGenerator; import au.com.anthonybruno.settings.CsvSettings; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; assertEquals(rowsToGenerate, result.split("\n").length); } @Test public void generateLotsOfFields() { StartDefinition fieldDefinition = Gen.start(); RecordDefinition recordDefinition = null; for (int i = 0; i < 100; i++) { recordDefinition = fieldDefinition.addField("Field " + i, new StringGenerator()); } String result = recordDefinition.generate(1000).asCsv().toStringForm(); String firstLine = result.substring(0, result.indexOf("\n")); assertEquals(100, firstLine.split(",").length); } @Test(expected = IllegalArgumentException.class) public void addNullGenerator() { Gen.start().addField("bad", null).generate(5).asCsv().toStringForm(); } @Test(expected = IllegalStateException.class) public void tryToGenerateNegativeRows() { Gen.start().addField("bad", new IntGenerator()).generate(-1).asCsv().toStringForm(); } public String generateSingleFieldCsv() { return Gen.start() .addField("Name", new StringGenerator()) .generate(rowsToGenerate)
.asCsv(new CsvSettings(false))
AussieGuy0/SDgen
src/main/java/au/com/anthonybruno/annotation/Generation.java
// Path: src/main/java/au/com/anthonybruno/generator/Generator.java // @FunctionalInterface // public interface Generator<T> { // // T generate(); // }
import au.com.anthonybruno.generator.Generator; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
package au.com.anthonybruno.annotation; /** * A field Annotation that provides configuration options on how a field is used for data generation. */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Generation { public static final String DEFAULT_FIELD = "${default}"; /** * The Generator that will be used to randomly create values for this field. * * @return The random value generator for this field */
// Path: src/main/java/au/com/anthonybruno/generator/Generator.java // @FunctionalInterface // public interface Generator<T> { // // T generate(); // } // Path: src/main/java/au/com/anthonybruno/annotation/Generation.java import au.com.anthonybruno.generator.Generator; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; package au.com.anthonybruno.annotation; /** * A field Annotation that provides configuration options on how a field is used for data generation. */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Generation { public static final String DEFAULT_FIELD = "${default}"; /** * The Generator that will be used to randomly create values for this field. * * @return The random value generator for this field */
Class<? extends Generator> value();
fjorum/fjorum
src/main/java/org/fjorum/DbInitializer.java
// Path: src/main/java/org/fjorum/model/entity/Role.java // @Entity // @Table(name = "roles") // public class Role { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id", nullable = false) // private Long id; // @Column(name = "name", nullable = false) // private String name; // @Column(name = "description") // private String descriptionKey; // @Column(name = "predefined") // boolean predefined; // // @ManyToMany(cascade = CascadeType.MERGE) // @JoinTable(name = "included_roles", // joinColumns = @JoinColumn(name = "role_id"), // inverseJoinColumns = @JoinColumn(name = "included_role_id")) // private Set<Role> includesRoles = new HashSet<>(); // // Role() { // } // // public Role(String name, String descriptionKey, boolean predefined) { // this.name = name; // this.descriptionKey = descriptionKey; // this.predefined = predefined; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescriptionKey() { // return descriptionKey; // } // // public void setDescriptionKey(String descriptionKey) { // this.descriptionKey = descriptionKey; // } // // public boolean isPredefined() { // return predefined; // } // // public void setPredefined(boolean predefined) { // this.predefined = predefined; // } // // public Set<Role> getIncludedRoles() { // return includesRoles; // } // // public void setIncludedRoles(Set<Role> includedRoles) { // this.includesRoles = includedRoles; // } // // public Set<Role> getAllRoles() { // return Stream.concat(Stream.of(this), // includesRoles.stream().flatMap(role -> role.getAllRoles().stream())) // .collect(Collectors.toSet()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || !(o instanceof Role)) return false; // // Role role = (Role) o; // // return id != null && id.equals(role.id); // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // @Override // public String toString() { // return name; // } // } // // Path: src/main/java/org/fjorum/model/service/RoleService.java // public interface RoleService { // List<Role> getAllRoles(); // // Role addRole(Role role); // // Optional<Role> findRole(String name); // }
import org.fjorum.controller.form.UserCreateForm; import org.fjorum.model.entity.Category; import org.fjorum.model.entity.Role; import org.fjorum.model.entity.User; import org.fjorum.model.service.CategoryService; import org.fjorum.model.service.RoleService; import org.fjorum.model.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream;
package org.fjorum; @Component @Lazy(false) @Scope("singleton") @Profile("development") public class DbInitializer { private enum ROLE { ACCESS_MODERATION_PAGE, ACCESS_ADMINISTRATION_PAGE, ADMINISTRATE_USERS, ROLE_USER(), ROLE_MODERATOR(ACCESS_MODERATION_PAGE, ADMINISTRATE_USERS), ROLE_ADMINISTRATOR(ROLE_MODERATOR, ACCESS_ADMINISTRATION_PAGE), ROLE_OWNER(ROLE_ADMINISTRATOR), ROLE_GUEST(); public final ROLE[] includesRoles; ROLE(ROLE... includesRoles) { this.includesRoles = includesRoles; } } @Autowired
// Path: src/main/java/org/fjorum/model/entity/Role.java // @Entity // @Table(name = "roles") // public class Role { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id", nullable = false) // private Long id; // @Column(name = "name", nullable = false) // private String name; // @Column(name = "description") // private String descriptionKey; // @Column(name = "predefined") // boolean predefined; // // @ManyToMany(cascade = CascadeType.MERGE) // @JoinTable(name = "included_roles", // joinColumns = @JoinColumn(name = "role_id"), // inverseJoinColumns = @JoinColumn(name = "included_role_id")) // private Set<Role> includesRoles = new HashSet<>(); // // Role() { // } // // public Role(String name, String descriptionKey, boolean predefined) { // this.name = name; // this.descriptionKey = descriptionKey; // this.predefined = predefined; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescriptionKey() { // return descriptionKey; // } // // public void setDescriptionKey(String descriptionKey) { // this.descriptionKey = descriptionKey; // } // // public boolean isPredefined() { // return predefined; // } // // public void setPredefined(boolean predefined) { // this.predefined = predefined; // } // // public Set<Role> getIncludedRoles() { // return includesRoles; // } // // public void setIncludedRoles(Set<Role> includedRoles) { // this.includesRoles = includedRoles; // } // // public Set<Role> getAllRoles() { // return Stream.concat(Stream.of(this), // includesRoles.stream().flatMap(role -> role.getAllRoles().stream())) // .collect(Collectors.toSet()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || !(o instanceof Role)) return false; // // Role role = (Role) o; // // return id != null && id.equals(role.id); // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // @Override // public String toString() { // return name; // } // } // // Path: src/main/java/org/fjorum/model/service/RoleService.java // public interface RoleService { // List<Role> getAllRoles(); // // Role addRole(Role role); // // Optional<Role> findRole(String name); // } // Path: src/main/java/org/fjorum/DbInitializer.java import org.fjorum.controller.form.UserCreateForm; import org.fjorum.model.entity.Category; import org.fjorum.model.entity.Role; import org.fjorum.model.entity.User; import org.fjorum.model.service.CategoryService; import org.fjorum.model.service.RoleService; import org.fjorum.model.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; package org.fjorum; @Component @Lazy(false) @Scope("singleton") @Profile("development") public class DbInitializer { private enum ROLE { ACCESS_MODERATION_PAGE, ACCESS_ADMINISTRATION_PAGE, ADMINISTRATE_USERS, ROLE_USER(), ROLE_MODERATOR(ACCESS_MODERATION_PAGE, ADMINISTRATE_USERS), ROLE_ADMINISTRATOR(ROLE_MODERATOR, ACCESS_ADMINISTRATION_PAGE), ROLE_OWNER(ROLE_ADMINISTRATOR), ROLE_GUEST(); public final ROLE[] includesRoles; ROLE(ROLE... includesRoles) { this.includesRoles = includesRoles; } } @Autowired
public DbInitializer(RoleService roleService,
fjorum/fjorum
src/main/java/org/fjorum/DbInitializer.java
// Path: src/main/java/org/fjorum/model/entity/Role.java // @Entity // @Table(name = "roles") // public class Role { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id", nullable = false) // private Long id; // @Column(name = "name", nullable = false) // private String name; // @Column(name = "description") // private String descriptionKey; // @Column(name = "predefined") // boolean predefined; // // @ManyToMany(cascade = CascadeType.MERGE) // @JoinTable(name = "included_roles", // joinColumns = @JoinColumn(name = "role_id"), // inverseJoinColumns = @JoinColumn(name = "included_role_id")) // private Set<Role> includesRoles = new HashSet<>(); // // Role() { // } // // public Role(String name, String descriptionKey, boolean predefined) { // this.name = name; // this.descriptionKey = descriptionKey; // this.predefined = predefined; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescriptionKey() { // return descriptionKey; // } // // public void setDescriptionKey(String descriptionKey) { // this.descriptionKey = descriptionKey; // } // // public boolean isPredefined() { // return predefined; // } // // public void setPredefined(boolean predefined) { // this.predefined = predefined; // } // // public Set<Role> getIncludedRoles() { // return includesRoles; // } // // public void setIncludedRoles(Set<Role> includedRoles) { // this.includesRoles = includedRoles; // } // // public Set<Role> getAllRoles() { // return Stream.concat(Stream.of(this), // includesRoles.stream().flatMap(role -> role.getAllRoles().stream())) // .collect(Collectors.toSet()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || !(o instanceof Role)) return false; // // Role role = (Role) o; // // return id != null && id.equals(role.id); // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // @Override // public String toString() { // return name; // } // } // // Path: src/main/java/org/fjorum/model/service/RoleService.java // public interface RoleService { // List<Role> getAllRoles(); // // Role addRole(Role role); // // Optional<Role> findRole(String name); // }
import org.fjorum.controller.form.UserCreateForm; import org.fjorum.model.entity.Category; import org.fjorum.model.entity.Role; import org.fjorum.model.entity.User; import org.fjorum.model.service.CategoryService; import org.fjorum.model.service.RoleService; import org.fjorum.model.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream;
ACCESS_MODERATION_PAGE, ACCESS_ADMINISTRATION_PAGE, ADMINISTRATE_USERS, ROLE_USER(), ROLE_MODERATOR(ACCESS_MODERATION_PAGE, ADMINISTRATE_USERS), ROLE_ADMINISTRATOR(ROLE_MODERATOR, ACCESS_ADMINISTRATION_PAGE), ROLE_OWNER(ROLE_ADMINISTRATOR), ROLE_GUEST(); public final ROLE[] includesRoles; ROLE(ROLE... includesRoles) { this.includesRoles = includesRoles; } } @Autowired public DbInitializer(RoleService roleService, UserService userService, CategoryService categoryService) { if (roleService.getAllRoles().isEmpty()) { initRoles(roleService); } if (userService.getAll().isEmpty()) { initOwner(userService, roleService); } if (categoryService.getRootCategory() == null) { initCategory(categoryService); } } private void initRoles(RoleService roleService) {
// Path: src/main/java/org/fjorum/model/entity/Role.java // @Entity // @Table(name = "roles") // public class Role { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id", nullable = false) // private Long id; // @Column(name = "name", nullable = false) // private String name; // @Column(name = "description") // private String descriptionKey; // @Column(name = "predefined") // boolean predefined; // // @ManyToMany(cascade = CascadeType.MERGE) // @JoinTable(name = "included_roles", // joinColumns = @JoinColumn(name = "role_id"), // inverseJoinColumns = @JoinColumn(name = "included_role_id")) // private Set<Role> includesRoles = new HashSet<>(); // // Role() { // } // // public Role(String name, String descriptionKey, boolean predefined) { // this.name = name; // this.descriptionKey = descriptionKey; // this.predefined = predefined; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescriptionKey() { // return descriptionKey; // } // // public void setDescriptionKey(String descriptionKey) { // this.descriptionKey = descriptionKey; // } // // public boolean isPredefined() { // return predefined; // } // // public void setPredefined(boolean predefined) { // this.predefined = predefined; // } // // public Set<Role> getIncludedRoles() { // return includesRoles; // } // // public void setIncludedRoles(Set<Role> includedRoles) { // this.includesRoles = includedRoles; // } // // public Set<Role> getAllRoles() { // return Stream.concat(Stream.of(this), // includesRoles.stream().flatMap(role -> role.getAllRoles().stream())) // .collect(Collectors.toSet()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || !(o instanceof Role)) return false; // // Role role = (Role) o; // // return id != null && id.equals(role.id); // } // // @Override // public int hashCode() { // return id != null ? id.hashCode() : 0; // } // // @Override // public String toString() { // return name; // } // } // // Path: src/main/java/org/fjorum/model/service/RoleService.java // public interface RoleService { // List<Role> getAllRoles(); // // Role addRole(Role role); // // Optional<Role> findRole(String name); // } // Path: src/main/java/org/fjorum/DbInitializer.java import org.fjorum.controller.form.UserCreateForm; import org.fjorum.model.entity.Category; import org.fjorum.model.entity.Role; import org.fjorum.model.entity.User; import org.fjorum.model.service.CategoryService; import org.fjorum.model.service.RoleService; import org.fjorum.model.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; ACCESS_MODERATION_PAGE, ACCESS_ADMINISTRATION_PAGE, ADMINISTRATE_USERS, ROLE_USER(), ROLE_MODERATOR(ACCESS_MODERATION_PAGE, ADMINISTRATE_USERS), ROLE_ADMINISTRATOR(ROLE_MODERATOR, ACCESS_ADMINISTRATION_PAGE), ROLE_OWNER(ROLE_ADMINISTRATOR), ROLE_GUEST(); public final ROLE[] includesRoles; ROLE(ROLE... includesRoles) { this.includesRoles = includesRoles; } } @Autowired public DbInitializer(RoleService roleService, UserService userService, CategoryService categoryService) { if (roleService.getAllRoles().isEmpty()) { initRoles(roleService); } if (userService.getAll().isEmpty()) { initOwner(userService, roleService); } if (categoryService.getRootCategory() == null) { initCategory(categoryService); } } private void initRoles(RoleService roleService) {
Map<String, Role> roles = new HashMap<>();