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
asher-stern/CRF
src/main/java/com/asher_stern/crf/postagging/data/penn/PennCorpusReader.java
// Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/FileUtilities.java // public class FileUtilities // { // /** // * Returns an array of File, sorted by their name (alphabetically). // * @param files // * @return // */ // public static File[] getSortedByName(File[] files) // { // ArrayList<File> list = new ArrayList<File>(files.length); // for (File file : files) {list.add(file);} // Collections.sort(list,new FilenameComparator()); // // File[] ret = new File[list.size()]; // int index=0; // for (File file : list) // { // ret[index] = file; // ++index; // } // return ret; // } // // /** // * Reads all the contents of the given text file into a string, and returns that string. // * @param file // * @return // */ // public static String readTextFile(File file) // { // StringBuilder sb = new StringBuilder(); // try(BufferedReader reader = new BufferedReader(new FileReader(file))) // { // String line = reader.readLine(); // while (line != null) // { // sb.append(line).append("\n"); // line = reader.readLine(); // } // } // catch (IOException e) // { // throw new CrfException("IO problem.",e); // } // // return sb.toString(); // } // // /** // * A comparator of two files, where the comparison is by the lexicographic ordering of their names. // * // */ // private static class FilenameComparator implements Comparator<File> // { // @Override // public int compare(File o1, File o2) // { // return o1.getName().compareTo(o2.getName()); // } // } // // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // }
import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import com.asher_stern.crf.utilities.CrfException; import com.asher_stern.crf.utilities.FileUtilities; import com.asher_stern.crf.utilities.TaggedToken;
package com.asher_stern.crf.postagging.data.penn; /** * Iterator for the Penn Tree-Bank. See {@link PennCorpus}. * * @author Asher Stern * Date: Nov 16, 2014 * */ public class PennCorpusReader implements Iterator<List<TaggedToken<String, String>>> { public static final String PENN_FILE_SUFFIX = ".mrg"; public PennCorpusReader(File directory) { super(); this.directory = directory; initialize(); } @Override public boolean hasNext() { return (fileIterator.hasNext() || treeIterator.hasNext()); } @Override public List<TaggedToken<String, String>> next() { while ((null==treeIterator) || (!treeIterator.hasNext())) { File file = fileIterator.next(); // might throw NoSuchElementException.
// Path: src/main/java/com/asher_stern/crf/utilities/CrfException.java // public class CrfException extends RuntimeException // { // private static final long serialVersionUID = 5414394233000815286L; // // public CrfException() // { // super(); // } // // public CrfException(String message, Throwable cause, // boolean enableSuppression, boolean writableStackTrace) // { // super(message, cause, enableSuppression, writableStackTrace); // } // // public CrfException(String message, Throwable cause) // { // super(message, cause); // } // // public CrfException(String message) // { // super(message); // } // // public CrfException(Throwable cause) // { // super(cause); // } // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/FileUtilities.java // public class FileUtilities // { // /** // * Returns an array of File, sorted by their name (alphabetically). // * @param files // * @return // */ // public static File[] getSortedByName(File[] files) // { // ArrayList<File> list = new ArrayList<File>(files.length); // for (File file : files) {list.add(file);} // Collections.sort(list,new FilenameComparator()); // // File[] ret = new File[list.size()]; // int index=0; // for (File file : list) // { // ret[index] = file; // ++index; // } // return ret; // } // // /** // * Reads all the contents of the given text file into a string, and returns that string. // * @param file // * @return // */ // public static String readTextFile(File file) // { // StringBuilder sb = new StringBuilder(); // try(BufferedReader reader = new BufferedReader(new FileReader(file))) // { // String line = reader.readLine(); // while (line != null) // { // sb.append(line).append("\n"); // line = reader.readLine(); // } // } // catch (IOException e) // { // throw new CrfException("IO problem.",e); // } // // return sb.toString(); // } // // /** // * A comparator of two files, where the comparison is by the lexicographic ordering of their names. // * // */ // private static class FilenameComparator implements Comparator<File> // { // @Override // public int compare(File o1, File o2) // { // return o1.getName().compareTo(o2.getName()); // } // } // // // // } // // Path: src/main/java/com/asher_stern/crf/utilities/TaggedToken.java // public class TaggedToken<K,G> // { // public TaggedToken(K token, G tag) // { // super(); // this.token = token; // this.tag = tag; // } // // // // public K getToken() // { // return token; // } // public G getTag() // { // return tag; // } // // // // // @Override // public String toString() // { // return "CrfTaggedToken [getToken()=" + getToken() + ", getTag()=" // + getTag() + "]"; // } // // // // // // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + ((tag == null) ? 0 : tag.hashCode()); // result = prime * result + ((token == null) ? 0 : token.hashCode()); // return result; // } // // // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaggedToken<?,?> other = (TaggedToken<?,?>) obj; // if (tag == null) // { // if (other.tag != null) // return false; // } else if (!tag.equals(other.tag)) // return false; // if (token == null) // { // if (other.token != null) // return false; // } else if (!token.equals(other.token)) // return false; // return true; // } // // // // // // // private final K token; // private final G tag; // } // Path: src/main/java/com/asher_stern/crf/postagging/data/penn/PennCorpusReader.java import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import com.asher_stern.crf.utilities.CrfException; import com.asher_stern.crf.utilities.FileUtilities; import com.asher_stern.crf.utilities.TaggedToken; package com.asher_stern.crf.postagging.data.penn; /** * Iterator for the Penn Tree-Bank. See {@link PennCorpus}. * * @author Asher Stern * Date: Nov 16, 2014 * */ public class PennCorpusReader implements Iterator<List<TaggedToken<String, String>>> { public static final String PENN_FILE_SUFFIX = ".mrg"; public PennCorpusReader(File directory) { super(); this.directory = directory; initialize(); } @Override public boolean hasNext() { return (fileIterator.hasNext() || treeIterator.hasNext()); } @Override public List<TaggedToken<String, String>> next() { while ((null==treeIterator) || (!treeIterator.hasNext())) { File file = fileIterator.next(); // might throw NoSuchElementException.
String fileContents = FileUtilities.readTextFile(file);
cesardeazevedo/react-native-bottom-sheet-behavior
example/android/app/src/main/java/com/bsbexample/MainApplication.java
// Path: android/src/main/java/com/bottomsheetbehavior/BottomSheetBehaviorPackage.java // public class BottomSheetBehaviorPackage implements ReactPackage { // @Override // public List<NativeModule> createNativeModules(ReactApplicationContext reactApplicationContext) { // return Collections.emptyList(); // } // // @Override // public List<ViewManager> createViewManagers(ReactApplicationContext reactApplicationContext) { // return Arrays.<ViewManager>asList( // new MergedAppBarLayoutManager(), // new ScrollingAppBarLayoutManager(), // new BottomSheetHeaderManager(), // new BottomSheetBehaviorManager(), // new BackdropBottomSheetManager(), // new CoordinatorLayoutManager(), // new FloatingActionButtonManager() // ); // } // }
import android.app.Application; import com.reactnativecommunity.viewpager.RNCViewPagerPackage; import com.bottomsheetbehavior.BottomSheetBehaviorPackage; import com.oblador.vectoricons.VectorIconsPackage; import com.rnnestedscrollview.RNNestedScrollViewPackage; import com.facebook.react.ReactApplication; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import java.util.Arrays; import java.util.List;
package com.bsbexample; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new VectorIconsPackage(), new RNCViewPagerPackage(),
// Path: android/src/main/java/com/bottomsheetbehavior/BottomSheetBehaviorPackage.java // public class BottomSheetBehaviorPackage implements ReactPackage { // @Override // public List<NativeModule> createNativeModules(ReactApplicationContext reactApplicationContext) { // return Collections.emptyList(); // } // // @Override // public List<ViewManager> createViewManagers(ReactApplicationContext reactApplicationContext) { // return Arrays.<ViewManager>asList( // new MergedAppBarLayoutManager(), // new ScrollingAppBarLayoutManager(), // new BottomSheetHeaderManager(), // new BottomSheetBehaviorManager(), // new BackdropBottomSheetManager(), // new CoordinatorLayoutManager(), // new FloatingActionButtonManager() // ); // } // } // Path: example/android/app/src/main/java/com/bsbexample/MainApplication.java import android.app.Application; import com.reactnativecommunity.viewpager.RNCViewPagerPackage; import com.bottomsheetbehavior.BottomSheetBehaviorPackage; import com.oblador.vectoricons.VectorIconsPackage; import com.rnnestedscrollview.RNNestedScrollViewPackage; import com.facebook.react.ReactApplication; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import java.util.Arrays; import java.util.List; package com.bsbexample; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new VectorIconsPackage(), new RNCViewPagerPackage(),
new BottomSheetBehaviorPackage(),
dai1741/forked_from_MikuMikuDroid
MikuMikuDroid/src/jp/gauzau/MikuMikuDroidmod/MikuRendererGLES20.java
// Path: MikuMikuDroid/src/jp/gauzau/MikuMikuDroidmod/Miku.java // public class RenderSet { // public String shader; // public String target; // public RenderSet(String s, String t) { // shader = s; // target = t; // } // }
import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.Map.Entry; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import jp.gauzau.MikuMikuDroidmod.Miku.RenderSet; import android.graphics.BitmapFactory; import android.opengl.GLES20; import android.opengl.GLU; import android.util.Log;
@Override public void onSurfaceChanged(GL10 gl, int width, int height) { super.onSurfaceChanged(gl, width, height); GLES20.glViewport(0, 0, width, height); } @Override public void onDrawFrame(GL10 gl) { mLightDir[0] = -0.5f; mLightDir[1] = -1.0f; mLightDir[2] = -0.5f; // in left-handed region Vector.normalize(mLightDir); mRT.get("screen").switchTargetFrameBuffer(); int clearMask = GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT; if (mUsesCoverageAa) { final int GL_COVERAGE_BUFFER_BIT_NV = 0x8000; clearMask |= GL_COVERAGE_BUFFER_BIT_NV; } GLES20.glClear(clearMask); initializeAllTexture(false); // initializeAllSkinningTexture(); int pos = mCoreLogic.applyCurrentMotion(); //////////////////////////////////////////////////////////////////// //// draw models if (mCoreLogic.getMiku() != null) { for (Miku miku : mCoreLogic.getMiku()) { if(miku.mModel.mIsTextureLoaded) {
// Path: MikuMikuDroid/src/jp/gauzau/MikuMikuDroidmod/Miku.java // public class RenderSet { // public String shader; // public String target; // public RenderSet(String s, String t) { // shader = s; // target = t; // } // } // Path: MikuMikuDroid/src/jp/gauzau/MikuMikuDroidmod/MikuRendererGLES20.java import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.Map.Entry; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import jp.gauzau.MikuMikuDroidmod.Miku.RenderSet; import android.graphics.BitmapFactory; import android.opengl.GLES20; import android.opengl.GLU; import android.util.Log; @Override public void onSurfaceChanged(GL10 gl, int width, int height) { super.onSurfaceChanged(gl, width, height); GLES20.glViewport(0, 0, width, height); } @Override public void onDrawFrame(GL10 gl) { mLightDir[0] = -0.5f; mLightDir[1] = -1.0f; mLightDir[2] = -0.5f; // in left-handed region Vector.normalize(mLightDir); mRT.get("screen").switchTargetFrameBuffer(); int clearMask = GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT; if (mUsesCoverageAa) { final int GL_COVERAGE_BUFFER_BIT_NV = 0x8000; clearMask |= GL_COVERAGE_BUFFER_BIT_NV; } GLES20.glClear(clearMask); initializeAllTexture(false); // initializeAllSkinningTexture(); int pos = mCoreLogic.applyCurrentMotion(); //////////////////////////////////////////////////////////////////// //// draw models if (mCoreLogic.getMiku() != null) { for (Miku miku : mCoreLogic.getMiku()) { if(miku.mModel.mIsTextureLoaded) {
for(RenderSet rs: miku.mRenderSenario) {
maruohon/minihud
src/main/java/fi/dy/masa/minihud/gui/widget/info/RendererToggleConfigStatusWidget.java
// Path: src/main/java/fi/dy/masa/minihud/config/RendererToggle.java // public enum RendererToggle implements ConfigInfo // { // DEBUG_COLLISION_BOXES ("debugCollisionBoxEnabled"), // DEBUG_HEIGHT_MAP ("debugHeightMapEnabled"), // DEBUG_NEIGHBOR_UPDATES ("debugNeighborsUpdateEnabled"), // DEBUG_PATH_FINDING ("debugPathfindingEnabled"), // DEBUG_SOLID_FACES ("debugSolidFaceEnabled"), // DEBUG_WATER ("debugWaterEnabled"), // // OVERLAY_BEACON_RANGE ("overlayBeaconRange"), // OVERLAY_BLOCK_GRID ("overlayBlockGrid"), // OVERLAY_CHUNK_UNLOAD_BUCKET ("overlayChunkUnloadBucket", KeyBindSettings.INGAME_BOTH), // OVERLAY_LIGHT_LEVEL ("overlayLightLevel"), // OVERLAY_RANDOM_TICKS_FIXED ("overlayRandomTicksFixed"), // OVERLAY_RANDOM_TICKS_PLAYER ("overlayRandomTicksPlayer"), // OVERLAY_REGION_FILE ("overlayRegionFile"), // OVERLAY_SLIME_CHUNKS_OVERLAY ("overlaySlimeChunks", KeyBindSettings.INGAME_BOTH), // OVERLAY_SPAWNABLE_CHUNKS_FIXED ("overlaySpawnableChunksFixed"), // OVERLAY_SPAWNABLE_CHUNKS_PLAYER ("overlaySpawnableChunksPlayer"), // OVERLAY_SPAWNABLE_COLUMN_HEIGHTS ("overlaySpawnableColumnHeights"), // OVERLAY_SPAWNER_POSITIONS ("overlaySpawnerPositions"), // OVERLAY_SPAWN_CHUNK_OVERLAY_REAL ("overlaySpawnChunkReal"), // OVERLAY_SPAWN_CHUNK_OVERLAY_PLAYER ("overlaySpawnChunkPlayer"), // OVERLAY_STRUCTURE_MAIN_TOGGLE ("overlayStructureMainToggle"), // OVERLAY_WATER_FALLS ("overlayWaterFalls"), // SHAPE_RENDERER ("shapeRenderer"); // // public static final ImmutableList<RendererToggle> VALUES = ImmutableList.copyOf(values()); // public static final ImmutableList<BooleanConfig> TOGGLE_CONFIGS = ImmutableList.copyOf(VALUES.stream().map(RendererToggle::getBooleanConfig).collect(Collectors.toList())); // public static final ImmutableList<HotkeyConfig> TOGGLE_HOTKEYS = ImmutableList.copyOf(VALUES.stream().map(RendererToggle::getHotkeyConfig).collect(Collectors.toList())); // // private final BooleanConfig toggleStatus; // private final HotkeyConfig toggleHotkey; // // RendererToggle(String name) // { // this(name, KeyBindSettings.INGAME_DEFAULT); // } // // RendererToggle(String name, KeyBindSettings settings) // { // this.toggleStatus = new BooleanConfig(name, false); // this.toggleHotkey = new HotkeyConfig(name, "", settings); // // String nameLower = name.toLowerCase(Locale.ROOT); // String nameKey = "minihud.renderer_toggle.name." + nameLower; // String commentKey = "minihud.renderer_toggle.comment." + nameLower; // // if (name.startsWith("debug")) // { // this.toggleHotkey.getKeyBind().setCallback(new DebugRendererHotkeyCallback(this)); // } // else // { // this.toggleHotkey.getKeyBind().setCallback(new RendererToggleHotkeyCallback(this.toggleStatus)); // } // // if (name.equals("overlayStructureMainToggle")) // { // this.toggleStatus.setValueChangeCallback((newValue, oldValue) -> DataStorage.getInstance().getStructureStorage().requestStructureDataUpdates()); // } // // this.toggleStatus.setNameTranslationKey(nameKey); // this.toggleStatus.setPrettyNameTranslationKey(nameKey); // this.toggleStatus.setCommentTranslationKey(commentKey); // // this.toggleHotkey.setNameTranslationKey(nameKey); // this.toggleHotkey.setPrettyNameTranslationKey(nameKey); // this.toggleHotkey.setCommentTranslationKey(commentKey); // } // // public boolean isRendererEnabled() // { // return this.toggleStatus.getBooleanValue(); // } // // public void addValueChangeListener(EventListener listener) // { // this.toggleStatus.addValueChangeListener(listener); // } // // public BooleanConfig getBooleanConfig() // { // return this.toggleStatus; // } // // public HotkeyConfig getHotkeyConfig() // { // return this.toggleHotkey; // } // // public KeyBind getKeyBind() // { // return this.toggleHotkey.getKeyBind(); // } // // @Override // public ModInfo getModInfo() // { // return Reference.MOD_INFO; // } // // @Override // public String getName() // { // return this.toggleStatus.getName(); // } // // @Override // public String getDisplayName() // { // return this.toggleStatus.getDisplayName(); // } // // @Override // public Optional<String> getComment() // { // return this.toggleStatus.getComment(); // } // // @Override // public boolean isModified() // { // return this.toggleStatus.isModified() || this.toggleHotkey.isModified(); // } // // @Override // public void resetToDefault() // { // this.toggleStatus.resetToDefault(); // this.toggleHotkey.resetToDefault(); // } // }
import fi.dy.masa.malilib.overlay.widget.sub.HotkeyedBooleanConfigStatusWidget; import fi.dy.masa.malilib.util.data.ConfigOnTab; import fi.dy.masa.minihud.config.RendererToggle;
package fi.dy.masa.minihud.gui.widget.info; public class RendererToggleConfigStatusWidget extends HotkeyedBooleanConfigStatusWidget {
// Path: src/main/java/fi/dy/masa/minihud/config/RendererToggle.java // public enum RendererToggle implements ConfigInfo // { // DEBUG_COLLISION_BOXES ("debugCollisionBoxEnabled"), // DEBUG_HEIGHT_MAP ("debugHeightMapEnabled"), // DEBUG_NEIGHBOR_UPDATES ("debugNeighborsUpdateEnabled"), // DEBUG_PATH_FINDING ("debugPathfindingEnabled"), // DEBUG_SOLID_FACES ("debugSolidFaceEnabled"), // DEBUG_WATER ("debugWaterEnabled"), // // OVERLAY_BEACON_RANGE ("overlayBeaconRange"), // OVERLAY_BLOCK_GRID ("overlayBlockGrid"), // OVERLAY_CHUNK_UNLOAD_BUCKET ("overlayChunkUnloadBucket", KeyBindSettings.INGAME_BOTH), // OVERLAY_LIGHT_LEVEL ("overlayLightLevel"), // OVERLAY_RANDOM_TICKS_FIXED ("overlayRandomTicksFixed"), // OVERLAY_RANDOM_TICKS_PLAYER ("overlayRandomTicksPlayer"), // OVERLAY_REGION_FILE ("overlayRegionFile"), // OVERLAY_SLIME_CHUNKS_OVERLAY ("overlaySlimeChunks", KeyBindSettings.INGAME_BOTH), // OVERLAY_SPAWNABLE_CHUNKS_FIXED ("overlaySpawnableChunksFixed"), // OVERLAY_SPAWNABLE_CHUNKS_PLAYER ("overlaySpawnableChunksPlayer"), // OVERLAY_SPAWNABLE_COLUMN_HEIGHTS ("overlaySpawnableColumnHeights"), // OVERLAY_SPAWNER_POSITIONS ("overlaySpawnerPositions"), // OVERLAY_SPAWN_CHUNK_OVERLAY_REAL ("overlaySpawnChunkReal"), // OVERLAY_SPAWN_CHUNK_OVERLAY_PLAYER ("overlaySpawnChunkPlayer"), // OVERLAY_STRUCTURE_MAIN_TOGGLE ("overlayStructureMainToggle"), // OVERLAY_WATER_FALLS ("overlayWaterFalls"), // SHAPE_RENDERER ("shapeRenderer"); // // public static final ImmutableList<RendererToggle> VALUES = ImmutableList.copyOf(values()); // public static final ImmutableList<BooleanConfig> TOGGLE_CONFIGS = ImmutableList.copyOf(VALUES.stream().map(RendererToggle::getBooleanConfig).collect(Collectors.toList())); // public static final ImmutableList<HotkeyConfig> TOGGLE_HOTKEYS = ImmutableList.copyOf(VALUES.stream().map(RendererToggle::getHotkeyConfig).collect(Collectors.toList())); // // private final BooleanConfig toggleStatus; // private final HotkeyConfig toggleHotkey; // // RendererToggle(String name) // { // this(name, KeyBindSettings.INGAME_DEFAULT); // } // // RendererToggle(String name, KeyBindSettings settings) // { // this.toggleStatus = new BooleanConfig(name, false); // this.toggleHotkey = new HotkeyConfig(name, "", settings); // // String nameLower = name.toLowerCase(Locale.ROOT); // String nameKey = "minihud.renderer_toggle.name." + nameLower; // String commentKey = "minihud.renderer_toggle.comment." + nameLower; // // if (name.startsWith("debug")) // { // this.toggleHotkey.getKeyBind().setCallback(new DebugRendererHotkeyCallback(this)); // } // else // { // this.toggleHotkey.getKeyBind().setCallback(new RendererToggleHotkeyCallback(this.toggleStatus)); // } // // if (name.equals("overlayStructureMainToggle")) // { // this.toggleStatus.setValueChangeCallback((newValue, oldValue) -> DataStorage.getInstance().getStructureStorage().requestStructureDataUpdates()); // } // // this.toggleStatus.setNameTranslationKey(nameKey); // this.toggleStatus.setPrettyNameTranslationKey(nameKey); // this.toggleStatus.setCommentTranslationKey(commentKey); // // this.toggleHotkey.setNameTranslationKey(nameKey); // this.toggleHotkey.setPrettyNameTranslationKey(nameKey); // this.toggleHotkey.setCommentTranslationKey(commentKey); // } // // public boolean isRendererEnabled() // { // return this.toggleStatus.getBooleanValue(); // } // // public void addValueChangeListener(EventListener listener) // { // this.toggleStatus.addValueChangeListener(listener); // } // // public BooleanConfig getBooleanConfig() // { // return this.toggleStatus; // } // // public HotkeyConfig getHotkeyConfig() // { // return this.toggleHotkey; // } // // public KeyBind getKeyBind() // { // return this.toggleHotkey.getKeyBind(); // } // // @Override // public ModInfo getModInfo() // { // return Reference.MOD_INFO; // } // // @Override // public String getName() // { // return this.toggleStatus.getName(); // } // // @Override // public String getDisplayName() // { // return this.toggleStatus.getDisplayName(); // } // // @Override // public Optional<String> getComment() // { // return this.toggleStatus.getComment(); // } // // @Override // public boolean isModified() // { // return this.toggleStatus.isModified() || this.toggleHotkey.isModified(); // } // // @Override // public void resetToDefault() // { // this.toggleStatus.resetToDefault(); // this.toggleHotkey.resetToDefault(); // } // } // Path: src/main/java/fi/dy/masa/minihud/gui/widget/info/RendererToggleConfigStatusWidget.java import fi.dy.masa.malilib.overlay.widget.sub.HotkeyedBooleanConfigStatusWidget; import fi.dy.masa.malilib.util.data.ConfigOnTab; import fi.dy.masa.minihud.config.RendererToggle; package fi.dy.masa.minihud.gui.widget.info; public class RendererToggleConfigStatusWidget extends HotkeyedBooleanConfigStatusWidget {
public RendererToggleConfigStatusWidget(RendererToggle config, ConfigOnTab configOnTab)
maruohon/minihud
src/main/java/fi/dy/masa/minihud/config/InfoLine.java
// Path: src/main/java/fi/dy/masa/minihud/Reference.java // public class Reference // { // public static final String MOD_ID = "minihud"; // public static final String MOD_NAME = "MiniHUD"; // public static final String MOD_VERSION = "@MOD_VERSION@"; // // public static final ModInfo MOD_INFO = new ModInfo(MOD_ID, MOD_NAME); // }
import java.util.Locale; import java.util.Optional; import java.util.stream.Collectors; import com.google.common.collect.ImmutableList; import fi.dy.masa.malilib.config.option.BooleanConfig; import fi.dy.masa.malilib.config.option.ConfigInfo; import fi.dy.masa.malilib.config.option.HotkeyConfig; import fi.dy.masa.malilib.config.option.IntegerConfig; import fi.dy.masa.malilib.input.KeyBind; import fi.dy.masa.malilib.input.KeyBindSettings; import fi.dy.masa.malilib.input.callback.ToggleBooleanWithMessageKeyCallback; import fi.dy.masa.malilib.listener.EventListener; import fi.dy.masa.malilib.util.data.ModInfo; import fi.dy.masa.minihud.Reference;
} public int getLineOrder() { return this.lineOrder.getIntegerValue(); } public BooleanConfig getBooleanConfig() { return this.toggleStatus; } public HotkeyConfig getHotkeyConfig() { return this.toggleHotkey; } public KeyBind getKeyBind() { return this.toggleHotkey.getKeyBind(); } public IntegerConfig getLineOrderConfig() { return this.lineOrder; } @Override public ModInfo getModInfo() {
// Path: src/main/java/fi/dy/masa/minihud/Reference.java // public class Reference // { // public static final String MOD_ID = "minihud"; // public static final String MOD_NAME = "MiniHUD"; // public static final String MOD_VERSION = "@MOD_VERSION@"; // // public static final ModInfo MOD_INFO = new ModInfo(MOD_ID, MOD_NAME); // } // Path: src/main/java/fi/dy/masa/minihud/config/InfoLine.java import java.util.Locale; import java.util.Optional; import java.util.stream.Collectors; import com.google.common.collect.ImmutableList; import fi.dy.masa.malilib.config.option.BooleanConfig; import fi.dy.masa.malilib.config.option.ConfigInfo; import fi.dy.masa.malilib.config.option.HotkeyConfig; import fi.dy.masa.malilib.config.option.IntegerConfig; import fi.dy.masa.malilib.input.KeyBind; import fi.dy.masa.malilib.input.KeyBindSettings; import fi.dy.masa.malilib.input.callback.ToggleBooleanWithMessageKeyCallback; import fi.dy.masa.malilib.listener.EventListener; import fi.dy.masa.malilib.util.data.ModInfo; import fi.dy.masa.minihud.Reference; } public int getLineOrder() { return this.lineOrder.getIntegerValue(); } public BooleanConfig getBooleanConfig() { return this.toggleStatus; } public HotkeyConfig getHotkeyConfig() { return this.toggleHotkey; } public KeyBind getKeyBind() { return this.toggleHotkey.getKeyBind(); } public IntegerConfig getLineOrderConfig() { return this.lineOrder; } @Override public ModInfo getModInfo() {
return Reference.MOD_INFO;
maruohon/minihud
src/main/java/fi/dy/masa/minihud/renderer/BaseBlockPositionListOverlayRenderer.java
// Path: src/main/java/fi/dy/masa/minihud/data/OrderedBlockPosLong.java // public class OrderedBlockPosLong // { // public final long posLong; // public final int order; // // public OrderedBlockPosLong(long posLong, int order) // { // this.posLong = posLong; // this.order = order; // } // // public BlockPos getPos() // { // return BlockPos.fromLong(this.posLong); // } // // @Override // public boolean equals(Object o) // { // if (this == o) {return true;} // if (o == null || this.getClass() != o.getClass()) {return false;} // // OrderedBlockPosLong that = (OrderedBlockPosLong) o; // // if (this.posLong != that.posLong) {return false;} // return this.order == that.order; // } // // @Override // public int hashCode() // { // int result = (int) (this.posLong ^ (this.posLong >>> 32)); // result = 31 * result + this.order; // return result; // } // // public static OrderedBlockPosLong of(BlockPos pos, int order) // { // return new OrderedBlockPosLong(pos.toLong(), order); // } // }
import java.util.ArrayList; import java.util.List; import java.util.function.BooleanSupplier; import java.util.function.Supplier; import org.lwjgl.opengl.GL11; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.Entity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.math.Vec3d; import fi.dy.masa.malilib.render.ShapeRenderUtils; import fi.dy.masa.malilib.render.TextRenderUtils; import fi.dy.masa.malilib.render.overlay.BaseRenderObject; import fi.dy.masa.malilib.util.data.Color4f; import fi.dy.masa.minihud.data.OrderedBlockPosLong; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
package fi.dy.masa.minihud.renderer; public abstract class BaseBlockPositionListOverlayRenderer extends OverlayRendererBase {
// Path: src/main/java/fi/dy/masa/minihud/data/OrderedBlockPosLong.java // public class OrderedBlockPosLong // { // public final long posLong; // public final int order; // // public OrderedBlockPosLong(long posLong, int order) // { // this.posLong = posLong; // this.order = order; // } // // public BlockPos getPos() // { // return BlockPos.fromLong(this.posLong); // } // // @Override // public boolean equals(Object o) // { // if (this == o) {return true;} // if (o == null || this.getClass() != o.getClass()) {return false;} // // OrderedBlockPosLong that = (OrderedBlockPosLong) o; // // if (this.posLong != that.posLong) {return false;} // return this.order == that.order; // } // // @Override // public int hashCode() // { // int result = (int) (this.posLong ^ (this.posLong >>> 32)); // result = 31 * result + this.order; // return result; // } // // public static OrderedBlockPosLong of(BlockPos pos, int order) // { // return new OrderedBlockPosLong(pos.toLong(), order); // } // } // Path: src/main/java/fi/dy/masa/minihud/renderer/BaseBlockPositionListOverlayRenderer.java import java.util.ArrayList; import java.util.List; import java.util.function.BooleanSupplier; import java.util.function.Supplier; import org.lwjgl.opengl.GL11; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.Entity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.math.Vec3d; import fi.dy.masa.malilib.render.ShapeRenderUtils; import fi.dy.masa.malilib.render.TextRenderUtils; import fi.dy.masa.malilib.render.overlay.BaseRenderObject; import fi.dy.masa.malilib.util.data.Color4f; import fi.dy.masa.minihud.data.OrderedBlockPosLong; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; package fi.dy.masa.minihud.renderer; public abstract class BaseBlockPositionListOverlayRenderer extends OverlayRendererBase {
protected final Long2ObjectOpenHashMap<ArrayList<OrderedBlockPosLong>> textPositions = new Long2ObjectOpenHashMap<>();
maruohon/minihud
src/main/java/fi/dy/masa/minihud/gui/widget/RendererToggleConfigWidget.java
// Path: src/main/java/fi/dy/masa/minihud/config/RendererToggle.java // public enum RendererToggle implements ConfigInfo // { // DEBUG_COLLISION_BOXES ("debugCollisionBoxEnabled"), // DEBUG_HEIGHT_MAP ("debugHeightMapEnabled"), // DEBUG_NEIGHBOR_UPDATES ("debugNeighborsUpdateEnabled"), // DEBUG_PATH_FINDING ("debugPathfindingEnabled"), // DEBUG_SOLID_FACES ("debugSolidFaceEnabled"), // DEBUG_WATER ("debugWaterEnabled"), // // OVERLAY_BEACON_RANGE ("overlayBeaconRange"), // OVERLAY_BLOCK_GRID ("overlayBlockGrid"), // OVERLAY_CHUNK_UNLOAD_BUCKET ("overlayChunkUnloadBucket", KeyBindSettings.INGAME_BOTH), // OVERLAY_LIGHT_LEVEL ("overlayLightLevel"), // OVERLAY_RANDOM_TICKS_FIXED ("overlayRandomTicksFixed"), // OVERLAY_RANDOM_TICKS_PLAYER ("overlayRandomTicksPlayer"), // OVERLAY_REGION_FILE ("overlayRegionFile"), // OVERLAY_SLIME_CHUNKS_OVERLAY ("overlaySlimeChunks", KeyBindSettings.INGAME_BOTH), // OVERLAY_SPAWNABLE_CHUNKS_FIXED ("overlaySpawnableChunksFixed"), // OVERLAY_SPAWNABLE_CHUNKS_PLAYER ("overlaySpawnableChunksPlayer"), // OVERLAY_SPAWNABLE_COLUMN_HEIGHTS ("overlaySpawnableColumnHeights"), // OVERLAY_SPAWNER_POSITIONS ("overlaySpawnerPositions"), // OVERLAY_SPAWN_CHUNK_OVERLAY_REAL ("overlaySpawnChunkReal"), // OVERLAY_SPAWN_CHUNK_OVERLAY_PLAYER ("overlaySpawnChunkPlayer"), // OVERLAY_STRUCTURE_MAIN_TOGGLE ("overlayStructureMainToggle"), // OVERLAY_WATER_FALLS ("overlayWaterFalls"), // SHAPE_RENDERER ("shapeRenderer"); // // public static final ImmutableList<RendererToggle> VALUES = ImmutableList.copyOf(values()); // public static final ImmutableList<BooleanConfig> TOGGLE_CONFIGS = ImmutableList.copyOf(VALUES.stream().map(RendererToggle::getBooleanConfig).collect(Collectors.toList())); // public static final ImmutableList<HotkeyConfig> TOGGLE_HOTKEYS = ImmutableList.copyOf(VALUES.stream().map(RendererToggle::getHotkeyConfig).collect(Collectors.toList())); // // private final BooleanConfig toggleStatus; // private final HotkeyConfig toggleHotkey; // // RendererToggle(String name) // { // this(name, KeyBindSettings.INGAME_DEFAULT); // } // // RendererToggle(String name, KeyBindSettings settings) // { // this.toggleStatus = new BooleanConfig(name, false); // this.toggleHotkey = new HotkeyConfig(name, "", settings); // // String nameLower = name.toLowerCase(Locale.ROOT); // String nameKey = "minihud.renderer_toggle.name." + nameLower; // String commentKey = "minihud.renderer_toggle.comment." + nameLower; // // if (name.startsWith("debug")) // { // this.toggleHotkey.getKeyBind().setCallback(new DebugRendererHotkeyCallback(this)); // } // else // { // this.toggleHotkey.getKeyBind().setCallback(new RendererToggleHotkeyCallback(this.toggleStatus)); // } // // if (name.equals("overlayStructureMainToggle")) // { // this.toggleStatus.setValueChangeCallback((newValue, oldValue) -> DataStorage.getInstance().getStructureStorage().requestStructureDataUpdates()); // } // // this.toggleStatus.setNameTranslationKey(nameKey); // this.toggleStatus.setPrettyNameTranslationKey(nameKey); // this.toggleStatus.setCommentTranslationKey(commentKey); // // this.toggleHotkey.setNameTranslationKey(nameKey); // this.toggleHotkey.setPrettyNameTranslationKey(nameKey); // this.toggleHotkey.setCommentTranslationKey(commentKey); // } // // public boolean isRendererEnabled() // { // return this.toggleStatus.getBooleanValue(); // } // // public void addValueChangeListener(EventListener listener) // { // this.toggleStatus.addValueChangeListener(listener); // } // // public BooleanConfig getBooleanConfig() // { // return this.toggleStatus; // } // // public HotkeyConfig getHotkeyConfig() // { // return this.toggleHotkey; // } // // public KeyBind getKeyBind() // { // return this.toggleHotkey.getKeyBind(); // } // // @Override // public ModInfo getModInfo() // { // return Reference.MOD_INFO; // } // // @Override // public String getName() // { // return this.toggleStatus.getName(); // } // // @Override // public String getDisplayName() // { // return this.toggleStatus.getDisplayName(); // } // // @Override // public Optional<String> getComment() // { // return this.toggleStatus.getComment(); // } // // @Override // public boolean isModified() // { // return this.toggleStatus.isModified() || this.toggleHotkey.isModified(); // } // // @Override // public void resetToDefault() // { // this.toggleStatus.resetToDefault(); // this.toggleHotkey.resetToDefault(); // } // }
import fi.dy.masa.malilib.gui.config.ConfigWidgetContext; import fi.dy.masa.malilib.gui.widget.list.entry.config.BaseHotkeyedBooleanConfigWidget; import fi.dy.masa.minihud.config.RendererToggle;
package fi.dy.masa.minihud.gui.widget; public class RendererToggleConfigWidget extends BaseHotkeyedBooleanConfigWidget { public RendererToggleConfigWidget(int x, int y, int width, int height, int listIndex,
// Path: src/main/java/fi/dy/masa/minihud/config/RendererToggle.java // public enum RendererToggle implements ConfigInfo // { // DEBUG_COLLISION_BOXES ("debugCollisionBoxEnabled"), // DEBUG_HEIGHT_MAP ("debugHeightMapEnabled"), // DEBUG_NEIGHBOR_UPDATES ("debugNeighborsUpdateEnabled"), // DEBUG_PATH_FINDING ("debugPathfindingEnabled"), // DEBUG_SOLID_FACES ("debugSolidFaceEnabled"), // DEBUG_WATER ("debugWaterEnabled"), // // OVERLAY_BEACON_RANGE ("overlayBeaconRange"), // OVERLAY_BLOCK_GRID ("overlayBlockGrid"), // OVERLAY_CHUNK_UNLOAD_BUCKET ("overlayChunkUnloadBucket", KeyBindSettings.INGAME_BOTH), // OVERLAY_LIGHT_LEVEL ("overlayLightLevel"), // OVERLAY_RANDOM_TICKS_FIXED ("overlayRandomTicksFixed"), // OVERLAY_RANDOM_TICKS_PLAYER ("overlayRandomTicksPlayer"), // OVERLAY_REGION_FILE ("overlayRegionFile"), // OVERLAY_SLIME_CHUNKS_OVERLAY ("overlaySlimeChunks", KeyBindSettings.INGAME_BOTH), // OVERLAY_SPAWNABLE_CHUNKS_FIXED ("overlaySpawnableChunksFixed"), // OVERLAY_SPAWNABLE_CHUNKS_PLAYER ("overlaySpawnableChunksPlayer"), // OVERLAY_SPAWNABLE_COLUMN_HEIGHTS ("overlaySpawnableColumnHeights"), // OVERLAY_SPAWNER_POSITIONS ("overlaySpawnerPositions"), // OVERLAY_SPAWN_CHUNK_OVERLAY_REAL ("overlaySpawnChunkReal"), // OVERLAY_SPAWN_CHUNK_OVERLAY_PLAYER ("overlaySpawnChunkPlayer"), // OVERLAY_STRUCTURE_MAIN_TOGGLE ("overlayStructureMainToggle"), // OVERLAY_WATER_FALLS ("overlayWaterFalls"), // SHAPE_RENDERER ("shapeRenderer"); // // public static final ImmutableList<RendererToggle> VALUES = ImmutableList.copyOf(values()); // public static final ImmutableList<BooleanConfig> TOGGLE_CONFIGS = ImmutableList.copyOf(VALUES.stream().map(RendererToggle::getBooleanConfig).collect(Collectors.toList())); // public static final ImmutableList<HotkeyConfig> TOGGLE_HOTKEYS = ImmutableList.copyOf(VALUES.stream().map(RendererToggle::getHotkeyConfig).collect(Collectors.toList())); // // private final BooleanConfig toggleStatus; // private final HotkeyConfig toggleHotkey; // // RendererToggle(String name) // { // this(name, KeyBindSettings.INGAME_DEFAULT); // } // // RendererToggle(String name, KeyBindSettings settings) // { // this.toggleStatus = new BooleanConfig(name, false); // this.toggleHotkey = new HotkeyConfig(name, "", settings); // // String nameLower = name.toLowerCase(Locale.ROOT); // String nameKey = "minihud.renderer_toggle.name." + nameLower; // String commentKey = "minihud.renderer_toggle.comment." + nameLower; // // if (name.startsWith("debug")) // { // this.toggleHotkey.getKeyBind().setCallback(new DebugRendererHotkeyCallback(this)); // } // else // { // this.toggleHotkey.getKeyBind().setCallback(new RendererToggleHotkeyCallback(this.toggleStatus)); // } // // if (name.equals("overlayStructureMainToggle")) // { // this.toggleStatus.setValueChangeCallback((newValue, oldValue) -> DataStorage.getInstance().getStructureStorage().requestStructureDataUpdates()); // } // // this.toggleStatus.setNameTranslationKey(nameKey); // this.toggleStatus.setPrettyNameTranslationKey(nameKey); // this.toggleStatus.setCommentTranslationKey(commentKey); // // this.toggleHotkey.setNameTranslationKey(nameKey); // this.toggleHotkey.setPrettyNameTranslationKey(nameKey); // this.toggleHotkey.setCommentTranslationKey(commentKey); // } // // public boolean isRendererEnabled() // { // return this.toggleStatus.getBooleanValue(); // } // // public void addValueChangeListener(EventListener listener) // { // this.toggleStatus.addValueChangeListener(listener); // } // // public BooleanConfig getBooleanConfig() // { // return this.toggleStatus; // } // // public HotkeyConfig getHotkeyConfig() // { // return this.toggleHotkey; // } // // public KeyBind getKeyBind() // { // return this.toggleHotkey.getKeyBind(); // } // // @Override // public ModInfo getModInfo() // { // return Reference.MOD_INFO; // } // // @Override // public String getName() // { // return this.toggleStatus.getName(); // } // // @Override // public String getDisplayName() // { // return this.toggleStatus.getDisplayName(); // } // // @Override // public Optional<String> getComment() // { // return this.toggleStatus.getComment(); // } // // @Override // public boolean isModified() // { // return this.toggleStatus.isModified() || this.toggleHotkey.isModified(); // } // // @Override // public void resetToDefault() // { // this.toggleStatus.resetToDefault(); // this.toggleHotkey.resetToDefault(); // } // } // Path: src/main/java/fi/dy/masa/minihud/gui/widget/RendererToggleConfigWidget.java import fi.dy.masa.malilib.gui.config.ConfigWidgetContext; import fi.dy.masa.malilib.gui.widget.list.entry.config.BaseHotkeyedBooleanConfigWidget; import fi.dy.masa.minihud.config.RendererToggle; package fi.dy.masa.minihud.gui.widget; public class RendererToggleConfigWidget extends BaseHotkeyedBooleanConfigWidget { public RendererToggleConfigWidget(int x, int y, int width, int height, int listIndex,
int originalListIndex, RendererToggle config, ConfigWidgetContext ctx)
maruohon/minihud
src/main/java/fi/dy/masa/minihud/LiteModMiniHud.java
// Path: src/main/java/fi/dy/masa/minihud/gui/MiniHudConfigPanel.java // public class MiniHudConfigPanel extends RedirectingConfigPanel // { // public MiniHudConfigPanel() // { // super(ConfigScreen::create); // } // }
import java.io.File; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.mumfrey.liteloader.Configurable; import com.mumfrey.liteloader.LiteMod; import com.mumfrey.liteloader.modconfig.ConfigPanel; import fi.dy.masa.malilib.registry.Registry; import fi.dy.masa.minihud.gui.MiniHudConfigPanel;
package fi.dy.masa.minihud; public class LiteModMiniHud implements LiteMod, Configurable { public static final Logger logger = LogManager.getLogger(Reference.MOD_ID); public LiteModMiniHud() { } @Override public String getName() { return Reference.MOD_NAME; } @Override public String getVersion() { return Reference.MOD_VERSION; } @Override public Class<? extends ConfigPanel> getConfigPanelClass() {
// Path: src/main/java/fi/dy/masa/minihud/gui/MiniHudConfigPanel.java // public class MiniHudConfigPanel extends RedirectingConfigPanel // { // public MiniHudConfigPanel() // { // super(ConfigScreen::create); // } // } // Path: src/main/java/fi/dy/masa/minihud/LiteModMiniHud.java import java.io.File; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.mumfrey.liteloader.Configurable; import com.mumfrey.liteloader.LiteMod; import com.mumfrey.liteloader.modconfig.ConfigPanel; import fi.dy.masa.malilib.registry.Registry; import fi.dy.masa.minihud.gui.MiniHudConfigPanel; package fi.dy.masa.minihud; public class LiteModMiniHud implements LiteMod, Configurable { public static final Logger logger = LogManager.getLogger(Reference.MOD_ID); public LiteModMiniHud() { } @Override public String getName() { return Reference.MOD_NAME; } @Override public String getVersion() { return Reference.MOD_VERSION; } @Override public Class<? extends ConfigPanel> getConfigPanelClass() {
return MiniHudConfigPanel.class;
maruohon/minihud
src/main/java/fi/dy/masa/minihud/data/StructureType.java
// Path: src/main/java/fi/dy/masa/minihud/config/StructureToggle.java // public enum StructureToggle implements ConfigInfo // { // OVERLAY_STRUCTURE_DESERT_PYRAMID ("desertPyramid", "#30FFFF00", "#30FFFF00"), // OVERLAY_STRUCTURE_END_CITY ("endCity", "#30EB07EB", "#30EB07EB"), // OVERLAY_STRUCTURE_IGLOO ("igloo", "#300FAFE4", "#300FAFE4"), // OVERLAY_STRUCTURE_JUNGLE_TEMPLE ("jungleTemple", "#3099FF00", "#3099FF00"), // OVERLAY_STRUCTURE_MANSION ("mansion", "#30FF6500", "#30FF6500"), // OVERLAY_STRUCTURE_NETHER_FORTRESS ("netherFortress", "#30FC381D", "#30FC381D"), // OVERLAY_STRUCTURE_OCEAN_MONUMENT ("oceanMonument", "#3029E6EF", "#3029E6EF"), // OVERLAY_STRUCTURE_STRONGHOLD ("stronghold", "#30009999", "#30009999"), // OVERLAY_STRUCTURE_VILLAGE ("village", "#3054CB4E", "#3054CB4E"), // OVERLAY_STRUCTURE_WITCH_HUT ("witchHut", "#30BE1DFC", "#300099FF"); // // public static final ImmutableList<StructureToggle> VALUES = ImmutableList.copyOf(values()); // public static final ImmutableList<ColorConfig> COLOR_CONFIGS = getColorConfigs(); // public static final ImmutableList<BooleanConfig> TOGGLE_CONFIGS = ImmutableList.copyOf(VALUES.stream().map(StructureToggle::getBooleanConfig).collect(Collectors.toList())); // public static final ImmutableList<HotkeyConfig> TOGGLE_HOTKEYS = ImmutableList.copyOf(VALUES.stream().map(StructureToggle::getHotkeyConfig).collect(Collectors.toList())); // // private final BooleanConfig toggleStatus; // private final HotkeyConfig toggleHotkey; // private final ColorConfig colorMain; // private final ColorConfig colorComponents; // // StructureToggle(String name, String colorMain, String colorComponents) // { // this.toggleStatus = new BooleanConfig(name, false); // this.toggleHotkey = new HotkeyConfig(name, ""); // this.colorMain = new ColorConfig(name + " Main", colorMain); // this.colorComponents = new ColorConfig(name + " Components", colorComponents); // // String nameLower = name.toLowerCase(Locale.ROOT); // String nameKey = "minihud.structure_toggle.name." + nameLower; // String commentKey = "minihud.structure_toggle.comment." + nameLower; // String colorMainKey = "minihud.structure_toggle.color.main." + nameLower; // String colorComponentsKey = "minihud.structure_toggle.color.components." + nameLower; // // this.toggleStatus.setNameTranslationKey(nameKey); // this.toggleStatus.setPrettyNameTranslationKey(nameKey); // this.toggleStatus.setCommentTranslationKey(commentKey); // // this.colorMain.setNameTranslationKey(colorMainKey); // this.colorMain.setPrettyNameTranslationKey(colorMainKey); // this.colorComponents.setNameTranslationKey(colorComponentsKey); // this.colorComponents.setPrettyNameTranslationKey(colorComponentsKey); // // this.toggleHotkey.setNameTranslationKey(nameKey); // this.toggleHotkey.setCommentTranslationKey(commentKey); // this.toggleHotkey.getKeyBind().setCallback(new ToggleBooleanWithMessageKeyCallback(this.toggleStatus)); // this.toggleStatus.addValueChangeListener(DataStorage.getInstance().getStructureStorage()::requestStructureDataUpdates); // } // // public boolean isEnabled() // { // return this.toggleStatus.getBooleanValue(); // } // // public BooleanConfig getBooleanConfig() // { // return this.toggleStatus; // } // // public HotkeyConfig getHotkeyConfig() // { // return this.toggleHotkey; // } // // public KeyBind getKeyBind() // { // return this.toggleHotkey.getKeyBind(); // } // // public ColorConfig getColorMain() // { // return this.colorMain; // } // // public ColorConfig getColorComponents() // { // return this.colorComponents; // } // // private static ImmutableList<ColorConfig> getColorConfigs() // { // ImmutableList.Builder<ColorConfig> builder = ImmutableList.builder(); // // for (StructureToggle toggle : VALUES) // { // builder.add(toggle.getColorMain()); // builder.add(toggle.getColorComponents()); // } // // return builder.build(); // } // // @Override // public ModInfo getModInfo() // { // return Reference.MOD_INFO; // } // // @Override // public String getName() // { // return this.toggleStatus.getName(); // } // // @Override // public String getDisplayName() // { // return this.toggleStatus.getDisplayName(); // } // // @Override // public Optional<String> getComment() // { // return this.toggleStatus.getComment(); // } // // @Override // public boolean isModified() // { // return this.toggleStatus.isModified() || // this.toggleHotkey.isModified() || // this.colorMain.isModified() || // this.colorComponents.isModified(); // } // // @Override // public void resetToDefault() // { // this.toggleStatus.resetToDefault(); // this.toggleHotkey.resetToDefault(); // this.colorMain.resetToDefault(); // this.colorComponents.resetToDefault(); // } // }
import javax.annotation.Nullable; import com.google.common.collect.ImmutableMap; import net.minecraft.world.DimensionType; import net.minecraft.world.WorldProvider; import net.minecraft.world.WorldProviderEnd; import fi.dy.masa.minihud.config.StructureToggle;
package fi.dy.masa.minihud.data; public enum StructureType {
// Path: src/main/java/fi/dy/masa/minihud/config/StructureToggle.java // public enum StructureToggle implements ConfigInfo // { // OVERLAY_STRUCTURE_DESERT_PYRAMID ("desertPyramid", "#30FFFF00", "#30FFFF00"), // OVERLAY_STRUCTURE_END_CITY ("endCity", "#30EB07EB", "#30EB07EB"), // OVERLAY_STRUCTURE_IGLOO ("igloo", "#300FAFE4", "#300FAFE4"), // OVERLAY_STRUCTURE_JUNGLE_TEMPLE ("jungleTemple", "#3099FF00", "#3099FF00"), // OVERLAY_STRUCTURE_MANSION ("mansion", "#30FF6500", "#30FF6500"), // OVERLAY_STRUCTURE_NETHER_FORTRESS ("netherFortress", "#30FC381D", "#30FC381D"), // OVERLAY_STRUCTURE_OCEAN_MONUMENT ("oceanMonument", "#3029E6EF", "#3029E6EF"), // OVERLAY_STRUCTURE_STRONGHOLD ("stronghold", "#30009999", "#30009999"), // OVERLAY_STRUCTURE_VILLAGE ("village", "#3054CB4E", "#3054CB4E"), // OVERLAY_STRUCTURE_WITCH_HUT ("witchHut", "#30BE1DFC", "#300099FF"); // // public static final ImmutableList<StructureToggle> VALUES = ImmutableList.copyOf(values()); // public static final ImmutableList<ColorConfig> COLOR_CONFIGS = getColorConfigs(); // public static final ImmutableList<BooleanConfig> TOGGLE_CONFIGS = ImmutableList.copyOf(VALUES.stream().map(StructureToggle::getBooleanConfig).collect(Collectors.toList())); // public static final ImmutableList<HotkeyConfig> TOGGLE_HOTKEYS = ImmutableList.copyOf(VALUES.stream().map(StructureToggle::getHotkeyConfig).collect(Collectors.toList())); // // private final BooleanConfig toggleStatus; // private final HotkeyConfig toggleHotkey; // private final ColorConfig colorMain; // private final ColorConfig colorComponents; // // StructureToggle(String name, String colorMain, String colorComponents) // { // this.toggleStatus = new BooleanConfig(name, false); // this.toggleHotkey = new HotkeyConfig(name, ""); // this.colorMain = new ColorConfig(name + " Main", colorMain); // this.colorComponents = new ColorConfig(name + " Components", colorComponents); // // String nameLower = name.toLowerCase(Locale.ROOT); // String nameKey = "minihud.structure_toggle.name." + nameLower; // String commentKey = "minihud.structure_toggle.comment." + nameLower; // String colorMainKey = "minihud.structure_toggle.color.main." + nameLower; // String colorComponentsKey = "minihud.structure_toggle.color.components." + nameLower; // // this.toggleStatus.setNameTranslationKey(nameKey); // this.toggleStatus.setPrettyNameTranslationKey(nameKey); // this.toggleStatus.setCommentTranslationKey(commentKey); // // this.colorMain.setNameTranslationKey(colorMainKey); // this.colorMain.setPrettyNameTranslationKey(colorMainKey); // this.colorComponents.setNameTranslationKey(colorComponentsKey); // this.colorComponents.setPrettyNameTranslationKey(colorComponentsKey); // // this.toggleHotkey.setNameTranslationKey(nameKey); // this.toggleHotkey.setCommentTranslationKey(commentKey); // this.toggleHotkey.getKeyBind().setCallback(new ToggleBooleanWithMessageKeyCallback(this.toggleStatus)); // this.toggleStatus.addValueChangeListener(DataStorage.getInstance().getStructureStorage()::requestStructureDataUpdates); // } // // public boolean isEnabled() // { // return this.toggleStatus.getBooleanValue(); // } // // public BooleanConfig getBooleanConfig() // { // return this.toggleStatus; // } // // public HotkeyConfig getHotkeyConfig() // { // return this.toggleHotkey; // } // // public KeyBind getKeyBind() // { // return this.toggleHotkey.getKeyBind(); // } // // public ColorConfig getColorMain() // { // return this.colorMain; // } // // public ColorConfig getColorComponents() // { // return this.colorComponents; // } // // private static ImmutableList<ColorConfig> getColorConfigs() // { // ImmutableList.Builder<ColorConfig> builder = ImmutableList.builder(); // // for (StructureToggle toggle : VALUES) // { // builder.add(toggle.getColorMain()); // builder.add(toggle.getColorComponents()); // } // // return builder.build(); // } // // @Override // public ModInfo getModInfo() // { // return Reference.MOD_INFO; // } // // @Override // public String getName() // { // return this.toggleStatus.getName(); // } // // @Override // public String getDisplayName() // { // return this.toggleStatus.getDisplayName(); // } // // @Override // public Optional<String> getComment() // { // return this.toggleStatus.getComment(); // } // // @Override // public boolean isModified() // { // return this.toggleStatus.isModified() || // this.toggleHotkey.isModified() || // this.colorMain.isModified() || // this.colorComponents.isModified(); // } // // @Override // public void resetToDefault() // { // this.toggleStatus.resetToDefault(); // this.toggleHotkey.resetToDefault(); // this.colorMain.resetToDefault(); // this.colorComponents.resetToDefault(); // } // } // Path: src/main/java/fi/dy/masa/minihud/data/StructureType.java import javax.annotation.Nullable; import com.google.common.collect.ImmutableMap; import net.minecraft.world.DimensionType; import net.minecraft.world.WorldProvider; import net.minecraft.world.WorldProviderEnd; import fi.dy.masa.minihud.config.StructureToggle; package fi.dy.masa.minihud.data; public enum StructureType {
DESERT_PYRAMID (DimensionType.OVERWORLD, "Temple", "TeDP", StructureToggle.OVERLAY_STRUCTURE_DESERT_PYRAMID),
maruohon/minihud
src/main/java/fi/dy/masa/minihud/gui/widget/info/StructureRendererConfigStatusWidget.java
// Path: src/main/java/fi/dy/masa/minihud/config/StructureToggle.java // public enum StructureToggle implements ConfigInfo // { // OVERLAY_STRUCTURE_DESERT_PYRAMID ("desertPyramid", "#30FFFF00", "#30FFFF00"), // OVERLAY_STRUCTURE_END_CITY ("endCity", "#30EB07EB", "#30EB07EB"), // OVERLAY_STRUCTURE_IGLOO ("igloo", "#300FAFE4", "#300FAFE4"), // OVERLAY_STRUCTURE_JUNGLE_TEMPLE ("jungleTemple", "#3099FF00", "#3099FF00"), // OVERLAY_STRUCTURE_MANSION ("mansion", "#30FF6500", "#30FF6500"), // OVERLAY_STRUCTURE_NETHER_FORTRESS ("netherFortress", "#30FC381D", "#30FC381D"), // OVERLAY_STRUCTURE_OCEAN_MONUMENT ("oceanMonument", "#3029E6EF", "#3029E6EF"), // OVERLAY_STRUCTURE_STRONGHOLD ("stronghold", "#30009999", "#30009999"), // OVERLAY_STRUCTURE_VILLAGE ("village", "#3054CB4E", "#3054CB4E"), // OVERLAY_STRUCTURE_WITCH_HUT ("witchHut", "#30BE1DFC", "#300099FF"); // // public static final ImmutableList<StructureToggle> VALUES = ImmutableList.copyOf(values()); // public static final ImmutableList<ColorConfig> COLOR_CONFIGS = getColorConfigs(); // public static final ImmutableList<BooleanConfig> TOGGLE_CONFIGS = ImmutableList.copyOf(VALUES.stream().map(StructureToggle::getBooleanConfig).collect(Collectors.toList())); // public static final ImmutableList<HotkeyConfig> TOGGLE_HOTKEYS = ImmutableList.copyOf(VALUES.stream().map(StructureToggle::getHotkeyConfig).collect(Collectors.toList())); // // private final BooleanConfig toggleStatus; // private final HotkeyConfig toggleHotkey; // private final ColorConfig colorMain; // private final ColorConfig colorComponents; // // StructureToggle(String name, String colorMain, String colorComponents) // { // this.toggleStatus = new BooleanConfig(name, false); // this.toggleHotkey = new HotkeyConfig(name, ""); // this.colorMain = new ColorConfig(name + " Main", colorMain); // this.colorComponents = new ColorConfig(name + " Components", colorComponents); // // String nameLower = name.toLowerCase(Locale.ROOT); // String nameKey = "minihud.structure_toggle.name." + nameLower; // String commentKey = "minihud.structure_toggle.comment." + nameLower; // String colorMainKey = "minihud.structure_toggle.color.main." + nameLower; // String colorComponentsKey = "minihud.structure_toggle.color.components." + nameLower; // // this.toggleStatus.setNameTranslationKey(nameKey); // this.toggleStatus.setPrettyNameTranslationKey(nameKey); // this.toggleStatus.setCommentTranslationKey(commentKey); // // this.colorMain.setNameTranslationKey(colorMainKey); // this.colorMain.setPrettyNameTranslationKey(colorMainKey); // this.colorComponents.setNameTranslationKey(colorComponentsKey); // this.colorComponents.setPrettyNameTranslationKey(colorComponentsKey); // // this.toggleHotkey.setNameTranslationKey(nameKey); // this.toggleHotkey.setCommentTranslationKey(commentKey); // this.toggleHotkey.getKeyBind().setCallback(new ToggleBooleanWithMessageKeyCallback(this.toggleStatus)); // this.toggleStatus.addValueChangeListener(DataStorage.getInstance().getStructureStorage()::requestStructureDataUpdates); // } // // public boolean isEnabled() // { // return this.toggleStatus.getBooleanValue(); // } // // public BooleanConfig getBooleanConfig() // { // return this.toggleStatus; // } // // public HotkeyConfig getHotkeyConfig() // { // return this.toggleHotkey; // } // // public KeyBind getKeyBind() // { // return this.toggleHotkey.getKeyBind(); // } // // public ColorConfig getColorMain() // { // return this.colorMain; // } // // public ColorConfig getColorComponents() // { // return this.colorComponents; // } // // private static ImmutableList<ColorConfig> getColorConfigs() // { // ImmutableList.Builder<ColorConfig> builder = ImmutableList.builder(); // // for (StructureToggle toggle : VALUES) // { // builder.add(toggle.getColorMain()); // builder.add(toggle.getColorComponents()); // } // // return builder.build(); // } // // @Override // public ModInfo getModInfo() // { // return Reference.MOD_INFO; // } // // @Override // public String getName() // { // return this.toggleStatus.getName(); // } // // @Override // public String getDisplayName() // { // return this.toggleStatus.getDisplayName(); // } // // @Override // public Optional<String> getComment() // { // return this.toggleStatus.getComment(); // } // // @Override // public boolean isModified() // { // return this.toggleStatus.isModified() || // this.toggleHotkey.isModified() || // this.colorMain.isModified() || // this.colorComponents.isModified(); // } // // @Override // public void resetToDefault() // { // this.toggleStatus.resetToDefault(); // this.toggleHotkey.resetToDefault(); // this.colorMain.resetToDefault(); // this.colorComponents.resetToDefault(); // } // }
import fi.dy.masa.malilib.overlay.widget.sub.HotkeyedBooleanConfigStatusWidget; import fi.dy.masa.malilib.util.data.ConfigOnTab; import fi.dy.masa.minihud.config.StructureToggle;
package fi.dy.masa.minihud.gui.widget.info; public class StructureRendererConfigStatusWidget extends HotkeyedBooleanConfigStatusWidget {
// Path: src/main/java/fi/dy/masa/minihud/config/StructureToggle.java // public enum StructureToggle implements ConfigInfo // { // OVERLAY_STRUCTURE_DESERT_PYRAMID ("desertPyramid", "#30FFFF00", "#30FFFF00"), // OVERLAY_STRUCTURE_END_CITY ("endCity", "#30EB07EB", "#30EB07EB"), // OVERLAY_STRUCTURE_IGLOO ("igloo", "#300FAFE4", "#300FAFE4"), // OVERLAY_STRUCTURE_JUNGLE_TEMPLE ("jungleTemple", "#3099FF00", "#3099FF00"), // OVERLAY_STRUCTURE_MANSION ("mansion", "#30FF6500", "#30FF6500"), // OVERLAY_STRUCTURE_NETHER_FORTRESS ("netherFortress", "#30FC381D", "#30FC381D"), // OVERLAY_STRUCTURE_OCEAN_MONUMENT ("oceanMonument", "#3029E6EF", "#3029E6EF"), // OVERLAY_STRUCTURE_STRONGHOLD ("stronghold", "#30009999", "#30009999"), // OVERLAY_STRUCTURE_VILLAGE ("village", "#3054CB4E", "#3054CB4E"), // OVERLAY_STRUCTURE_WITCH_HUT ("witchHut", "#30BE1DFC", "#300099FF"); // // public static final ImmutableList<StructureToggle> VALUES = ImmutableList.copyOf(values()); // public static final ImmutableList<ColorConfig> COLOR_CONFIGS = getColorConfigs(); // public static final ImmutableList<BooleanConfig> TOGGLE_CONFIGS = ImmutableList.copyOf(VALUES.stream().map(StructureToggle::getBooleanConfig).collect(Collectors.toList())); // public static final ImmutableList<HotkeyConfig> TOGGLE_HOTKEYS = ImmutableList.copyOf(VALUES.stream().map(StructureToggle::getHotkeyConfig).collect(Collectors.toList())); // // private final BooleanConfig toggleStatus; // private final HotkeyConfig toggleHotkey; // private final ColorConfig colorMain; // private final ColorConfig colorComponents; // // StructureToggle(String name, String colorMain, String colorComponents) // { // this.toggleStatus = new BooleanConfig(name, false); // this.toggleHotkey = new HotkeyConfig(name, ""); // this.colorMain = new ColorConfig(name + " Main", colorMain); // this.colorComponents = new ColorConfig(name + " Components", colorComponents); // // String nameLower = name.toLowerCase(Locale.ROOT); // String nameKey = "minihud.structure_toggle.name." + nameLower; // String commentKey = "minihud.structure_toggle.comment." + nameLower; // String colorMainKey = "minihud.structure_toggle.color.main." + nameLower; // String colorComponentsKey = "minihud.structure_toggle.color.components." + nameLower; // // this.toggleStatus.setNameTranslationKey(nameKey); // this.toggleStatus.setPrettyNameTranslationKey(nameKey); // this.toggleStatus.setCommentTranslationKey(commentKey); // // this.colorMain.setNameTranslationKey(colorMainKey); // this.colorMain.setPrettyNameTranslationKey(colorMainKey); // this.colorComponents.setNameTranslationKey(colorComponentsKey); // this.colorComponents.setPrettyNameTranslationKey(colorComponentsKey); // // this.toggleHotkey.setNameTranslationKey(nameKey); // this.toggleHotkey.setCommentTranslationKey(commentKey); // this.toggleHotkey.getKeyBind().setCallback(new ToggleBooleanWithMessageKeyCallback(this.toggleStatus)); // this.toggleStatus.addValueChangeListener(DataStorage.getInstance().getStructureStorage()::requestStructureDataUpdates); // } // // public boolean isEnabled() // { // return this.toggleStatus.getBooleanValue(); // } // // public BooleanConfig getBooleanConfig() // { // return this.toggleStatus; // } // // public HotkeyConfig getHotkeyConfig() // { // return this.toggleHotkey; // } // // public KeyBind getKeyBind() // { // return this.toggleHotkey.getKeyBind(); // } // // public ColorConfig getColorMain() // { // return this.colorMain; // } // // public ColorConfig getColorComponents() // { // return this.colorComponents; // } // // private static ImmutableList<ColorConfig> getColorConfigs() // { // ImmutableList.Builder<ColorConfig> builder = ImmutableList.builder(); // // for (StructureToggle toggle : VALUES) // { // builder.add(toggle.getColorMain()); // builder.add(toggle.getColorComponents()); // } // // return builder.build(); // } // // @Override // public ModInfo getModInfo() // { // return Reference.MOD_INFO; // } // // @Override // public String getName() // { // return this.toggleStatus.getName(); // } // // @Override // public String getDisplayName() // { // return this.toggleStatus.getDisplayName(); // } // // @Override // public Optional<String> getComment() // { // return this.toggleStatus.getComment(); // } // // @Override // public boolean isModified() // { // return this.toggleStatus.isModified() || // this.toggleHotkey.isModified() || // this.colorMain.isModified() || // this.colorComponents.isModified(); // } // // @Override // public void resetToDefault() // { // this.toggleStatus.resetToDefault(); // this.toggleHotkey.resetToDefault(); // this.colorMain.resetToDefault(); // this.colorComponents.resetToDefault(); // } // } // Path: src/main/java/fi/dy/masa/minihud/gui/widget/info/StructureRendererConfigStatusWidget.java import fi.dy.masa.malilib.overlay.widget.sub.HotkeyedBooleanConfigStatusWidget; import fi.dy.masa.malilib.util.data.ConfigOnTab; import fi.dy.masa.minihud.config.StructureToggle; package fi.dy.masa.minihud.gui.widget.info; public class StructureRendererConfigStatusWidget extends HotkeyedBooleanConfigStatusWidget {
public StructureRendererConfigStatusWidget(StructureToggle config, ConfigOnTab configOnTab)
maruohon/minihud
src/main/java/fi/dy/masa/minihud/network/ServuxInfoSubRegistrationPacketHandler.java
// Path: src/main/java/fi/dy/masa/minihud/MiniHUD.java // public class MiniHUD // { // public static final Logger LOGGER = LogManager.getLogger(Reference.MOD_ID); // // public static void logInfo(String msg, Object... args) // { // if (Configs.Generic.DEBUG_MESSAGES.getBooleanValue()) // { // LOGGER.info(msg, args); // } // } // }
import java.util.List; import com.google.common.collect.ImmutableList; import net.minecraft.network.PacketBuffer; import net.minecraft.util.ResourceLocation; import fi.dy.masa.malilib.network.PluginChannelHandler; import fi.dy.masa.malilib.overlay.message.MessageDispatcher; import fi.dy.masa.minihud.MiniHUD;
package fi.dy.masa.minihud.network; public class ServuxInfoSubRegistrationPacketHandler implements PluginChannelHandler { public static final ServuxInfoSubRegistrationPacketHandler INSTANCE = new ServuxInfoSubRegistrationPacketHandler(); public static final ResourceLocation REG_CHANNEL = new ResourceLocation("servux:info_reg"); protected static final List<ResourceLocation> CHANNELS = ImmutableList.of(REG_CHANNEL); protected static final int PACKET_S2C_METADATA = 1; @Override public List<ResourceLocation> getChannels() { return CHANNELS; } @Override public void onPacketReceived(PacketBuffer buf) { int type = buf.readVarInt(); System.out.printf("REG packet received, type: %d\n", type); if (type == PACKET_S2C_METADATA) { try { ServuxInfoSubDataPacketHandler.INSTANCE.receiveMetadata(buf.readCompoundTag()); } catch (Exception e) { MessageDispatcher.error("minihud.message.error.info_sub.failed_receive_metadata");
// Path: src/main/java/fi/dy/masa/minihud/MiniHUD.java // public class MiniHUD // { // public static final Logger LOGGER = LogManager.getLogger(Reference.MOD_ID); // // public static void logInfo(String msg, Object... args) // { // if (Configs.Generic.DEBUG_MESSAGES.getBooleanValue()) // { // LOGGER.info(msg, args); // } // } // } // Path: src/main/java/fi/dy/masa/minihud/network/ServuxInfoSubRegistrationPacketHandler.java import java.util.List; import com.google.common.collect.ImmutableList; import net.minecraft.network.PacketBuffer; import net.minecraft.util.ResourceLocation; import fi.dy.masa.malilib.network.PluginChannelHandler; import fi.dy.masa.malilib.overlay.message.MessageDispatcher; import fi.dy.masa.minihud.MiniHUD; package fi.dy.masa.minihud.network; public class ServuxInfoSubRegistrationPacketHandler implements PluginChannelHandler { public static final ServuxInfoSubRegistrationPacketHandler INSTANCE = new ServuxInfoSubRegistrationPacketHandler(); public static final ResourceLocation REG_CHANNEL = new ResourceLocation("servux:info_reg"); protected static final List<ResourceLocation> CHANNELS = ImmutableList.of(REG_CHANNEL); protected static final int PACKET_S2C_METADATA = 1; @Override public List<ResourceLocation> getChannels() { return CHANNELS; } @Override public void onPacketReceived(PacketBuffer buf) { int type = buf.readVarInt(); System.out.printf("REG packet received, type: %d\n", type); if (type == PACKET_S2C_METADATA) { try { ServuxInfoSubDataPacketHandler.INSTANCE.receiveMetadata(buf.readCompoundTag()); } catch (Exception e) { MessageDispatcher.error("minihud.message.error.info_sub.failed_receive_metadata");
MiniHUD.LOGGER.warn("Failed to receive info sub metadata from the server");
maruohon/minihud
src/main/java/fi/dy/masa/minihud/renderer/shapes/ShapeCircleBase.java
// Path: src/main/java/fi/dy/masa/minihud/util/ShapeRenderType.java // public class ShapeRenderType extends BaseOptionListConfigValue // { // public static final ShapeRenderType FULL_BLOCK = new ShapeRenderType("full_block", "minihud.name.shape_render_type.full_block"); // public static final ShapeRenderType INNER_EDGE = new ShapeRenderType("inner_edge", "minihud.name.shape_render_type.inner_edge"); // public static final ShapeRenderType OUTER_EDGE = new ShapeRenderType("outer_edge", "minihud.name.shape_render_type.outer_edge"); // // public static final ImmutableList<ShapeRenderType> VALUES = ImmutableList.of(FULL_BLOCK, INNER_EDGE, OUTER_EDGE); // // private ShapeRenderType(String name, String translationKey) // { // super(name, translationKey); // } // }
import java.text.DecimalFormat; import java.util.HashSet; import java.util.List; import javax.annotation.Nullable; import org.lwjgl.opengl.GL11; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import fi.dy.masa.malilib.config.value.BaseOptionListConfigValue; import fi.dy.masa.malilib.config.value.BlockSnap; import fi.dy.masa.malilib.render.ShapeRenderUtils; import fi.dy.masa.malilib.util.EntityUtils; import fi.dy.masa.malilib.util.JsonUtils; import fi.dy.masa.malilib.util.StringUtils; import fi.dy.masa.malilib.util.data.Color4f; import fi.dy.masa.malilib.util.position.LayerRange; import fi.dy.masa.minihud.util.ShapeRenderType;
Vec3d center = JsonUtils.vec3dFromJson(obj, "center"); if (center != null) { this.setCenter(center); } } @Override public List<String> getWidgetHoverLines() { List<String> lines = super.getWidgetHoverLines(); DecimalFormat fmt = new DecimalFormat("#.##"); Vec3d c = this.center; lines.add(StringUtils.translate("minihud.hover.shape.radius", this.getRadius())); lines.add(StringUtils.translate("minihud.hover.shape.center", fmt.format(c.x), fmt.format(c.y), fmt.format(c.z))); lines.add(StringUtils.translate("minihud.hover.shape.block_snap", this.snap.getDisplayName())); if (this.snap != BlockSnap.NONE) { c = this.effectiveCenter; lines.add(StringUtils.translate("minihud.hover.shape.effective_center", fmt.format(c.x), fmt.format(c.y), fmt.format(c.z))); } return lines; } protected void renderPositions(HashSet<BlockPos> positions, EnumFacing[] sides, EnumFacing mainAxis, Color4f color, Vec3d cameraPos) {
// Path: src/main/java/fi/dy/masa/minihud/util/ShapeRenderType.java // public class ShapeRenderType extends BaseOptionListConfigValue // { // public static final ShapeRenderType FULL_BLOCK = new ShapeRenderType("full_block", "minihud.name.shape_render_type.full_block"); // public static final ShapeRenderType INNER_EDGE = new ShapeRenderType("inner_edge", "minihud.name.shape_render_type.inner_edge"); // public static final ShapeRenderType OUTER_EDGE = new ShapeRenderType("outer_edge", "minihud.name.shape_render_type.outer_edge"); // // public static final ImmutableList<ShapeRenderType> VALUES = ImmutableList.of(FULL_BLOCK, INNER_EDGE, OUTER_EDGE); // // private ShapeRenderType(String name, String translationKey) // { // super(name, translationKey); // } // } // Path: src/main/java/fi/dy/masa/minihud/renderer/shapes/ShapeCircleBase.java import java.text.DecimalFormat; import java.util.HashSet; import java.util.List; import javax.annotation.Nullable; import org.lwjgl.opengl.GL11; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import fi.dy.masa.malilib.config.value.BaseOptionListConfigValue; import fi.dy.masa.malilib.config.value.BlockSnap; import fi.dy.masa.malilib.render.ShapeRenderUtils; import fi.dy.masa.malilib.util.EntityUtils; import fi.dy.masa.malilib.util.JsonUtils; import fi.dy.masa.malilib.util.StringUtils; import fi.dy.masa.malilib.util.data.Color4f; import fi.dy.masa.malilib.util.position.LayerRange; import fi.dy.masa.minihud.util.ShapeRenderType; Vec3d center = JsonUtils.vec3dFromJson(obj, "center"); if (center != null) { this.setCenter(center); } } @Override public List<String> getWidgetHoverLines() { List<String> lines = super.getWidgetHoverLines(); DecimalFormat fmt = new DecimalFormat("#.##"); Vec3d c = this.center; lines.add(StringUtils.translate("minihud.hover.shape.radius", this.getRadius())); lines.add(StringUtils.translate("minihud.hover.shape.center", fmt.format(c.x), fmt.format(c.y), fmt.format(c.z))); lines.add(StringUtils.translate("minihud.hover.shape.block_snap", this.snap.getDisplayName())); if (this.snap != BlockSnap.NONE) { c = this.effectiveCenter; lines.add(StringUtils.translate("minihud.hover.shape.effective_center", fmt.format(c.x), fmt.format(c.y), fmt.format(c.z))); } return lines; } protected void renderPositions(HashSet<BlockPos> positions, EnumFacing[] sides, EnumFacing mainAxis, Color4f color, Vec3d cameraPos) {
boolean full = this.renderType == ShapeRenderType.FULL_BLOCK;
maruohon/minihud
src/main/java/fi/dy/masa/minihud/data/StructureData.java
// Path: src/main/java/fi/dy/masa/minihud/MiniHUD.java // public class MiniHUD // { // public static final Logger LOGGER = LogManager.getLogger(Reference.MOD_ID); // // public static void logInfo(String msg, Object... args) // { // if (Configs.Generic.DEBUG_MESSAGES.getBooleanValue()) // { // LOGGER.info(msg, args); // } // } // }
import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.world.gen.structure.StructureComponent; import net.minecraft.world.gen.structure.StructureStart; import fi.dy.masa.malilib.util.data.Constants; import fi.dy.masa.malilib.util.position.IntBoundingBox; import fi.dy.masa.minihud.MiniHUD;
CARPET_BOX_READER.type = null; CARPET_BOX_READER.componentsBuilder = ImmutableList.builder(); } else { CARPET_BOX_READER.componentBoxes++; if (CARPET_BOX_READER.readTypeFromNextBox) { CARPET_BOX_READER.type = getTypeFromCarpetId(id); CARPET_BOX_READER.readTypeFromNextBox = false; } if (CARPET_BOX_READER.componentsBuilder != null) { CARPET_BOX_READER.componentsBuilder.add(bb); } } if (CARPET_BOX_READER.seenBoxes >= CARPET_BOX_READER.expectedBoxes) { if (CARPET_BOX_READER.type != null && CARPET_BOX_READER.bbMain != null && CARPET_BOX_READER.componentBoxes > 0) { map.put(CARPET_BOX_READER.type, new StructureData(CARPET_BOX_READER.bbMain, CARPET_BOX_READER.componentsBuilder.build())); } resetCarpetBoxReader();
// Path: src/main/java/fi/dy/masa/minihud/MiniHUD.java // public class MiniHUD // { // public static final Logger LOGGER = LogManager.getLogger(Reference.MOD_ID); // // public static void logInfo(String msg, Object... args) // { // if (Configs.Generic.DEBUG_MESSAGES.getBooleanValue()) // { // LOGGER.info(msg, args); // } // } // } // Path: src/main/java/fi/dy/masa/minihud/data/StructureData.java import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.world.gen.structure.StructureComponent; import net.minecraft.world.gen.structure.StructureStart; import fi.dy.masa.malilib.util.data.Constants; import fi.dy.masa.malilib.util.position.IntBoundingBox; import fi.dy.masa.minihud.MiniHUD; CARPET_BOX_READER.type = null; CARPET_BOX_READER.componentsBuilder = ImmutableList.builder(); } else { CARPET_BOX_READER.componentBoxes++; if (CARPET_BOX_READER.readTypeFromNextBox) { CARPET_BOX_READER.type = getTypeFromCarpetId(id); CARPET_BOX_READER.readTypeFromNextBox = false; } if (CARPET_BOX_READER.componentsBuilder != null) { CARPET_BOX_READER.componentsBuilder.add(bb); } } if (CARPET_BOX_READER.seenBoxes >= CARPET_BOX_READER.expectedBoxes) { if (CARPET_BOX_READER.type != null && CARPET_BOX_READER.bbMain != null && CARPET_BOX_READER.componentBoxes > 0) { map.put(CARPET_BOX_READER.type, new StructureData(CARPET_BOX_READER.bbMain, CARPET_BOX_READER.componentsBuilder.build())); } resetCarpetBoxReader();
MiniHUD.logInfo("Structure data updated from Carpet server (split data), structures: {}", map.size());
unidal/cat2
cat-consumer/src/main/java/com/dianping/cat/consumer/storage/StorageDelegate.java
// Path: cat-core/src/main/java/com/dianping/cat/config/server/ServerFilterConfigManager.java // public class ServerFilterConfigManager implements Initializable { // // @Inject // protected ConfigDao m_configDao; // // @Inject // protected ContentFetcher m_fetcher; // // private volatile ServerFilterConfig m_config; // // private int m_configId; // // private long m_modifyTime; // // private static final String CONFIG_NAME = "serverFilter"; // // public boolean discardTransaction(String type, String name) { // if ("Cache.web".equals(type) || "ABTest".equals(type)) { // return true; // } // if (m_config.getTransactionTypes().contains(type) && m_config.getTransactionNames().contains(name)) { // return true; // } // return false; // } // // public ServerFilterConfig getConfig() { // return m_config; // } // // public Map<String, CrashLogDomain> getCrashLogDomains() { // return m_config.getCrashLogDomains(); // } // // public Set<String> getUnusedDomains() { // Set<String> unusedDomains = new HashSet<String>(); // // unusedDomains.addAll(m_config.getCrashLogDomains().keySet()); // unusedDomains.addAll(m_config.getDomains()); // return unusedDomains; // } // // @Override // public void initialize() throws InitializationException { // try { // Config config = m_configDao.findByName(CONFIG_NAME, ConfigEntity.READSET_FULL); // String content = config.getContent(); // // m_configId = config.getId(); // m_modifyTime = config.getModifyDate().getTime(); // m_config = DefaultSaxParser.parse(content); // } catch (DalNotFoundException e) { // try { // String content = m_fetcher.getConfigContent(CONFIG_NAME); // Config config = m_configDao.createLocal(); // // config.setName(CONFIG_NAME); // config.setContent(content); // m_configDao.insert(config); // m_configId = config.getId(); // m_config = DefaultSaxParser.parse(content); // } catch (Exception ex) { // Cat.logError(ex); // } // } catch (Exception e) { // Cat.logError(e); // } // if (m_config == null) { // m_config = new ServerFilterConfig(); // } // Threads.forGroup(CatConstant.CAT).start(new ConfigReloadTask()); // } // // public boolean insert(String xml) { // try { // m_config = DefaultSaxParser.parse(xml); // // return storeConfig(); // } catch (Exception e) { // Cat.logError(e); // return false; // } // } // // public boolean isCrashLog(String domain) { // return m_config.getCrashLogDomains().containsKey(domain); // } // // public boolean storeConfig() { // try { // Config config = m_configDao.createLocal(); // // config.setId(m_configId); // config.setKeyId(m_configId); // config.setName(CONFIG_NAME); // config.setContent(m_config.toString()); // m_configDao.updateByPK(config, ConfigEntity.UPDATESET_FULL); // } catch (Exception e) { // Cat.logError(e); // return false; // } // return true; // } // // public boolean validateDomain(String domain) { // return !m_config.getDomains().contains(domain) && !m_config.getCrashLogDomains().containsKey(domain); // } // // public void refreshConfig() throws DalException, SAXException, IOException { // Config config = m_configDao.findByName(CONFIG_NAME, ConfigEntity.READSET_FULL); // long modifyTime = config.getModifyDate().getTime(); // // synchronized (this) { // if (modifyTime > m_modifyTime) { // String content = config.getContent(); // ServerFilterConfig serverConfig = DefaultSaxParser.parse(content); // // m_config = serverConfig; // m_modifyTime = modifyTime; // } // } // } // // public class ConfigReloadTask implements Task { // // @Override // public String getName() { // return getClass().getSimpleName(); // } // // @Override // public void run() { // boolean active = true; // // while (active) { // try { // refreshConfig(); // } catch (Exception e) { // Cat.logError(e); // } // try { // Thread.sleep(TimeHelper.ONE_MINUTE); // } catch (InterruptedException e) { // active = false; // } // } // } // // @Override // public void shutdown() { // } // } // // public boolean discardEvent(String type, String name) { // return false; // } // // }
import java.util.Date; import java.util.Map; import org.unidal.lookup.annotation.Inject; import com.dianping.cat.config.server.ServerFilterConfigManager; import com.dianping.cat.consumer.storage.model.entity.StorageReport; import com.dianping.cat.consumer.storage.model.transform.DefaultNativeBuilder; import com.dianping.cat.consumer.storage.model.transform.DefaultNativeParser; import com.dianping.cat.consumer.storage.model.transform.DefaultSaxParser; import com.dianping.cat.report.ReportDelegate; import com.dianping.cat.task.TaskManager; import com.dianping.cat.task.TaskManager.TaskProlicy;
package com.dianping.cat.consumer.storage; public class StorageDelegate implements ReportDelegate<StorageReport> { @Inject private TaskManager m_taskManager; @Inject
// Path: cat-core/src/main/java/com/dianping/cat/config/server/ServerFilterConfigManager.java // public class ServerFilterConfigManager implements Initializable { // // @Inject // protected ConfigDao m_configDao; // // @Inject // protected ContentFetcher m_fetcher; // // private volatile ServerFilterConfig m_config; // // private int m_configId; // // private long m_modifyTime; // // private static final String CONFIG_NAME = "serverFilter"; // // public boolean discardTransaction(String type, String name) { // if ("Cache.web".equals(type) || "ABTest".equals(type)) { // return true; // } // if (m_config.getTransactionTypes().contains(type) && m_config.getTransactionNames().contains(name)) { // return true; // } // return false; // } // // public ServerFilterConfig getConfig() { // return m_config; // } // // public Map<String, CrashLogDomain> getCrashLogDomains() { // return m_config.getCrashLogDomains(); // } // // public Set<String> getUnusedDomains() { // Set<String> unusedDomains = new HashSet<String>(); // // unusedDomains.addAll(m_config.getCrashLogDomains().keySet()); // unusedDomains.addAll(m_config.getDomains()); // return unusedDomains; // } // // @Override // public void initialize() throws InitializationException { // try { // Config config = m_configDao.findByName(CONFIG_NAME, ConfigEntity.READSET_FULL); // String content = config.getContent(); // // m_configId = config.getId(); // m_modifyTime = config.getModifyDate().getTime(); // m_config = DefaultSaxParser.parse(content); // } catch (DalNotFoundException e) { // try { // String content = m_fetcher.getConfigContent(CONFIG_NAME); // Config config = m_configDao.createLocal(); // // config.setName(CONFIG_NAME); // config.setContent(content); // m_configDao.insert(config); // m_configId = config.getId(); // m_config = DefaultSaxParser.parse(content); // } catch (Exception ex) { // Cat.logError(ex); // } // } catch (Exception e) { // Cat.logError(e); // } // if (m_config == null) { // m_config = new ServerFilterConfig(); // } // Threads.forGroup(CatConstant.CAT).start(new ConfigReloadTask()); // } // // public boolean insert(String xml) { // try { // m_config = DefaultSaxParser.parse(xml); // // return storeConfig(); // } catch (Exception e) { // Cat.logError(e); // return false; // } // } // // public boolean isCrashLog(String domain) { // return m_config.getCrashLogDomains().containsKey(domain); // } // // public boolean storeConfig() { // try { // Config config = m_configDao.createLocal(); // // config.setId(m_configId); // config.setKeyId(m_configId); // config.setName(CONFIG_NAME); // config.setContent(m_config.toString()); // m_configDao.updateByPK(config, ConfigEntity.UPDATESET_FULL); // } catch (Exception e) { // Cat.logError(e); // return false; // } // return true; // } // // public boolean validateDomain(String domain) { // return !m_config.getDomains().contains(domain) && !m_config.getCrashLogDomains().containsKey(domain); // } // // public void refreshConfig() throws DalException, SAXException, IOException { // Config config = m_configDao.findByName(CONFIG_NAME, ConfigEntity.READSET_FULL); // long modifyTime = config.getModifyDate().getTime(); // // synchronized (this) { // if (modifyTime > m_modifyTime) { // String content = config.getContent(); // ServerFilterConfig serverConfig = DefaultSaxParser.parse(content); // // m_config = serverConfig; // m_modifyTime = modifyTime; // } // } // } // // public class ConfigReloadTask implements Task { // // @Override // public String getName() { // return getClass().getSimpleName(); // } // // @Override // public void run() { // boolean active = true; // // while (active) { // try { // refreshConfig(); // } catch (Exception e) { // Cat.logError(e); // } // try { // Thread.sleep(TimeHelper.ONE_MINUTE); // } catch (InterruptedException e) { // active = false; // } // } // } // // @Override // public void shutdown() { // } // } // // public boolean discardEvent(String type, String name) { // return false; // } // // } // Path: cat-consumer/src/main/java/com/dianping/cat/consumer/storage/StorageDelegate.java import java.util.Date; import java.util.Map; import org.unidal.lookup.annotation.Inject; import com.dianping.cat.config.server.ServerFilterConfigManager; import com.dianping.cat.consumer.storage.model.entity.StorageReport; import com.dianping.cat.consumer.storage.model.transform.DefaultNativeBuilder; import com.dianping.cat.consumer.storage.model.transform.DefaultNativeParser; import com.dianping.cat.consumer.storage.model.transform.DefaultSaxParser; import com.dianping.cat.report.ReportDelegate; import com.dianping.cat.task.TaskManager; import com.dianping.cat.task.TaskManager.TaskProlicy; package com.dianping.cat.consumer.storage; public class StorageDelegate implements ReportDelegate<StorageReport> { @Inject private TaskManager m_taskManager; @Inject
private ServerFilterConfigManager m_configManager;
unidal/cat2
cat-plugin-event/src/main/java/org/unidal/cat/plugin/event/report/page/Handler.java
// Path: cat-plugin-event/src/main/java/org/unidal/cat/plugin/event/EventConstants.java // public interface EventConstants { // public String NAME = "event"; // }
import java.io.IOException; import java.util.Date; import javax.servlet.ServletException; import org.unidal.cat.core.view.svg.GraphBuilder; import org.unidal.cat.plugin.event.EventConstants; import org.unidal.cat.plugin.event.filter.EventNameFilter; import org.unidal.cat.plugin.event.filter.EventNameGraphFilter; import org.unidal.cat.plugin.event.filter.EventTypeFilter; import org.unidal.cat.plugin.event.filter.EventTypeGraphFilter; import org.unidal.cat.plugin.event.model.entity.EventReport; import org.unidal.cat.plugin.event.report.view.GraphViewModel; import org.unidal.cat.plugin.event.report.view.NameViewModel; import org.unidal.cat.plugin.event.report.view.TypeViewModel; import org.unidal.cat.spi.ReportPeriod; import org.unidal.cat.spi.report.ReportManager; import org.unidal.lookup.annotation.Inject; import org.unidal.web.mvc.PageHandler; import org.unidal.web.mvc.annotation.InboundActionMeta; import org.unidal.web.mvc.annotation.OutboundActionMeta; import org.unidal.web.mvc.annotation.PayloadMeta; import com.dianping.cat.mvc.PayloadNormalizer;
package org.unidal.cat.plugin.event.report.page; public class Handler implements PageHandler<Context> { @Inject private GraphBuilder m_builder; @Inject private JspViewer m_jspViewer; @Inject private PayloadNormalizer m_normalizer;
// Path: cat-plugin-event/src/main/java/org/unidal/cat/plugin/event/EventConstants.java // public interface EventConstants { // public String NAME = "event"; // } // Path: cat-plugin-event/src/main/java/org/unidal/cat/plugin/event/report/page/Handler.java import java.io.IOException; import java.util.Date; import javax.servlet.ServletException; import org.unidal.cat.core.view.svg.GraphBuilder; import org.unidal.cat.plugin.event.EventConstants; import org.unidal.cat.plugin.event.filter.EventNameFilter; import org.unidal.cat.plugin.event.filter.EventNameGraphFilter; import org.unidal.cat.plugin.event.filter.EventTypeFilter; import org.unidal.cat.plugin.event.filter.EventTypeGraphFilter; import org.unidal.cat.plugin.event.model.entity.EventReport; import org.unidal.cat.plugin.event.report.view.GraphViewModel; import org.unidal.cat.plugin.event.report.view.NameViewModel; import org.unidal.cat.plugin.event.report.view.TypeViewModel; import org.unidal.cat.spi.ReportPeriod; import org.unidal.cat.spi.report.ReportManager; import org.unidal.lookup.annotation.Inject; import org.unidal.web.mvc.PageHandler; import org.unidal.web.mvc.annotation.InboundActionMeta; import org.unidal.web.mvc.annotation.OutboundActionMeta; import org.unidal.web.mvc.annotation.PayloadMeta; import com.dianping.cat.mvc.PayloadNormalizer; package org.unidal.cat.plugin.event.report.page; public class Handler implements PageHandler<Context> { @Inject private GraphBuilder m_builder; @Inject private JspViewer m_jspViewer; @Inject private PayloadNormalizer m_normalizer;
@Inject(EventConstants.NAME)
unidal/cat2
cat-client/src/main/java/org/unidal/cat/transport/DefaultSocketAddressProvider.java
// Path: cat-client/src/main/java/com/site/helper/JsonBuilder.java // public class JsonBuilder { // // private FieldNamingStrategy m_fieldNamingStrategy = new FieldNamingStrategy() { // // @Override // public String translateName(Field f) { // String name = f.getName(); // // if (name.startsWith("m_")) { // return name.substring(2); // } else { // return name; // } // } // }; // // private Gson m_gson = new GsonBuilder().registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()) // .setDateFormat("yyyy-MM-dd HH:mm:ss").setFieldNamingStrategy(m_fieldNamingStrategy).create(); // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public Object parse(String json, Class clz) { // return m_gson.fromJson(json, clz); // } // // public String toJson(Object o) { // return m_gson.toJson(o); // } // // public String toJsonWithEnter(Object o) { // return m_gson.toJson(o) + "\n"; // } // // public class TimestampTypeAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp> { // private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // // public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) // throws JsonParseException { // if (!(json instanceof JsonPrimitive)) { // throw new JsonParseException("The date should be a string value"); // } // // try { // Date date = format.parse(json.getAsString()); // return new Timestamp(date.getTime()); // } catch (ParseException e) { // throw new JsonParseException(e); // } // } // // public JsonElement serialize(Timestamp src, Type arg1, JsonSerializationContext arg2) { // String dateFormatAsString = format.format(new Date(src.getTime())); // return new JsonPrimitive(dateFormatAsString); // } // } // // }
import java.io.InputStream; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.codehaus.plexus.logging.LogEnabled; import org.codehaus.plexus.logging.Logger; import org.unidal.cat.config.ClientConfigurationManager; import org.unidal.helper.Files; import org.unidal.helper.Splitters; import org.unidal.helper.Urls; import org.unidal.lookup.annotation.Inject; import org.unidal.lookup.annotation.Named; import org.unidal.net.SocketAddressProvider; import com.dianping.cat.configuration.KVConfig; import com.site.helper.JsonBuilder;
package org.unidal.cat.transport; @Named(type = SocketAddressProvider.class) public class DefaultSocketAddressProvider implements SocketAddressProvider, LogEnabled { @Inject private ClientConfigurationManager m_configManager;
// Path: cat-client/src/main/java/com/site/helper/JsonBuilder.java // public class JsonBuilder { // // private FieldNamingStrategy m_fieldNamingStrategy = new FieldNamingStrategy() { // // @Override // public String translateName(Field f) { // String name = f.getName(); // // if (name.startsWith("m_")) { // return name.substring(2); // } else { // return name; // } // } // }; // // private Gson m_gson = new GsonBuilder().registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()) // .setDateFormat("yyyy-MM-dd HH:mm:ss").setFieldNamingStrategy(m_fieldNamingStrategy).create(); // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public Object parse(String json, Class clz) { // return m_gson.fromJson(json, clz); // } // // public String toJson(Object o) { // return m_gson.toJson(o); // } // // public String toJsonWithEnter(Object o) { // return m_gson.toJson(o) + "\n"; // } // // public class TimestampTypeAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp> { // private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // // public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) // throws JsonParseException { // if (!(json instanceof JsonPrimitive)) { // throw new JsonParseException("The date should be a string value"); // } // // try { // Date date = format.parse(json.getAsString()); // return new Timestamp(date.getTime()); // } catch (ParseException e) { // throw new JsonParseException(e); // } // } // // public JsonElement serialize(Timestamp src, Type arg1, JsonSerializationContext arg2) { // String dateFormatAsString = format.format(new Date(src.getTime())); // return new JsonPrimitive(dateFormatAsString); // } // } // // } // Path: cat-client/src/main/java/org/unidal/cat/transport/DefaultSocketAddressProvider.java import java.io.InputStream; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.codehaus.plexus.logging.LogEnabled; import org.codehaus.plexus.logging.Logger; import org.unidal.cat.config.ClientConfigurationManager; import org.unidal.helper.Files; import org.unidal.helper.Splitters; import org.unidal.helper.Urls; import org.unidal.lookup.annotation.Inject; import org.unidal.lookup.annotation.Named; import org.unidal.net.SocketAddressProvider; import com.dianping.cat.configuration.KVConfig; import com.site.helper.JsonBuilder; package org.unidal.cat.transport; @Named(type = SocketAddressProvider.class) public class DefaultSocketAddressProvider implements SocketAddressProvider, LogEnabled { @Inject private ClientConfigurationManager m_configManager;
private JsonBuilder m_jsonBuilder = new JsonBuilder();
OpenHFT/Chronicle-Logger
logger-jul/src/main/java/net/openhft/chronicle/logger/jul/ChronicleLogger.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // }
import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.logger.ChronicleLogWriter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger;
/* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.jul; class ChronicleLogger extends Logger { protected final String name;
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // } // Path: logger-jul/src/main/java/net/openhft/chronicle/logger/jul/ChronicleLogger.java import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.logger.ChronicleLogWriter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; /* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.jul; class ChronicleLogger extends Logger { protected final String name;
protected final ChronicleLogWriter writer;
OpenHFT/Chronicle-Logger
logger-jul/src/main/java/net/openhft/chronicle/logger/jul/ChronicleLogger.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // }
import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.logger.ChronicleLogWriter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger;
/* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.jul; class ChronicleLogger extends Logger { protected final String name; protected final ChronicleLogWriter writer;
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // } // Path: logger-jul/src/main/java/net/openhft/chronicle/logger/jul/ChronicleLogger.java import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.logger.ChronicleLogWriter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; /* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.jul; class ChronicleLogger extends Logger { protected final String name; protected final ChronicleLogWriter writer;
protected final ChronicleLogLevel level;
OpenHFT/Chronicle-Logger
logger-jcl/src/main/java/net/openhft/chronicle/logger/jcl/ChronicleLogger.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // }
import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.logger.ChronicleLogWriter; import org.apache.commons.logging.Log;
/* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.jcl; class ChronicleLogger implements Log { private final String name;
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // } // Path: logger-jcl/src/main/java/net/openhft/chronicle/logger/jcl/ChronicleLogger.java import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.logger.ChronicleLogWriter; import org.apache.commons.logging.Log; /* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.jcl; class ChronicleLogger implements Log { private final String name;
private final ChronicleLogWriter appender;
OpenHFT/Chronicle-Logger
logger-jcl/src/main/java/net/openhft/chronicle/logger/jcl/ChronicleLogger.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // }
import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.logger.ChronicleLogWriter; import org.apache.commons.logging.Log;
/* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.jcl; class ChronicleLogger implements Log { private final String name; private final ChronicleLogWriter appender;
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // } // Path: logger-jcl/src/main/java/net/openhft/chronicle/logger/jcl/ChronicleLogger.java import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.logger.ChronicleLogWriter; import org.apache.commons.logging.Log; /* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.jcl; class ChronicleLogger implements Log { private final String name; private final ChronicleLogWriter appender;
private final ChronicleLogLevel level;
OpenHFT/Chronicle-Logger
logger-logback/src/main/java/net/openhft/chronicle/logger/logback/AbstractChronicleAppender.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // }
import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; import ch.qos.logback.core.filter.Filter; import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.spi.FilterAttachableImpl; import ch.qos.logback.core.spi.FilterReply; import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.logger.ChronicleLogWriter; import java.io.IOException; import java.util.List;
/* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.logback; public abstract class AbstractChronicleAppender extends ContextAwareBase implements Appender<ILoggingEvent> { private final FilterAttachableImpl<ILoggingEvent> filterAttachable;
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // } // Path: logger-logback/src/main/java/net/openhft/chronicle/logger/logback/AbstractChronicleAppender.java import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; import ch.qos.logback.core.filter.Filter; import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.spi.FilterAttachableImpl; import ch.qos.logback.core.spi.FilterReply; import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.logger.ChronicleLogWriter; import java.io.IOException; import java.util.List; /* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.logback; public abstract class AbstractChronicleAppender extends ContextAwareBase implements Appender<ILoggingEvent> { private final FilterAttachableImpl<ILoggingEvent> filterAttachable;
protected ChronicleLogWriter writer;
OpenHFT/Chronicle-Logger
logger-logback/src/main/java/net/openhft/chronicle/logger/logback/AbstractChronicleAppender.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // }
import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; import ch.qos.logback.core.filter.Filter; import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.spi.FilterAttachableImpl; import ch.qos.logback.core.spi.FilterReply; import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.logger.ChronicleLogWriter; import java.io.IOException; import java.util.List;
/* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.logback; public abstract class AbstractChronicleAppender extends ContextAwareBase implements Appender<ILoggingEvent> { private final FilterAttachableImpl<ILoggingEvent> filterAttachable; protected ChronicleLogWriter writer; private String name; private boolean started; private String path; private String wireType; protected AbstractChronicleAppender() { this.filterAttachable = new FilterAttachableImpl<>(); this.name = null; this.started = false; this.path = null; this.wireType = null; this.writer = null; } // ************************************************************************* // Custom logging options // *************************************************************************
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // } // Path: logger-logback/src/main/java/net/openhft/chronicle/logger/logback/AbstractChronicleAppender.java import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; import ch.qos.logback.core.filter.Filter; import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.spi.FilterAttachableImpl; import ch.qos.logback.core.spi.FilterReply; import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.logger.ChronicleLogWriter; import java.io.IOException; import java.util.List; /* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.logback; public abstract class AbstractChronicleAppender extends ContextAwareBase implements Appender<ILoggingEvent> { private final FilterAttachableImpl<ILoggingEvent> filterAttachable; protected ChronicleLogWriter writer; private String name; private boolean started; private String path; private String wireType; protected AbstractChronicleAppender() { this.filterAttachable = new FilterAttachableImpl<>(); this.name = null; this.started = false; this.path = null; this.wireType = null; this.writer = null; } // ************************************************************************* // Custom logging options // *************************************************************************
public static ChronicleLogLevel toChronicleLogLevel(final Level level) {
OpenHFT/Chronicle-Logger
logger-logback/src/test/java/net/openhft/chronicle/logger/logback/LogbackChronicleBinaryAppenderTest.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // }
import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import static java.lang.System.currentTimeMillis; import static org.junit.Assert.*; import net.openhft.chronicle.core.io.IOTools; import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.queue.ChronicleQueue; import net.openhft.chronicle.wire.DocumentContext; import net.openhft.chronicle.wire.Wire; import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException;
/* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.logback; public class LogbackChronicleBinaryAppenderTest extends LogbackTestBase { @NotNull private static ChronicleQueue getChronicleQueue(String testId) { return ChronicleQueue.singleBuilder(basePath(testId)).build(); } @Before public void setup() { System.setProperty( "logback.configurationFile", System.getProperty("resources.path") + "/logback-chronicle-binary-appender.xml"); } @After public void tearDown() { IOTools.deleteDirWithFiles(rootPath()); } @Test public void testBinaryAppender() throws IOException { final String testId = "binary-chronicle"; final String threadId = testId + "-th"; final Logger logger = LoggerFactory.getLogger(testId); Files.createDirectories(Paths.get(basePath(testId))); Thread.currentThread().setName(threadId);
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // Path: logger-logback/src/test/java/net/openhft/chronicle/logger/logback/LogbackChronicleBinaryAppenderTest.java import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import static java.lang.System.currentTimeMillis; import static org.junit.Assert.*; import net.openhft.chronicle.core.io.IOTools; import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.queue.ChronicleQueue; import net.openhft.chronicle.wire.DocumentContext; import net.openhft.chronicle.wire.Wire; import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.logback; public class LogbackChronicleBinaryAppenderTest extends LogbackTestBase { @NotNull private static ChronicleQueue getChronicleQueue(String testId) { return ChronicleQueue.singleBuilder(basePath(testId)).build(); } @Before public void setup() { System.setProperty( "logback.configurationFile", System.getProperty("resources.path") + "/logback-chronicle-binary-appender.xml"); } @After public void tearDown() { IOTools.deleteDirWithFiles(rootPath()); } @Test public void testBinaryAppender() throws IOException { final String testId = "binary-chronicle"; final String threadId = testId + "-th"; final Logger logger = LoggerFactory.getLogger(testId); Files.createDirectories(Paths.get(basePath(testId))); Thread.currentThread().setName(threadId);
for (ChronicleLogLevel level : LOG_LEVELS) {
OpenHFT/Chronicle-Logger
logger-slf4j/src/main/java/org/slf4j/impl/StaticLoggerBinder.java
// Path: logger-slf4j/src/main/java/net/openhft/chronicle/logger/slf4j/ChronicleLoggerFactory.java // public class ChronicleLoggerFactory implements ILoggerFactory { // private final Map<String, Logger> loggers; // private final ChronicleLogManager manager; // // // ************************************************************************* // // // // ************************************************************************* // // /** // * c-tor // */ // public ChronicleLoggerFactory() { // this.loggers = new ConcurrentHashMap<>(); // this.manager = ChronicleLogManager.getInstance(); // } // // // ************************************************************************* // // for testing // // ************************************************************************* // // /** // * Return an appropriate {@link ChronicleLogger} instance by name. // */ // @Override // public Logger getLogger(String name) { // try { // return doGetLogger(name); // } catch (Exception e) { // System.err.println("Unable to initialize chronicle-logger-slf4j (" + name + ")\n " + e.getMessage()); // e.printStackTrace(); // } // // return NOPLogger.NOP_LOGGER; // } // // // ************************************************************************* // // // // ************************************************************************* // // synchronized void reload() { // this.loggers.clear(); // this.manager.reload(); // } // // private synchronized Logger doGetLogger(String name) { // Logger logger = loggers.get(name); // if (logger == null) { // if (name != null && name.startsWith("net.openhft")) { // SimpleLogger.lazyInit(); // logger = new SimpleLogger(name); // } else { // final ChronicleLogWriter writer = manager.getWriter(name); // logger = new ChronicleLogger(writer, name, manager.cfg().getLevel(name)); // } // loggers.put(name, logger); // } // // return logger; // } // }
import net.openhft.chronicle.logger.slf4j.ChronicleLoggerFactory; import org.slf4j.ILoggerFactory; import org.slf4j.spi.LoggerFactoryBinder;
/* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.slf4j.impl; public class StaticLoggerBinder implements LoggerFactoryBinder { private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
// Path: logger-slf4j/src/main/java/net/openhft/chronicle/logger/slf4j/ChronicleLoggerFactory.java // public class ChronicleLoggerFactory implements ILoggerFactory { // private final Map<String, Logger> loggers; // private final ChronicleLogManager manager; // // // ************************************************************************* // // // // ************************************************************************* // // /** // * c-tor // */ // public ChronicleLoggerFactory() { // this.loggers = new ConcurrentHashMap<>(); // this.manager = ChronicleLogManager.getInstance(); // } // // // ************************************************************************* // // for testing // // ************************************************************************* // // /** // * Return an appropriate {@link ChronicleLogger} instance by name. // */ // @Override // public Logger getLogger(String name) { // try { // return doGetLogger(name); // } catch (Exception e) { // System.err.println("Unable to initialize chronicle-logger-slf4j (" + name + ")\n " + e.getMessage()); // e.printStackTrace(); // } // // return NOPLogger.NOP_LOGGER; // } // // // ************************************************************************* // // // // ************************************************************************* // // synchronized void reload() { // this.loggers.clear(); // this.manager.reload(); // } // // private synchronized Logger doGetLogger(String name) { // Logger logger = loggers.get(name); // if (logger == null) { // if (name != null && name.startsWith("net.openhft")) { // SimpleLogger.lazyInit(); // logger = new SimpleLogger(name); // } else { // final ChronicleLogWriter writer = manager.getWriter(name); // logger = new ChronicleLogger(writer, name, manager.cfg().getLevel(name)); // } // loggers.put(name, logger); // } // // return logger; // } // } // Path: logger-slf4j/src/main/java/org/slf4j/impl/StaticLoggerBinder.java import net.openhft.chronicle.logger.slf4j.ChronicleLoggerFactory; import org.slf4j.ILoggerFactory; import org.slf4j.spi.LoggerFactoryBinder; /* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.slf4j.impl; public class StaticLoggerBinder implements LoggerFactoryBinder { private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
private static final String loggerFactoryClassStr = ChronicleLoggerFactory.class.getName();
OpenHFT/Chronicle-Logger
logger-jul/src/main/java/net/openhft/chronicle/logger/jul/AbstractChronicleHandler.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // }
import net.openhft.chronicle.logger.ChronicleLogWriter; import java.io.IOException; import java.util.logging.Filter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord;
/* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.jul; abstract class AbstractChronicleHandler extends Handler { private String path;
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // } // Path: logger-jul/src/main/java/net/openhft/chronicle/logger/jul/AbstractChronicleHandler.java import net.openhft.chronicle.logger.ChronicleLogWriter; import java.io.IOException; import java.util.logging.Filter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; /* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.jul; abstract class AbstractChronicleHandler extends Handler { private String path;
private ChronicleLogWriter writer;
OpenHFT/Chronicle-Logger
logger-log4j-1/src/test/java/net/openhft/chronicle/logger/log4j1/Log4j1ChronicleLogTest.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // }
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static java.lang.System.currentTimeMillis; import static org.junit.Assert.*; import net.openhft.chronicle.core.io.IOTools; import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.queue.ChronicleQueue; import net.openhft.chronicle.wire.DocumentContext; import net.openhft.chronicle.wire.Wire; import net.openhft.chronicle.wire.WireType; import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.log4j1; public class Log4j1ChronicleLogTest extends Log4j1TestBase { @NotNull private static ChronicleQueue getChronicleQueue(String testId, WireType wt) { return ChronicleQueue.singleBuilder(basePath(testId)).wireType(wt).build(); } @After public void tearDown() { IOTools.deleteDirWithFiles(rootPath()); } @Test public void testBinaryAppender() throws IOException { final String testId = "chronicle"; final String threadId = testId + "-th"; final Logger logger = LoggerFactory.getLogger(testId); Files.createDirectories(Paths.get(basePath(testId))); Thread.currentThread().setName(threadId);
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // Path: logger-log4j-1/src/test/java/net/openhft/chronicle/logger/log4j1/Log4j1ChronicleLogTest.java import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static java.lang.System.currentTimeMillis; import static org.junit.Assert.*; import net.openhft.chronicle.core.io.IOTools; import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.queue.ChronicleQueue; import net.openhft.chronicle.wire.DocumentContext; import net.openhft.chronicle.wire.Wire; import net.openhft.chronicle.wire.WireType; import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.log4j1; public class Log4j1ChronicleLogTest extends Log4j1TestBase { @NotNull private static ChronicleQueue getChronicleQueue(String testId, WireType wt) { return ChronicleQueue.singleBuilder(basePath(testId)).wireType(wt).build(); } @After public void tearDown() { IOTools.deleteDirWithFiles(rootPath()); } @Test public void testBinaryAppender() throws IOException { final String testId = "chronicle"; final String threadId = testId + "-th"; final Logger logger = LoggerFactory.getLogger(testId); Files.createDirectories(Paths.get(basePath(testId))); Thread.currentThread().setName(threadId);
for (ChronicleLogLevel level : LOG_LEVELS) {
OpenHFT/Chronicle-Logger
logger-slf4j/src/main/java/net/openhft/chronicle/logger/slf4j/ChronicleLogger.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // }
import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.logger.ChronicleLogWriter; import org.slf4j.helpers.MarkerIgnoringBase;
/* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.slf4j; public final class ChronicleLogger extends MarkerIgnoringBase { private static final long serialVersionUID = 1L;
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // } // Path: logger-slf4j/src/main/java/net/openhft/chronicle/logger/slf4j/ChronicleLogger.java import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.logger.ChronicleLogWriter; import org.slf4j.helpers.MarkerIgnoringBase; /* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.slf4j; public final class ChronicleLogger extends MarkerIgnoringBase { private static final long serialVersionUID = 1L;
protected final ChronicleLogLevel level;
OpenHFT/Chronicle-Logger
logger-slf4j/src/main/java/net/openhft/chronicle/logger/slf4j/ChronicleLogger.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // }
import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.logger.ChronicleLogWriter; import org.slf4j.helpers.MarkerIgnoringBase;
/* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.slf4j; public final class ChronicleLogger extends MarkerIgnoringBase { private static final long serialVersionUID = 1L; protected final ChronicleLogLevel level;
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // } // Path: logger-slf4j/src/main/java/net/openhft/chronicle/logger/slf4j/ChronicleLogger.java import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.logger.ChronicleLogWriter; import org.slf4j.helpers.MarkerIgnoringBase; /* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.slf4j; public final class ChronicleLogger extends MarkerIgnoringBase { private static final long serialVersionUID = 1L; protected final ChronicleLogLevel level;
private final ChronicleLogWriter writer;
OpenHFT/Chronicle-Logger
logger-tools/src/main/java/net/openhft/chronicle/logger/tools/ChronicleLogProcessor.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // }
import net.openhft.chronicle.logger.ChronicleLogLevel; import org.jetbrains.annotations.Nullable;
/* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.tools; public interface ChronicleLogProcessor { void process( final long timestamp,
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // Path: logger-tools/src/main/java/net/openhft/chronicle/logger/tools/ChronicleLogProcessor.java import net.openhft.chronicle.logger.ChronicleLogLevel; import org.jetbrains.annotations.Nullable; /* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.tools; public interface ChronicleLogProcessor { void process( final long timestamp,
final ChronicleLogLevel level,
OpenHFT/Chronicle-Logger
logger-slf4j/src/test/java/net/openhft/chronicle/logger/slf4j/Slf4jTestBase.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-slf4j/src/main/java/org/slf4j/impl/StaticLoggerBinder.java // public class StaticLoggerBinder implements LoggerFactoryBinder { // // private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); // private static final String loggerFactoryClassStr = ChronicleLoggerFactory.class.getName(); // /** // * Declare the version of the SLF4J API this implementation is compiled // * against. The value of this field is usually modified with each release. // */ // // to avoid constant folding by the compiler, this field must *not* be final // public static String REQUESTED_API_VERSION = "1.7.30"; // !final // /** // * The ILoggerFactory instance returned by the {@link #getLoggerFactory} // * method should always be the same object // */ // private final ILoggerFactory loggerFactory; // // /** // * c-tor // */ // private StaticLoggerBinder() { // loggerFactory = new ChronicleLoggerFactory(); // } // // /** // * Return the singleton of this class. // * // * @return the StaticLoggerBinder singleton // */ // public static final StaticLoggerBinder getSingleton() { // return SINGLETON; // } // // @Override // public ILoggerFactory getLoggerFactory() { // return loggerFactory; // } // // @Override // public String getLoggerFactoryClassStr() { // return loggerFactoryClassStr; // } // }
import net.openhft.chronicle.core.OS; import net.openhft.chronicle.core.util.Time; import net.openhft.chronicle.logger.ChronicleLogLevel; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.impl.StaticLoggerBinder;
case INFO: logger.info(fmt, args); break; case WARN: logger.warn(fmt, args); break; case ERROR: logger.error(fmt, args); break; default: throw new UnsupportedOperationException(); } } static void warmup(Logger logger) { for (int i = 0; i < 10; i++) { logger.info("warmup"); } } // ************************************************************************* // // ************************************************************************* /** * @return the ChronicleLoggerFactory singleton */ ChronicleLoggerFactory getChronicleLoggerFactory() {
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-slf4j/src/main/java/org/slf4j/impl/StaticLoggerBinder.java // public class StaticLoggerBinder implements LoggerFactoryBinder { // // private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); // private static final String loggerFactoryClassStr = ChronicleLoggerFactory.class.getName(); // /** // * Declare the version of the SLF4J API this implementation is compiled // * against. The value of this field is usually modified with each release. // */ // // to avoid constant folding by the compiler, this field must *not* be final // public static String REQUESTED_API_VERSION = "1.7.30"; // !final // /** // * The ILoggerFactory instance returned by the {@link #getLoggerFactory} // * method should always be the same object // */ // private final ILoggerFactory loggerFactory; // // /** // * c-tor // */ // private StaticLoggerBinder() { // loggerFactory = new ChronicleLoggerFactory(); // } // // /** // * Return the singleton of this class. // * // * @return the StaticLoggerBinder singleton // */ // public static final StaticLoggerBinder getSingleton() { // return SINGLETON; // } // // @Override // public ILoggerFactory getLoggerFactory() { // return loggerFactory; // } // // @Override // public String getLoggerFactoryClassStr() { // return loggerFactoryClassStr; // } // } // Path: logger-slf4j/src/test/java/net/openhft/chronicle/logger/slf4j/Slf4jTestBase.java import net.openhft.chronicle.core.OS; import net.openhft.chronicle.core.util.Time; import net.openhft.chronicle.logger.ChronicleLogLevel; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.impl.StaticLoggerBinder; case INFO: logger.info(fmt, args); break; case WARN: logger.warn(fmt, args); break; case ERROR: logger.error(fmt, args); break; default: throw new UnsupportedOperationException(); } } static void warmup(Logger logger) { for (int i = 0; i < 10; i++) { logger.info("warmup"); } } // ************************************************************************* // // ************************************************************************* /** * @return the ChronicleLoggerFactory singleton */ ChronicleLoggerFactory getChronicleLoggerFactory() {
return (ChronicleLoggerFactory) StaticLoggerBinder.getSingleton().getLoggerFactory();
OpenHFT/Chronicle-Logger
logger-jul/src/test/java/net/openhft/chronicle/logger/jul/JulHandlerChronicleTest.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // }
import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import static java.lang.System.currentTimeMillis; import static org.junit.Assert.*; import net.openhft.chronicle.core.io.IOTools; import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.queue.ChronicleQueue; import net.openhft.chronicle.threads.DiskSpaceMonitor; import net.openhft.chronicle.wire.DocumentContext; import net.openhft.chronicle.wire.Wire; import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import java.util.ArrayList;
DiskSpaceMonitor.INSTANCE.close(); } @After public void tearDown() { IOTools.deleteDirWithFiles(rootPath()); } @Test public void testConfiguration() throws IOException { setupLogManager("binary-cfg"); Logger logger = Logger.getLogger("binary-cfg"); assertEquals(Level.INFO, logger.getLevel()); assertFalse(logger.getUseParentHandlers()); assertNull(logger.getFilter()); assertNotNull(logger.getHandlers()); assertEquals(1, logger.getHandlers().length); assertEquals(ChronicleHandler.class, logger.getHandlers()[0].getClass()); } @Test public void testAppender() throws IOException { final String testId = "binary-chronicle"; setupLogManager(testId); Logger logger = Logger.getLogger(testId); final String threadId = "thread-" + Thread.currentThread().getId();
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // Path: logger-jul/src/test/java/net/openhft/chronicle/logger/jul/JulHandlerChronicleTest.java import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import static java.lang.System.currentTimeMillis; import static org.junit.Assert.*; import net.openhft.chronicle.core.io.IOTools; import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.queue.ChronicleQueue; import net.openhft.chronicle.threads.DiskSpaceMonitor; import net.openhft.chronicle.wire.DocumentContext; import net.openhft.chronicle.wire.Wire; import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import java.util.ArrayList; DiskSpaceMonitor.INSTANCE.close(); } @After public void tearDown() { IOTools.deleteDirWithFiles(rootPath()); } @Test public void testConfiguration() throws IOException { setupLogManager("binary-cfg"); Logger logger = Logger.getLogger("binary-cfg"); assertEquals(Level.INFO, logger.getLevel()); assertFalse(logger.getUseParentHandlers()); assertNull(logger.getFilter()); assertNotNull(logger.getHandlers()); assertEquals(1, logger.getHandlers().length); assertEquals(ChronicleHandler.class, logger.getHandlers()[0].getClass()); } @Test public void testAppender() throws IOException { final String testId = "binary-chronicle"; setupLogManager(testId); Logger logger = Logger.getLogger(testId); final String threadId = "thread-" + Thread.currentThread().getId();
for (ChronicleLogLevel level : LOG_LEVELS) {
OpenHFT/Chronicle-Logger
logger-logback/src/test/java/net/openhft/chronicle/logger/logback/LogbackChronicleProgrammaticConfigTest.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/LogAppenderConfig.java // public class LogAppenderConfig { // // private static final String[] KEYS = new String[]{ // "blockSize", // "bufferCapacity", // "rollCycle" // }; // // private int blockSize; // private long bufferCapacity; // private String rollCycle; // // public LogAppenderConfig() { // } // // // ************************************************************************* // // // // ************************************************************************* // // public int getBlockSize() { // return this.blockSize; // } // // public void setBlockSize(int blockSize) { // this.blockSize = blockSize; // } // // public long getBufferCapacity() { // return this.bufferCapacity; // } // // public void setBufferCapacity(long bufferCapacity) { // this.bufferCapacity = bufferCapacity; // } // // public String getRollCycle() { // return rollCycle; // } // // public void setRollCycle(String rollCycle) { // this.rollCycle = rollCycle; // } // // // ************************************************************************* // // // // ************************************************************************* // // public String[] keys() { // return KEYS; // } // // public ChronicleQueue build(String path, String wireType) { // WireType wireTypeEnum = wireType != null ? WireType.valueOf(wireType.toUpperCase()) : WireType.BINARY_LIGHT; // SingleChronicleQueueBuilder builder = ChronicleQueue.singleBuilder(path) // .wireType(wireTypeEnum) // .blockSize(blockSize) // .bufferCapacity(bufferCapacity); // if (rollCycle != null) // builder.rollCycle(RollCycles.valueOf(rollCycle)); // return builder.build(); // } // // public void setProperties(@NotNull final Properties properties, @Nullable final String prefix) { // for (final Map.Entry<Object, Object> entry : properties.entrySet()) { // final String name = entry.getKey().toString(); // final String value = entry.getValue().toString(); // // if (prefix != null && !prefix.isEmpty()) { // if (name.startsWith(prefix)) { // setProperty(name.substring(prefix.length()), value); // } // } else { // setProperty(name, value); // } // } // } // // public void setProperty(@NotNull final String propName, final String propValue) { // try { // final PropertyDescriptor property = new PropertyDescriptor(propName, this.getClass()); // final Method method = property.getWriteMethod(); // final Class<?> type = method.getParameterTypes()[0]; // // if (type == null || propValue == null || propValue.isEmpty()) { // return; // } // if (type == int.class) { // method.invoke(this, Integer.parseInt(propValue)); // // } else if (type == long.class) { // method.invoke(this, Long.parseLong(propValue)); // // } else if (type == boolean.class) { // method.invoke(this, Boolean.parseBoolean(propValue)); // // } else if (type == String.class) { // method.invoke(this, propValue); // } // } catch (Exception e) { // } // } // }
import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import net.openhft.chronicle.core.OS; import net.openhft.chronicle.core.util.Time; import net.openhft.chronicle.logger.LogAppenderConfig; import org.junit.Test; import org.slf4j.LoggerFactory;
/* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.logback; public class LogbackChronicleProgrammaticConfigTest extends LogbackTestBase { @Test public void testConfig() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); context.reset(); ChronicleAppender appender = new ChronicleAppender(); appender.setPath(OS.getTarget() + "/clog" + Time.uniqueId());
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/LogAppenderConfig.java // public class LogAppenderConfig { // // private static final String[] KEYS = new String[]{ // "blockSize", // "bufferCapacity", // "rollCycle" // }; // // private int blockSize; // private long bufferCapacity; // private String rollCycle; // // public LogAppenderConfig() { // } // // // ************************************************************************* // // // // ************************************************************************* // // public int getBlockSize() { // return this.blockSize; // } // // public void setBlockSize(int blockSize) { // this.blockSize = blockSize; // } // // public long getBufferCapacity() { // return this.bufferCapacity; // } // // public void setBufferCapacity(long bufferCapacity) { // this.bufferCapacity = bufferCapacity; // } // // public String getRollCycle() { // return rollCycle; // } // // public void setRollCycle(String rollCycle) { // this.rollCycle = rollCycle; // } // // // ************************************************************************* // // // // ************************************************************************* // // public String[] keys() { // return KEYS; // } // // public ChronicleQueue build(String path, String wireType) { // WireType wireTypeEnum = wireType != null ? WireType.valueOf(wireType.toUpperCase()) : WireType.BINARY_LIGHT; // SingleChronicleQueueBuilder builder = ChronicleQueue.singleBuilder(path) // .wireType(wireTypeEnum) // .blockSize(blockSize) // .bufferCapacity(bufferCapacity); // if (rollCycle != null) // builder.rollCycle(RollCycles.valueOf(rollCycle)); // return builder.build(); // } // // public void setProperties(@NotNull final Properties properties, @Nullable final String prefix) { // for (final Map.Entry<Object, Object> entry : properties.entrySet()) { // final String name = entry.getKey().toString(); // final String value = entry.getValue().toString(); // // if (prefix != null && !prefix.isEmpty()) { // if (name.startsWith(prefix)) { // setProperty(name.substring(prefix.length()), value); // } // } else { // setProperty(name, value); // } // } // } // // public void setProperty(@NotNull final String propName, final String propValue) { // try { // final PropertyDescriptor property = new PropertyDescriptor(propName, this.getClass()); // final Method method = property.getWriteMethod(); // final Class<?> type = method.getParameterTypes()[0]; // // if (type == null || propValue == null || propValue.isEmpty()) { // return; // } // if (type == int.class) { // method.invoke(this, Integer.parseInt(propValue)); // // } else if (type == long.class) { // method.invoke(this, Long.parseLong(propValue)); // // } else if (type == boolean.class) { // method.invoke(this, Boolean.parseBoolean(propValue)); // // } else if (type == String.class) { // method.invoke(this, propValue); // } // } catch (Exception e) { // } // } // } // Path: logger-logback/src/test/java/net/openhft/chronicle/logger/logback/LogbackChronicleProgrammaticConfigTest.java import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import net.openhft.chronicle.core.OS; import net.openhft.chronicle.core.util.Time; import net.openhft.chronicle.logger.LogAppenderConfig; import org.junit.Test; import org.slf4j.LoggerFactory; /* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.logback; public class LogbackChronicleProgrammaticConfigTest extends LogbackTestBase { @Test public void testConfig() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); context.reset(); ChronicleAppender appender = new ChronicleAppender(); appender.setPath(OS.getTarget() + "/clog" + Time.uniqueId());
appender.setChronicleConfig(new LogAppenderConfig());
OpenHFT/Chronicle-Logger
logger-log4j-1/src/main/java/net/openhft/chronicle/logger/log4j1/AbstractChronicleAppender.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // }
import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.logger.ChronicleLogWriter; import org.apache.log4j.Appender; import org.apache.log4j.Layout; import org.apache.log4j.Level; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.helpers.OnlyOnceErrorHandler; import org.apache.log4j.spi.*; import java.io.IOException;
/* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.log4j1; public abstract class AbstractChronicleAppender implements Appender, OptionHandler { protected ChronicleLogWriter writer; private Filter filter; private String name; private ErrorHandler errorHandler; private String path; private String wireType; protected AbstractChronicleAppender() { this.path = null; this.writer = null; this.name = null; this.errorHandler = new OnlyOnceErrorHandler(); } // ************************************************************************* // Custom logging options // *************************************************************************
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // } // Path: logger-log4j-1/src/main/java/net/openhft/chronicle/logger/log4j1/AbstractChronicleAppender.java import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.logger.ChronicleLogWriter; import org.apache.log4j.Appender; import org.apache.log4j.Layout; import org.apache.log4j.Level; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.helpers.OnlyOnceErrorHandler; import org.apache.log4j.spi.*; import java.io.IOException; /* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.log4j1; public abstract class AbstractChronicleAppender implements Appender, OptionHandler { protected ChronicleLogWriter writer; private Filter filter; private String name; private ErrorHandler errorHandler; private String path; private String wireType; protected AbstractChronicleAppender() { this.path = null; this.writer = null; this.name = null; this.errorHandler = new OnlyOnceErrorHandler(); } // ************************************************************************* // Custom logging options // *************************************************************************
public static ChronicleLogLevel toChronicleLogLevel(final Level level) {
OpenHFT/Chronicle-Logger
logger-jul/src/main/java/net/openhft/chronicle/logger/jul/ChronicleHandlerConfig.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/LogAppenderConfig.java // public class LogAppenderConfig { // // private static final String[] KEYS = new String[]{ // "blockSize", // "bufferCapacity", // "rollCycle" // }; // // private int blockSize; // private long bufferCapacity; // private String rollCycle; // // public LogAppenderConfig() { // } // // // ************************************************************************* // // // // ************************************************************************* // // public int getBlockSize() { // return this.blockSize; // } // // public void setBlockSize(int blockSize) { // this.blockSize = blockSize; // } // // public long getBufferCapacity() { // return this.bufferCapacity; // } // // public void setBufferCapacity(long bufferCapacity) { // this.bufferCapacity = bufferCapacity; // } // // public String getRollCycle() { // return rollCycle; // } // // public void setRollCycle(String rollCycle) { // this.rollCycle = rollCycle; // } // // // ************************************************************************* // // // // ************************************************************************* // // public String[] keys() { // return KEYS; // } // // public ChronicleQueue build(String path, String wireType) { // WireType wireTypeEnum = wireType != null ? WireType.valueOf(wireType.toUpperCase()) : WireType.BINARY_LIGHT; // SingleChronicleQueueBuilder builder = ChronicleQueue.singleBuilder(path) // .wireType(wireTypeEnum) // .blockSize(blockSize) // .bufferCapacity(bufferCapacity); // if (rollCycle != null) // builder.rollCycle(RollCycles.valueOf(rollCycle)); // return builder.build(); // } // // public void setProperties(@NotNull final Properties properties, @Nullable final String prefix) { // for (final Map.Entry<Object, Object> entry : properties.entrySet()) { // final String name = entry.getKey().toString(); // final String value = entry.getValue().toString(); // // if (prefix != null && !prefix.isEmpty()) { // if (name.startsWith(prefix)) { // setProperty(name.substring(prefix.length()), value); // } // } else { // setProperty(name, value); // } // } // } // // public void setProperty(@NotNull final String propName, final String propValue) { // try { // final PropertyDescriptor property = new PropertyDescriptor(propName, this.getClass()); // final Method method = property.getWriteMethod(); // final Class<?> type = method.getParameterTypes()[0]; // // if (type == null || propValue == null || propValue.isEmpty()) { // return; // } // if (type == int.class) { // method.invoke(this, Integer.parseInt(propValue)); // // } else if (type == long.class) { // method.invoke(this, Long.parseLong(propValue)); // // } else if (type == boolean.class) { // method.invoke(this, Boolean.parseBoolean(propValue)); // // } else if (type == String.class) { // method.invoke(this, propValue); // } // } catch (Exception e) { // } // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogConfig.java // public static final String PLACEHOLDER_END = "}"; // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogConfig.java // public static final String PLACEHOLDER_START = "${";
import net.openhft.chronicle.logger.LogAppenderConfig; import java.util.logging.Filter; import java.util.logging.Level; import java.util.logging.LogManager; import static net.openhft.chronicle.logger.ChronicleLogConfig.PLACEHOLDER_END; import static net.openhft.chronicle.logger.ChronicleLogConfig.PLACEHOLDER_START;
/* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.jul; public class ChronicleHandlerConfig { private final LogManager manager; private final String prefix; public ChronicleHandlerConfig(final Class<?> type) { this.manager = LogManager.getLogManager(); this.prefix = type.getName(); } public String getString(String name, String defaultValue) { return getStringProperty(this.prefix + "." + name, defaultValue); } public int getInt(String name, int defaultValue) { return getIntProperty(this.prefix + "." + name, defaultValue); } public boolean getBoolean(String name, boolean defaultValue) { return getBooleanProperty(this.prefix + "." + name, defaultValue); } public Level getLevel(String name, Level defaultValue) { return getLevelProperty(this.prefix + "." + name, defaultValue); } public Filter getFilter(String name, Filter defaultValue) { return getFilterProperty(this.prefix + "." + name, defaultValue); }
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/LogAppenderConfig.java // public class LogAppenderConfig { // // private static final String[] KEYS = new String[]{ // "blockSize", // "bufferCapacity", // "rollCycle" // }; // // private int blockSize; // private long bufferCapacity; // private String rollCycle; // // public LogAppenderConfig() { // } // // // ************************************************************************* // // // // ************************************************************************* // // public int getBlockSize() { // return this.blockSize; // } // // public void setBlockSize(int blockSize) { // this.blockSize = blockSize; // } // // public long getBufferCapacity() { // return this.bufferCapacity; // } // // public void setBufferCapacity(long bufferCapacity) { // this.bufferCapacity = bufferCapacity; // } // // public String getRollCycle() { // return rollCycle; // } // // public void setRollCycle(String rollCycle) { // this.rollCycle = rollCycle; // } // // // ************************************************************************* // // // // ************************************************************************* // // public String[] keys() { // return KEYS; // } // // public ChronicleQueue build(String path, String wireType) { // WireType wireTypeEnum = wireType != null ? WireType.valueOf(wireType.toUpperCase()) : WireType.BINARY_LIGHT; // SingleChronicleQueueBuilder builder = ChronicleQueue.singleBuilder(path) // .wireType(wireTypeEnum) // .blockSize(blockSize) // .bufferCapacity(bufferCapacity); // if (rollCycle != null) // builder.rollCycle(RollCycles.valueOf(rollCycle)); // return builder.build(); // } // // public void setProperties(@NotNull final Properties properties, @Nullable final String prefix) { // for (final Map.Entry<Object, Object> entry : properties.entrySet()) { // final String name = entry.getKey().toString(); // final String value = entry.getValue().toString(); // // if (prefix != null && !prefix.isEmpty()) { // if (name.startsWith(prefix)) { // setProperty(name.substring(prefix.length()), value); // } // } else { // setProperty(name, value); // } // } // } // // public void setProperty(@NotNull final String propName, final String propValue) { // try { // final PropertyDescriptor property = new PropertyDescriptor(propName, this.getClass()); // final Method method = property.getWriteMethod(); // final Class<?> type = method.getParameterTypes()[0]; // // if (type == null || propValue == null || propValue.isEmpty()) { // return; // } // if (type == int.class) { // method.invoke(this, Integer.parseInt(propValue)); // // } else if (type == long.class) { // method.invoke(this, Long.parseLong(propValue)); // // } else if (type == boolean.class) { // method.invoke(this, Boolean.parseBoolean(propValue)); // // } else if (type == String.class) { // method.invoke(this, propValue); // } // } catch (Exception e) { // } // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogConfig.java // public static final String PLACEHOLDER_END = "}"; // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogConfig.java // public static final String PLACEHOLDER_START = "${"; // Path: logger-jul/src/main/java/net/openhft/chronicle/logger/jul/ChronicleHandlerConfig.java import net.openhft.chronicle.logger.LogAppenderConfig; import java.util.logging.Filter; import java.util.logging.Level; import java.util.logging.LogManager; import static net.openhft.chronicle.logger.ChronicleLogConfig.PLACEHOLDER_END; import static net.openhft.chronicle.logger.ChronicleLogConfig.PLACEHOLDER_START; /* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.jul; public class ChronicleHandlerConfig { private final LogManager manager; private final String prefix; public ChronicleHandlerConfig(final Class<?> type) { this.manager = LogManager.getLogManager(); this.prefix = type.getName(); } public String getString(String name, String defaultValue) { return getStringProperty(this.prefix + "." + name, defaultValue); } public int getInt(String name, int defaultValue) { return getIntProperty(this.prefix + "." + name, defaultValue); } public boolean getBoolean(String name, boolean defaultValue) { return getBooleanProperty(this.prefix + "." + name, defaultValue); } public Level getLevel(String name, Level defaultValue) { return getLevelProperty(this.prefix + "." + name, defaultValue); } public Filter getFilter(String name, Filter defaultValue) { return getFilterProperty(this.prefix + "." + name, defaultValue); }
public LogAppenderConfig getAppenderConfig() {
OpenHFT/Chronicle-Logger
logger-jul/src/main/java/net/openhft/chronicle/logger/jul/ChronicleHandlerConfig.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/LogAppenderConfig.java // public class LogAppenderConfig { // // private static final String[] KEYS = new String[]{ // "blockSize", // "bufferCapacity", // "rollCycle" // }; // // private int blockSize; // private long bufferCapacity; // private String rollCycle; // // public LogAppenderConfig() { // } // // // ************************************************************************* // // // // ************************************************************************* // // public int getBlockSize() { // return this.blockSize; // } // // public void setBlockSize(int blockSize) { // this.blockSize = blockSize; // } // // public long getBufferCapacity() { // return this.bufferCapacity; // } // // public void setBufferCapacity(long bufferCapacity) { // this.bufferCapacity = bufferCapacity; // } // // public String getRollCycle() { // return rollCycle; // } // // public void setRollCycle(String rollCycle) { // this.rollCycle = rollCycle; // } // // // ************************************************************************* // // // // ************************************************************************* // // public String[] keys() { // return KEYS; // } // // public ChronicleQueue build(String path, String wireType) { // WireType wireTypeEnum = wireType != null ? WireType.valueOf(wireType.toUpperCase()) : WireType.BINARY_LIGHT; // SingleChronicleQueueBuilder builder = ChronicleQueue.singleBuilder(path) // .wireType(wireTypeEnum) // .blockSize(blockSize) // .bufferCapacity(bufferCapacity); // if (rollCycle != null) // builder.rollCycle(RollCycles.valueOf(rollCycle)); // return builder.build(); // } // // public void setProperties(@NotNull final Properties properties, @Nullable final String prefix) { // for (final Map.Entry<Object, Object> entry : properties.entrySet()) { // final String name = entry.getKey().toString(); // final String value = entry.getValue().toString(); // // if (prefix != null && !prefix.isEmpty()) { // if (name.startsWith(prefix)) { // setProperty(name.substring(prefix.length()), value); // } // } else { // setProperty(name, value); // } // } // } // // public void setProperty(@NotNull final String propName, final String propValue) { // try { // final PropertyDescriptor property = new PropertyDescriptor(propName, this.getClass()); // final Method method = property.getWriteMethod(); // final Class<?> type = method.getParameterTypes()[0]; // // if (type == null || propValue == null || propValue.isEmpty()) { // return; // } // if (type == int.class) { // method.invoke(this, Integer.parseInt(propValue)); // // } else if (type == long.class) { // method.invoke(this, Long.parseLong(propValue)); // // } else if (type == boolean.class) { // method.invoke(this, Boolean.parseBoolean(propValue)); // // } else if (type == String.class) { // method.invoke(this, propValue); // } // } catch (Exception e) { // } // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogConfig.java // public static final String PLACEHOLDER_END = "}"; // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogConfig.java // public static final String PLACEHOLDER_START = "${";
import net.openhft.chronicle.logger.LogAppenderConfig; import java.util.logging.Filter; import java.util.logging.Level; import java.util.logging.LogManager; import static net.openhft.chronicle.logger.ChronicleLogConfig.PLACEHOLDER_END; import static net.openhft.chronicle.logger.ChronicleLogConfig.PLACEHOLDER_START;
try { if (val != null) { Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(val); return (Filter) clz.newInstance(); } } catch (Exception ex) { // We got one of a variety of exceptions in creating the // class or creating an instance. // Drop through. } // We got an exception. Return the defaultValue. return defaultValue; } Level getLevelProperty(String name, Level defaultValue) { String val = getStringProperty(name, null); if (val == null) { return defaultValue; } Level l = Level.parse(val.trim()); return l != null ? l : defaultValue; } private String resolvePlaceholder(String placeholder) { int startIndex = 0; int endIndex = 0; do {
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/LogAppenderConfig.java // public class LogAppenderConfig { // // private static final String[] KEYS = new String[]{ // "blockSize", // "bufferCapacity", // "rollCycle" // }; // // private int blockSize; // private long bufferCapacity; // private String rollCycle; // // public LogAppenderConfig() { // } // // // ************************************************************************* // // // // ************************************************************************* // // public int getBlockSize() { // return this.blockSize; // } // // public void setBlockSize(int blockSize) { // this.blockSize = blockSize; // } // // public long getBufferCapacity() { // return this.bufferCapacity; // } // // public void setBufferCapacity(long bufferCapacity) { // this.bufferCapacity = bufferCapacity; // } // // public String getRollCycle() { // return rollCycle; // } // // public void setRollCycle(String rollCycle) { // this.rollCycle = rollCycle; // } // // // ************************************************************************* // // // // ************************************************************************* // // public String[] keys() { // return KEYS; // } // // public ChronicleQueue build(String path, String wireType) { // WireType wireTypeEnum = wireType != null ? WireType.valueOf(wireType.toUpperCase()) : WireType.BINARY_LIGHT; // SingleChronicleQueueBuilder builder = ChronicleQueue.singleBuilder(path) // .wireType(wireTypeEnum) // .blockSize(blockSize) // .bufferCapacity(bufferCapacity); // if (rollCycle != null) // builder.rollCycle(RollCycles.valueOf(rollCycle)); // return builder.build(); // } // // public void setProperties(@NotNull final Properties properties, @Nullable final String prefix) { // for (final Map.Entry<Object, Object> entry : properties.entrySet()) { // final String name = entry.getKey().toString(); // final String value = entry.getValue().toString(); // // if (prefix != null && !prefix.isEmpty()) { // if (name.startsWith(prefix)) { // setProperty(name.substring(prefix.length()), value); // } // } else { // setProperty(name, value); // } // } // } // // public void setProperty(@NotNull final String propName, final String propValue) { // try { // final PropertyDescriptor property = new PropertyDescriptor(propName, this.getClass()); // final Method method = property.getWriteMethod(); // final Class<?> type = method.getParameterTypes()[0]; // // if (type == null || propValue == null || propValue.isEmpty()) { // return; // } // if (type == int.class) { // method.invoke(this, Integer.parseInt(propValue)); // // } else if (type == long.class) { // method.invoke(this, Long.parseLong(propValue)); // // } else if (type == boolean.class) { // method.invoke(this, Boolean.parseBoolean(propValue)); // // } else if (type == String.class) { // method.invoke(this, propValue); // } // } catch (Exception e) { // } // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogConfig.java // public static final String PLACEHOLDER_END = "}"; // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogConfig.java // public static final String PLACEHOLDER_START = "${"; // Path: logger-jul/src/main/java/net/openhft/chronicle/logger/jul/ChronicleHandlerConfig.java import net.openhft.chronicle.logger.LogAppenderConfig; import java.util.logging.Filter; import java.util.logging.Level; import java.util.logging.LogManager; import static net.openhft.chronicle.logger.ChronicleLogConfig.PLACEHOLDER_END; import static net.openhft.chronicle.logger.ChronicleLogConfig.PLACEHOLDER_START; try { if (val != null) { Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(val); return (Filter) clz.newInstance(); } } catch (Exception ex) { // We got one of a variety of exceptions in creating the // class or creating an instance. // Drop through. } // We got an exception. Return the defaultValue. return defaultValue; } Level getLevelProperty(String name, Level defaultValue) { String val = getStringProperty(name, null); if (val == null) { return defaultValue; } Level l = Level.parse(val.trim()); return l != null ? l : defaultValue; } private String resolvePlaceholder(String placeholder) { int startIndex = 0; int endIndex = 0; do {
startIndex = placeholder.indexOf(PLACEHOLDER_START, endIndex);
OpenHFT/Chronicle-Logger
logger-jul/src/main/java/net/openhft/chronicle/logger/jul/ChronicleHandlerConfig.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/LogAppenderConfig.java // public class LogAppenderConfig { // // private static final String[] KEYS = new String[]{ // "blockSize", // "bufferCapacity", // "rollCycle" // }; // // private int blockSize; // private long bufferCapacity; // private String rollCycle; // // public LogAppenderConfig() { // } // // // ************************************************************************* // // // // ************************************************************************* // // public int getBlockSize() { // return this.blockSize; // } // // public void setBlockSize(int blockSize) { // this.blockSize = blockSize; // } // // public long getBufferCapacity() { // return this.bufferCapacity; // } // // public void setBufferCapacity(long bufferCapacity) { // this.bufferCapacity = bufferCapacity; // } // // public String getRollCycle() { // return rollCycle; // } // // public void setRollCycle(String rollCycle) { // this.rollCycle = rollCycle; // } // // // ************************************************************************* // // // // ************************************************************************* // // public String[] keys() { // return KEYS; // } // // public ChronicleQueue build(String path, String wireType) { // WireType wireTypeEnum = wireType != null ? WireType.valueOf(wireType.toUpperCase()) : WireType.BINARY_LIGHT; // SingleChronicleQueueBuilder builder = ChronicleQueue.singleBuilder(path) // .wireType(wireTypeEnum) // .blockSize(blockSize) // .bufferCapacity(bufferCapacity); // if (rollCycle != null) // builder.rollCycle(RollCycles.valueOf(rollCycle)); // return builder.build(); // } // // public void setProperties(@NotNull final Properties properties, @Nullable final String prefix) { // for (final Map.Entry<Object, Object> entry : properties.entrySet()) { // final String name = entry.getKey().toString(); // final String value = entry.getValue().toString(); // // if (prefix != null && !prefix.isEmpty()) { // if (name.startsWith(prefix)) { // setProperty(name.substring(prefix.length()), value); // } // } else { // setProperty(name, value); // } // } // } // // public void setProperty(@NotNull final String propName, final String propValue) { // try { // final PropertyDescriptor property = new PropertyDescriptor(propName, this.getClass()); // final Method method = property.getWriteMethod(); // final Class<?> type = method.getParameterTypes()[0]; // // if (type == null || propValue == null || propValue.isEmpty()) { // return; // } // if (type == int.class) { // method.invoke(this, Integer.parseInt(propValue)); // // } else if (type == long.class) { // method.invoke(this, Long.parseLong(propValue)); // // } else if (type == boolean.class) { // method.invoke(this, Boolean.parseBoolean(propValue)); // // } else if (type == String.class) { // method.invoke(this, propValue); // } // } catch (Exception e) { // } // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogConfig.java // public static final String PLACEHOLDER_END = "}"; // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogConfig.java // public static final String PLACEHOLDER_START = "${";
import net.openhft.chronicle.logger.LogAppenderConfig; import java.util.logging.Filter; import java.util.logging.Level; import java.util.logging.LogManager; import static net.openhft.chronicle.logger.ChronicleLogConfig.PLACEHOLDER_END; import static net.openhft.chronicle.logger.ChronicleLogConfig.PLACEHOLDER_START;
if (val != null) { Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(val); return (Filter) clz.newInstance(); } } catch (Exception ex) { // We got one of a variety of exceptions in creating the // class or creating an instance. // Drop through. } // We got an exception. Return the defaultValue. return defaultValue; } Level getLevelProperty(String name, Level defaultValue) { String val = getStringProperty(name, null); if (val == null) { return defaultValue; } Level l = Level.parse(val.trim()); return l != null ? l : defaultValue; } private String resolvePlaceholder(String placeholder) { int startIndex = 0; int endIndex = 0; do { startIndex = placeholder.indexOf(PLACEHOLDER_START, endIndex); if (startIndex != -1) {
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/LogAppenderConfig.java // public class LogAppenderConfig { // // private static final String[] KEYS = new String[]{ // "blockSize", // "bufferCapacity", // "rollCycle" // }; // // private int blockSize; // private long bufferCapacity; // private String rollCycle; // // public LogAppenderConfig() { // } // // // ************************************************************************* // // // // ************************************************************************* // // public int getBlockSize() { // return this.blockSize; // } // // public void setBlockSize(int blockSize) { // this.blockSize = blockSize; // } // // public long getBufferCapacity() { // return this.bufferCapacity; // } // // public void setBufferCapacity(long bufferCapacity) { // this.bufferCapacity = bufferCapacity; // } // // public String getRollCycle() { // return rollCycle; // } // // public void setRollCycle(String rollCycle) { // this.rollCycle = rollCycle; // } // // // ************************************************************************* // // // // ************************************************************************* // // public String[] keys() { // return KEYS; // } // // public ChronicleQueue build(String path, String wireType) { // WireType wireTypeEnum = wireType != null ? WireType.valueOf(wireType.toUpperCase()) : WireType.BINARY_LIGHT; // SingleChronicleQueueBuilder builder = ChronicleQueue.singleBuilder(path) // .wireType(wireTypeEnum) // .blockSize(blockSize) // .bufferCapacity(bufferCapacity); // if (rollCycle != null) // builder.rollCycle(RollCycles.valueOf(rollCycle)); // return builder.build(); // } // // public void setProperties(@NotNull final Properties properties, @Nullable final String prefix) { // for (final Map.Entry<Object, Object> entry : properties.entrySet()) { // final String name = entry.getKey().toString(); // final String value = entry.getValue().toString(); // // if (prefix != null && !prefix.isEmpty()) { // if (name.startsWith(prefix)) { // setProperty(name.substring(prefix.length()), value); // } // } else { // setProperty(name, value); // } // } // } // // public void setProperty(@NotNull final String propName, final String propValue) { // try { // final PropertyDescriptor property = new PropertyDescriptor(propName, this.getClass()); // final Method method = property.getWriteMethod(); // final Class<?> type = method.getParameterTypes()[0]; // // if (type == null || propValue == null || propValue.isEmpty()) { // return; // } // if (type == int.class) { // method.invoke(this, Integer.parseInt(propValue)); // // } else if (type == long.class) { // method.invoke(this, Long.parseLong(propValue)); // // } else if (type == boolean.class) { // method.invoke(this, Boolean.parseBoolean(propValue)); // // } else if (type == String.class) { // method.invoke(this, propValue); // } // } catch (Exception e) { // } // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogConfig.java // public static final String PLACEHOLDER_END = "}"; // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogConfig.java // public static final String PLACEHOLDER_START = "${"; // Path: logger-jul/src/main/java/net/openhft/chronicle/logger/jul/ChronicleHandlerConfig.java import net.openhft.chronicle.logger.LogAppenderConfig; import java.util.logging.Filter; import java.util.logging.Level; import java.util.logging.LogManager; import static net.openhft.chronicle.logger.ChronicleLogConfig.PLACEHOLDER_END; import static net.openhft.chronicle.logger.ChronicleLogConfig.PLACEHOLDER_START; if (val != null) { Class<?> clz = ClassLoader.getSystemClassLoader().loadClass(val); return (Filter) clz.newInstance(); } } catch (Exception ex) { // We got one of a variety of exceptions in creating the // class or creating an instance. // Drop through. } // We got an exception. Return the defaultValue. return defaultValue; } Level getLevelProperty(String name, Level defaultValue) { String val = getStringProperty(name, null); if (val == null) { return defaultValue; } Level l = Level.parse(val.trim()); return l != null ? l : defaultValue; } private String resolvePlaceholder(String placeholder) { int startIndex = 0; int endIndex = 0; do { startIndex = placeholder.indexOf(PLACEHOLDER_START, endIndex); if (startIndex != -1) {
endIndex = placeholder.indexOf(PLACEHOLDER_END, startIndex);
OpenHFT/Chronicle-Logger
logger-jul/src/main/java/net/openhft/chronicle/logger/jul/ChronicleLoggerManager.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogManager.java // public class ChronicleLogManager { // private ChronicleLogConfig cfg; // private Map<String, ChronicleLogWriter> writers; // // private ChronicleLogManager() { // this.cfg = ChronicleLogConfig.load(); // this.writers = new ConcurrentHashMap<>(); // } // // public static ChronicleLogManager getInstance() { // return Holder.INSTANCE; // } // // public ChronicleLogConfig cfg() { // return this.cfg; // } // // public void clear() { // for (final ChronicleLogWriter writer : writers.values()) { // try { // writer.close(); // } catch (IOException e) { // } // } // // writers.clear(); // } // // public void reload() { // clear(); // // this.cfg = ChronicleLogConfig.load(); // this.writers = new ConcurrentHashMap<>(); // } // // public ChronicleLogWriter getWriter(String name) { // if (this.cfg == null) { // throw new IllegalArgumentException("ChronicleLogManager is not configured"); // } // // final String path = cfg.getString(name, ChronicleLogConfig.KEY_PATH); // if (path != null) { // // Creating a Queue takes some time. Other threads might be blocked for longer periods. // return writers.computeIfAbsent(path, p-> new DefaultChronicleLogWriter(newChronicle(p, name))); // } else { // throw new IllegalArgumentException( // "chronicle.logger.root.path is not defined, chronicle.logger." + name + ".path is not defined" // ); // } // } // // // ************************************************************************* // // // // ************************************************************************* // // private ChronicleQueue newChronicle(String path, String name) { // final String wireType = cfg.getString(name, ChronicleLogConfig.KEY_WIRETYPE); // ChronicleQueue cq = this.cfg.getAppenderConfig().build(path, wireType); // if (!cfg.getBoolean(name, ChronicleLogConfig.KEY_APPEND, true)) { // // TODO re-enable when it's implemented. ATM it throws UnsupportedOperationException... // //cq.clear(); // } // return cq; // } // // // ************************************************************************* // // // // ************************************************************************* // // private static class Holder { // private static final ChronicleLogManager INSTANCE = new ChronicleLogManager(); // // private Holder() { // // } // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // }
import net.openhft.chronicle.logger.ChronicleLogManager; import net.openhft.chronicle.logger.ChronicleLogWriter; import java.io.IOException; import java.util.Collections; import java.util.Enumeration; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.LogManager; import java.util.logging.Logger;
/* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.jul; public class ChronicleLoggerManager extends LogManager { private final Map<String, Logger> loggers;
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogManager.java // public class ChronicleLogManager { // private ChronicleLogConfig cfg; // private Map<String, ChronicleLogWriter> writers; // // private ChronicleLogManager() { // this.cfg = ChronicleLogConfig.load(); // this.writers = new ConcurrentHashMap<>(); // } // // public static ChronicleLogManager getInstance() { // return Holder.INSTANCE; // } // // public ChronicleLogConfig cfg() { // return this.cfg; // } // // public void clear() { // for (final ChronicleLogWriter writer : writers.values()) { // try { // writer.close(); // } catch (IOException e) { // } // } // // writers.clear(); // } // // public void reload() { // clear(); // // this.cfg = ChronicleLogConfig.load(); // this.writers = new ConcurrentHashMap<>(); // } // // public ChronicleLogWriter getWriter(String name) { // if (this.cfg == null) { // throw new IllegalArgumentException("ChronicleLogManager is not configured"); // } // // final String path = cfg.getString(name, ChronicleLogConfig.KEY_PATH); // if (path != null) { // // Creating a Queue takes some time. Other threads might be blocked for longer periods. // return writers.computeIfAbsent(path, p-> new DefaultChronicleLogWriter(newChronicle(p, name))); // } else { // throw new IllegalArgumentException( // "chronicle.logger.root.path is not defined, chronicle.logger." + name + ".path is not defined" // ); // } // } // // // ************************************************************************* // // // // ************************************************************************* // // private ChronicleQueue newChronicle(String path, String name) { // final String wireType = cfg.getString(name, ChronicleLogConfig.KEY_WIRETYPE); // ChronicleQueue cq = this.cfg.getAppenderConfig().build(path, wireType); // if (!cfg.getBoolean(name, ChronicleLogConfig.KEY_APPEND, true)) { // // TODO re-enable when it's implemented. ATM it throws UnsupportedOperationException... // //cq.clear(); // } // return cq; // } // // // ************************************************************************* // // // // ************************************************************************* // // private static class Holder { // private static final ChronicleLogManager INSTANCE = new ChronicleLogManager(); // // private Holder() { // // } // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // } // Path: logger-jul/src/main/java/net/openhft/chronicle/logger/jul/ChronicleLoggerManager.java import net.openhft.chronicle.logger.ChronicleLogManager; import net.openhft.chronicle.logger.ChronicleLogWriter; import java.io.IOException; import java.util.Collections; import java.util.Enumeration; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.LogManager; import java.util.logging.Logger; /* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.jul; public class ChronicleLoggerManager extends LogManager { private final Map<String, Logger> loggers;
private final ChronicleLogManager manager;
OpenHFT/Chronicle-Logger
logger-jul/src/main/java/net/openhft/chronicle/logger/jul/ChronicleLoggerManager.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogManager.java // public class ChronicleLogManager { // private ChronicleLogConfig cfg; // private Map<String, ChronicleLogWriter> writers; // // private ChronicleLogManager() { // this.cfg = ChronicleLogConfig.load(); // this.writers = new ConcurrentHashMap<>(); // } // // public static ChronicleLogManager getInstance() { // return Holder.INSTANCE; // } // // public ChronicleLogConfig cfg() { // return this.cfg; // } // // public void clear() { // for (final ChronicleLogWriter writer : writers.values()) { // try { // writer.close(); // } catch (IOException e) { // } // } // // writers.clear(); // } // // public void reload() { // clear(); // // this.cfg = ChronicleLogConfig.load(); // this.writers = new ConcurrentHashMap<>(); // } // // public ChronicleLogWriter getWriter(String name) { // if (this.cfg == null) { // throw new IllegalArgumentException("ChronicleLogManager is not configured"); // } // // final String path = cfg.getString(name, ChronicleLogConfig.KEY_PATH); // if (path != null) { // // Creating a Queue takes some time. Other threads might be blocked for longer periods. // return writers.computeIfAbsent(path, p-> new DefaultChronicleLogWriter(newChronicle(p, name))); // } else { // throw new IllegalArgumentException( // "chronicle.logger.root.path is not defined, chronicle.logger." + name + ".path is not defined" // ); // } // } // // // ************************************************************************* // // // // ************************************************************************* // // private ChronicleQueue newChronicle(String path, String name) { // final String wireType = cfg.getString(name, ChronicleLogConfig.KEY_WIRETYPE); // ChronicleQueue cq = this.cfg.getAppenderConfig().build(path, wireType); // if (!cfg.getBoolean(name, ChronicleLogConfig.KEY_APPEND, true)) { // // TODO re-enable when it's implemented. ATM it throws UnsupportedOperationException... // //cq.clear(); // } // return cq; // } // // // ************************************************************************* // // // // ************************************************************************* // // private static class Holder { // private static final ChronicleLogManager INSTANCE = new ChronicleLogManager(); // // private Holder() { // // } // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // }
import net.openhft.chronicle.logger.ChronicleLogManager; import net.openhft.chronicle.logger.ChronicleLogWriter; import java.io.IOException; import java.util.Collections; import java.util.Enumeration; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.LogManager; import java.util.logging.Logger;
@Override public Logger getLogger(final String name) { try { return doGetLogger(name); } catch (Exception e) { System.err.println("Unable to initialize chronicle-logger-jul (" + name + ")\n " + e.getMessage()); } return ChronicleLogger.Null.INSTANCE; } @Override public Enumeration<String> getLoggerNames() { return Collections.enumeration(this.loggers.keySet()); } @Override public void reset() throws SecurityException { this.loggers.clear(); this.manager.clear(); } // ************************************************************************* // // ************************************************************************* private synchronized Logger doGetLogger(String name) throws IOException { Logger logger = loggers.get(name); if (logger == null) {
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogManager.java // public class ChronicleLogManager { // private ChronicleLogConfig cfg; // private Map<String, ChronicleLogWriter> writers; // // private ChronicleLogManager() { // this.cfg = ChronicleLogConfig.load(); // this.writers = new ConcurrentHashMap<>(); // } // // public static ChronicleLogManager getInstance() { // return Holder.INSTANCE; // } // // public ChronicleLogConfig cfg() { // return this.cfg; // } // // public void clear() { // for (final ChronicleLogWriter writer : writers.values()) { // try { // writer.close(); // } catch (IOException e) { // } // } // // writers.clear(); // } // // public void reload() { // clear(); // // this.cfg = ChronicleLogConfig.load(); // this.writers = new ConcurrentHashMap<>(); // } // // public ChronicleLogWriter getWriter(String name) { // if (this.cfg == null) { // throw new IllegalArgumentException("ChronicleLogManager is not configured"); // } // // final String path = cfg.getString(name, ChronicleLogConfig.KEY_PATH); // if (path != null) { // // Creating a Queue takes some time. Other threads might be blocked for longer periods. // return writers.computeIfAbsent(path, p-> new DefaultChronicleLogWriter(newChronicle(p, name))); // } else { // throw new IllegalArgumentException( // "chronicle.logger.root.path is not defined, chronicle.logger." + name + ".path is not defined" // ); // } // } // // // ************************************************************************* // // // // ************************************************************************* // // private ChronicleQueue newChronicle(String path, String name) { // final String wireType = cfg.getString(name, ChronicleLogConfig.KEY_WIRETYPE); // ChronicleQueue cq = this.cfg.getAppenderConfig().build(path, wireType); // if (!cfg.getBoolean(name, ChronicleLogConfig.KEY_APPEND, true)) { // // TODO re-enable when it's implemented. ATM it throws UnsupportedOperationException... // //cq.clear(); // } // return cq; // } // // // ************************************************************************* // // // // ************************************************************************* // // private static class Holder { // private static final ChronicleLogManager INSTANCE = new ChronicleLogManager(); // // private Holder() { // // } // } // } // // Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogWriter.java // public interface ChronicleLogWriter extends Closeable { // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message); // // void write( // ChronicleLogLevel level, // long timestamp, // String threadName, // String loggerName, // String message, // Throwable throwable, // Object... args); // // } // Path: logger-jul/src/main/java/net/openhft/chronicle/logger/jul/ChronicleLoggerManager.java import net.openhft.chronicle.logger.ChronicleLogManager; import net.openhft.chronicle.logger.ChronicleLogWriter; import java.io.IOException; import java.util.Collections; import java.util.Enumeration; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.LogManager; import java.util.logging.Logger; @Override public Logger getLogger(final String name) { try { return doGetLogger(name); } catch (Exception e) { System.err.println("Unable to initialize chronicle-logger-jul (" + name + ")\n " + e.getMessage()); } return ChronicleLogger.Null.INSTANCE; } @Override public Enumeration<String> getLoggerNames() { return Collections.enumeration(this.loggers.keySet()); } @Override public void reset() throws SecurityException { this.loggers.clear(); this.manager.clear(); } // ************************************************************************* // // ************************************************************************* private synchronized Logger doGetLogger(String name) throws IOException { Logger logger = loggers.get(name); if (logger == null) {
final ChronicleLogWriter writer = manager.getWriter(name);
OpenHFT/Chronicle-Logger
logger-log4j-2/src/test/java/net/openhft/chronicle/logger/log4j2/Log4j2BinaryTest.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // }
import java.nio.file.Files; import java.nio.file.Paths; import static java.lang.System.currentTimeMillis; import static org.junit.Assert.*; import net.openhft.chronicle.core.OS; import net.openhft.chronicle.core.io.IOTools; import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.queue.ChronicleQueue; import net.openhft.chronicle.wire.DocumentContext; import net.openhft.chronicle.wire.Wire; import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException;
/* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.log4j2; public class Log4j2BinaryTest extends Log4j2TestBase { @NotNull private static ChronicleQueue getChronicleQueue(String testId) { return ChronicleQueue.singleBuilder(basePath(testId)).build(); } @After public void tearDown() { IOTools.deleteDirWithFiles(rootPath()); } // ************************************************************************* // // ************************************************************************* @Test public void testConfig() { // needs to be initialised before trying to get the appender, otherwise we end up in a loop final Logger logger = LoggerFactory.getLogger(OS.class); final String appenderName = "CONF-CHRONICLE"; final org.apache.logging.log4j.core.Appender appender = getAppender(appenderName); assertNotNull(appender); assertEquals(appenderName, appender.getName()); assertTrue(appender instanceof ChronicleAppender); final ChronicleAppender ba = (ChronicleAppender) appender; assertEquals(128, ba.getChronicleConfig().getBlockSize()); assertEquals(256, ba.getChronicleConfig().getBufferCapacity()); } @Test public void testIndexedAppender() throws IOException { final String testId = "chronicle"; final String threadId = testId + "-th"; final Logger logger = LoggerFactory.getLogger(testId); Thread.currentThread().setName(threadId); Files.createDirectories(Paths.get(basePath(testId)));
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // Path: logger-log4j-2/src/test/java/net/openhft/chronicle/logger/log4j2/Log4j2BinaryTest.java import java.nio.file.Files; import java.nio.file.Paths; import static java.lang.System.currentTimeMillis; import static org.junit.Assert.*; import net.openhft.chronicle.core.OS; import net.openhft.chronicle.core.io.IOTools; import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.queue.ChronicleQueue; import net.openhft.chronicle.wire.DocumentContext; import net.openhft.chronicle.wire.Wire; import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /* * Copyright 2014-2020 chronicle.software * * http://www.chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.log4j2; public class Log4j2BinaryTest extends Log4j2TestBase { @NotNull private static ChronicleQueue getChronicleQueue(String testId) { return ChronicleQueue.singleBuilder(basePath(testId)).build(); } @After public void tearDown() { IOTools.deleteDirWithFiles(rootPath()); } // ************************************************************************* // // ************************************************************************* @Test public void testConfig() { // needs to be initialised before trying to get the appender, otherwise we end up in a loop final Logger logger = LoggerFactory.getLogger(OS.class); final String appenderName = "CONF-CHRONICLE"; final org.apache.logging.log4j.core.Appender appender = getAppender(appenderName); assertNotNull(appender); assertEquals(appenderName, appender.getName()); assertTrue(appender instanceof ChronicleAppender); final ChronicleAppender ba = (ChronicleAppender) appender; assertEquals(128, ba.getChronicleConfig().getBlockSize()); assertEquals(256, ba.getChronicleConfig().getBufferCapacity()); } @Test public void testIndexedAppender() throws IOException { final String testId = "chronicle"; final String threadId = testId + "-th"; final Logger logger = LoggerFactory.getLogger(testId); Thread.currentThread().setName(threadId); Files.createDirectories(Paths.get(basePath(testId)));
for (ChronicleLogLevel level : LOG_LEVELS) {
OpenHFT/Chronicle-Logger
logger-tools/src/main/java/net/openhft/chronicle/logger/tools/ChronicleLogReader.java
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // }
import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.queue.ChronicleQueue; import net.openhft.chronicle.queue.ExcerptTailer; import net.openhft.chronicle.wire.DocumentContext; import net.openhft.chronicle.wire.Wire; import net.openhft.chronicle.wire.WireType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.helpers.MessageFormatter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List;
/* * Copyright 2014-2017 Higher Frequency Trading * * http://chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.tools; /** * Generic tool allowing users to process Chronicle logs in their own way */ public class ChronicleLogReader { private static final SimpleDateFormat tsFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); private final ChronicleQueue cq; /** * Create reader with default wire type * * @param path the path to Chronicle Logs storage */ public ChronicleLogReader( @NotNull String path) { this(path, WireType.BINARY_LIGHT); } /** * @param path the path to Chronicle Logs storage * @param wireType Chronicle wire type. Must match the wire type specified in corresponding Chronicle Logger */ public ChronicleLogReader( @NotNull String path, @NotNull WireType wireType) { cq = ChronicleQueue.singleBuilder(path).wireType(wireType).build(); } /** * Simple {@link ChronicleLogProcessor} implementation. Prints formatted message to stdout */ public static void printf( long timestamp,
// Path: logger-core/src/main/java/net/openhft/chronicle/logger/ChronicleLogLevel.java // public enum ChronicleLogLevel { // ERROR(50, "ERROR"), // WARN(40, "WARN"), // INFO(30, "INFO"), // DEBUG(20, "DEBUG"), // TRACE(10, "TRACE"); // // /** // * Array is not cached in Java enum internals, make the single copy to prevent garbage creation // */ // private static final ChronicleLogLevel[] VALUES = values(); // // private static final int CASE_DIFF = 'A' - 'a'; // // private final int levelInt; // private final String levelStr; // // ChronicleLogLevel(int levelInt, String levelStr) { // this.levelInt = levelInt; // this.levelStr = levelStr; // } // // public static ChronicleLogLevel fromStringLevel(final CharSequence levelStr) { // if (levelStr != null) { // for (ChronicleLogLevel cll : VALUES) { // if (fastEqualsIgnoreCase(cll.levelStr, levelStr)) { // return cll; // } // } // } // // throw new IllegalArgumentException(levelStr + " not a valid level value"); // } // // /** // * Package-private for testing. // * // * @param upperCase string of A-Z characters // * @param other a {@code CharSequence} to compare // * @return {@code true} if {@code upperCase} and {@code other} equals ignore case // */ // private static boolean fastEqualsIgnoreCase(@NotNull String upperCase, @NotNull CharSequence other) { // int l; // if ((l = upperCase.length()) != other.length()) { // return false; // } // // for (int i = 0; i < l; i++) { // int uC, oC; // if ((uC = upperCase.charAt(i)) != (oC = other.charAt(i)) && (uC != oC + CASE_DIFF)) { // return false; // } // } // // return true; // } // // public boolean isHigherOrEqualTo(final ChronicleLogLevel presumablyLowerLevel) { // return levelInt >= presumablyLowerLevel.levelInt; // } // // @Override // public String toString() { // return levelStr; // } // } // Path: logger-tools/src/main/java/net/openhft/chronicle/logger/tools/ChronicleLogReader.java import net.openhft.chronicle.logger.ChronicleLogLevel; import net.openhft.chronicle.queue.ChronicleQueue; import net.openhft.chronicle.queue.ExcerptTailer; import net.openhft.chronicle.wire.DocumentContext; import net.openhft.chronicle.wire.Wire; import net.openhft.chronicle.wire.WireType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.helpers.MessageFormatter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; /* * Copyright 2014-2017 Higher Frequency Trading * * http://chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.logger.tools; /** * Generic tool allowing users to process Chronicle logs in their own way */ public class ChronicleLogReader { private static final SimpleDateFormat tsFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); private final ChronicleQueue cq; /** * Create reader with default wire type * * @param path the path to Chronicle Logs storage */ public ChronicleLogReader( @NotNull String path) { this(path, WireType.BINARY_LIGHT); } /** * @param path the path to Chronicle Logs storage * @param wireType Chronicle wire type. Must match the wire type specified in corresponding Chronicle Logger */ public ChronicleLogReader( @NotNull String path, @NotNull WireType wireType) { cq = ChronicleQueue.singleBuilder(path).wireType(wireType).build(); } /** * Simple {@link ChronicleLogProcessor} implementation. Prints formatted message to stdout */ public static void printf( long timestamp,
ChronicleLogLevel level,
talklittle/reddit-is-fun
src/com/andrewshu/android/reddit/threads/ShowThumbnailsTask.java
// Path: src/com/andrewshu/android/reddit/common/util/StringUtils.java // public class StringUtils { // // public static boolean isEmpty(CharSequence s) { // return s == null || "".equals(s); // } // // public static boolean listContainsIgnoreCase(ArrayList<String> list, String str){ // for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) { // String string = (String) iterator.next(); // // if(string.equalsIgnoreCase(str)) // return true; // } // return false; // } // // } // // Path: src/com/andrewshu/android/reddit/threads/ShowThumbnailsTask.java // public static class ThumbnailLoadAction { // public ThingInfo thingInfo; // public ImageView imageView; // prefer imageView; if it's null, use threadIndex // public int threadIndex; // public ThumbnailLoadAction(ThingInfo thingInfo, ImageView imageView, int threadIndex) { // this.thingInfo = thingInfo; // this.imageView = imageView; // this.threadIndex = threadIndex; // } // }
import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.net.MalformedURLException; import java.util.HashMap; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import android.app.ListActivity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.Log; import android.view.View; import android.widget.ImageView; import com.andrewshu.android.reddit.R; import com.andrewshu.android.reddit.common.util.StringUtils; import com.andrewshu.android.reddit.things.ThingInfo; import com.andrewshu.android.reddit.threads.ShowThumbnailsTask.ThumbnailLoadAction;
private static final String TAG = "ShowThumbnailsTask"; public ShowThumbnailsTask(ListActivity activity, HttpClient client, Integer defaultThumbnailResource) { this.mActivity = activity; this.mClient = client; this.mDefaultThumbnailResource = defaultThumbnailResource; } public static class ThumbnailLoadAction { public ThingInfo thingInfo; public ImageView imageView; // prefer imageView; if it's null, use threadIndex public int threadIndex; public ThumbnailLoadAction(ThingInfo thingInfo, ImageView imageView, int threadIndex) { this.thingInfo = thingInfo; this.imageView = imageView; this.threadIndex = threadIndex; } } @Override protected Void doInBackground(ThumbnailLoadAction... thumbnailLoadActions) { for (ThumbnailLoadAction thumbnailLoadAction : thumbnailLoadActions) { loadThumbnail(thumbnailLoadAction.thingInfo); publishProgress(thumbnailLoadAction); } return null; } // TODO use external storage cache if present private void loadThumbnail(ThingInfo thingInfo) {
// Path: src/com/andrewshu/android/reddit/common/util/StringUtils.java // public class StringUtils { // // public static boolean isEmpty(CharSequence s) { // return s == null || "".equals(s); // } // // public static boolean listContainsIgnoreCase(ArrayList<String> list, String str){ // for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) { // String string = (String) iterator.next(); // // if(string.equalsIgnoreCase(str)) // return true; // } // return false; // } // // } // // Path: src/com/andrewshu/android/reddit/threads/ShowThumbnailsTask.java // public static class ThumbnailLoadAction { // public ThingInfo thingInfo; // public ImageView imageView; // prefer imageView; if it's null, use threadIndex // public int threadIndex; // public ThumbnailLoadAction(ThingInfo thingInfo, ImageView imageView, int threadIndex) { // this.thingInfo = thingInfo; // this.imageView = imageView; // this.threadIndex = threadIndex; // } // } // Path: src/com/andrewshu/android/reddit/threads/ShowThumbnailsTask.java import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.net.MalformedURLException; import java.util.HashMap; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import android.app.ListActivity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.Log; import android.view.View; import android.widget.ImageView; import com.andrewshu.android.reddit.R; import com.andrewshu.android.reddit.common.util.StringUtils; import com.andrewshu.android.reddit.things.ThingInfo; import com.andrewshu.android.reddit.threads.ShowThumbnailsTask.ThumbnailLoadAction; private static final String TAG = "ShowThumbnailsTask"; public ShowThumbnailsTask(ListActivity activity, HttpClient client, Integer defaultThumbnailResource) { this.mActivity = activity; this.mClient = client; this.mDefaultThumbnailResource = defaultThumbnailResource; } public static class ThumbnailLoadAction { public ThingInfo thingInfo; public ImageView imageView; // prefer imageView; if it's null, use threadIndex public int threadIndex; public ThumbnailLoadAction(ThingInfo thingInfo, ImageView imageView, int threadIndex) { this.thingInfo = thingInfo; this.imageView = imageView; this.threadIndex = threadIndex; } } @Override protected Void doInBackground(ThumbnailLoadAction... thumbnailLoadActions) { for (ThumbnailLoadAction thumbnailLoadAction : thumbnailLoadActions) { loadThumbnail(thumbnailLoadAction.thingInfo); publishProgress(thumbnailLoadAction); } return null; } // TODO use external storage cache if present private void loadThumbnail(ThingInfo thingInfo) {
if ("default".equals(thingInfo.getThumbnail()) || "self".equals(thingInfo.getThumbnail()) || StringUtils.isEmpty(thingInfo.getThumbnail())) {
talklittle/reddit-is-fun
src/com/andrewshu/android/reddit/common/RedditIsFunHttpClientFactory.java
// Path: src/com/andrewshu/android/reddit/RedditIsFunApplication.java // public class RedditIsFunApplication extends Application { // private static RedditIsFunApplication application; // // public RedditIsFunApplication(){ // application = this; // } // // public static RedditIsFunApplication getApplication(){ // return application; // } // }
import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.zip.GZIPInputStream; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpVersion; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HttpContext; import android.content.Context; import android.content.pm.PackageManager.NameNotFoundException; import android.util.Log; import com.andrewshu.android.reddit.R; import com.andrewshu.android.reddit.RedditIsFunApplication;
package com.andrewshu.android.reddit.common; public class RedditIsFunHttpClientFactory { private static final String TAG = "RedditIsFunHttpClientFactory"; private static final DefaultHttpClient mGzipHttpClient = createGzipHttpClient(); private static final CookieStore mCookieStore = mGzipHttpClient.getCookieStore(); // Default connection and socket timeout of 60 seconds. Tweak to taste. private static final int SOCKET_OPERATION_TIMEOUT = 60 * 1000; static DefaultHttpClient createGzipHttpClient() { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); DefaultHttpClient httpclient = new DefaultHttpClient(params) { @Override protected ClientConnectionManager createClientConnectionManager() { SchemeRegistry registry = new SchemeRegistry(); registry.register( new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register( new Scheme("https", getHttpsSocketFactory(), 443)); HttpParams params = getParams(); HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT); HttpConnectionParams.setSocketBufferSize(params, 8192); return new ThreadSafeClientConnManager(params, registry); } /** Gets an HTTPS socket factory with SSL Session Caching if such support is available, otherwise falls back to a non-caching factory * @return */ protected SocketFactory getHttpsSocketFactory(){ try { Class<?> sslSessionCacheClass = Class.forName("android.net.SSLSessionCache");
// Path: src/com/andrewshu/android/reddit/RedditIsFunApplication.java // public class RedditIsFunApplication extends Application { // private static RedditIsFunApplication application; // // public RedditIsFunApplication(){ // application = this; // } // // public static RedditIsFunApplication getApplication(){ // return application; // } // } // Path: src/com/andrewshu/android/reddit/common/RedditIsFunHttpClientFactory.java import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.zip.GZIPInputStream; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpVersion; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HttpContext; import android.content.Context; import android.content.pm.PackageManager.NameNotFoundException; import android.util.Log; import com.andrewshu.android.reddit.R; import com.andrewshu.android.reddit.RedditIsFunApplication; package com.andrewshu.android.reddit.common; public class RedditIsFunHttpClientFactory { private static final String TAG = "RedditIsFunHttpClientFactory"; private static final DefaultHttpClient mGzipHttpClient = createGzipHttpClient(); private static final CookieStore mCookieStore = mGzipHttpClient.getCookieStore(); // Default connection and socket timeout of 60 seconds. Tweak to taste. private static final int SOCKET_OPERATION_TIMEOUT = 60 * 1000; static DefaultHttpClient createGzipHttpClient() { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); DefaultHttpClient httpclient = new DefaultHttpClient(params) { @Override protected ClientConnectionManager createClientConnectionManager() { SchemeRegistry registry = new SchemeRegistry(); registry.register( new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register( new Scheme("https", getHttpsSocketFactory(), 443)); HttpParams params = getParams(); HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT); HttpConnectionParams.setSocketBufferSize(params, 8192); return new ThreadSafeClientConnManager(params, registry); } /** Gets an HTTPS socket factory with SSL Session Caching if such support is available, otherwise falls back to a non-caching factory * @return */ protected SocketFactory getHttpsSocketFactory(){ try { Class<?> sslSessionCacheClass = Class.forName("android.net.SSLSessionCache");
Object sslSessionCache = sslSessionCacheClass.getConstructor(Context.class).newInstance(RedditIsFunApplication.getApplication());
alphagov/locate-api
locate-api-service/src/main/java/uk/gov/gds/locate/api/validation/ValidateQuery.java
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/model/QueryType.java // public enum QueryType { // ELECTORAL("electoral", new Predicate<Address>() { // @Override // public boolean apply(@Nullable Address input) { // return input.getDetails().getIsElectoral() && input.getDetails().getIsPostalAddress(); // } // }), // RESIDENTIAL("residential", new Predicate<Address>() { // @Override // public boolean apply(@Nullable Address input) { // return input.getDetails().getIsResidential() && input.getDetails().getIsPostalAddress(); // } // }), // COMMERCIAL("commercial", new Predicate<Address>() { // @Override // public boolean apply(@Nullable Address input) { // return input.getDetails().getIsCommercial() && input.getDetails().getIsPostalAddress(); // } // }), // RESIDENTIAL_AND_COMMERCIAL("residentialAndCommercial", new Predicate<Address>() { // @Override // public boolean apply(@Nullable Address input) { // return (input.getDetails().getIsCommercial() || input.getDetails().getIsResidential()) && input.getDetails().getIsPostalAddress(); // } // }), // ALL("all", new Predicate<Address>() { // @Override // public boolean apply(@Nullable Address input) { // return true; // } // }); // private final Predicate<Address> predicate; // private String type; // // private QueryType(String type, Predicate<Address> predicate) { // this.type = type; // this.predicate = predicate; // } // // public static QueryType parse(String value) throws IllegalArgumentException { // for (QueryType queryType : QueryType.values()) { // if (queryType.getType().equals(value)) { // return queryType; // } // } // return ALL; // } // // public static Boolean isValid(String check) { // for (QueryType queryType : QueryType.values()) { // if (queryType.getType().equals(check)) { // return true; // } // } // return false; // // } // // public String getType() { // return this.type; // } // // public Predicate<Address> predicate() { // return this.predicate; // } // // }
import com.google.common.base.Strings; import uk.gov.gds.locate.api.model.QueryType;
package uk.gov.gds.locate.api.validation; public class ValidateQuery { public static Boolean isValid(String query) {
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/model/QueryType.java // public enum QueryType { // ELECTORAL("electoral", new Predicate<Address>() { // @Override // public boolean apply(@Nullable Address input) { // return input.getDetails().getIsElectoral() && input.getDetails().getIsPostalAddress(); // } // }), // RESIDENTIAL("residential", new Predicate<Address>() { // @Override // public boolean apply(@Nullable Address input) { // return input.getDetails().getIsResidential() && input.getDetails().getIsPostalAddress(); // } // }), // COMMERCIAL("commercial", new Predicate<Address>() { // @Override // public boolean apply(@Nullable Address input) { // return input.getDetails().getIsCommercial() && input.getDetails().getIsPostalAddress(); // } // }), // RESIDENTIAL_AND_COMMERCIAL("residentialAndCommercial", new Predicate<Address>() { // @Override // public boolean apply(@Nullable Address input) { // return (input.getDetails().getIsCommercial() || input.getDetails().getIsResidential()) && input.getDetails().getIsPostalAddress(); // } // }), // ALL("all", new Predicate<Address>() { // @Override // public boolean apply(@Nullable Address input) { // return true; // } // }); // private final Predicate<Address> predicate; // private String type; // // private QueryType(String type, Predicate<Address> predicate) { // this.type = type; // this.predicate = predicate; // } // // public static QueryType parse(String value) throws IllegalArgumentException { // for (QueryType queryType : QueryType.values()) { // if (queryType.getType().equals(value)) { // return queryType; // } // } // return ALL; // } // // public static Boolean isValid(String check) { // for (QueryType queryType : QueryType.values()) { // if (queryType.getType().equals(check)) { // return true; // } // } // return false; // // } // // public String getType() { // return this.type; // } // // public Predicate<Address> predicate() { // return this.predicate; // } // // } // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/validation/ValidateQuery.java import com.google.common.base.Strings; import uk.gov.gds.locate.api.model.QueryType; package uk.gov.gds.locate.api.validation; public class ValidateQuery { public static Boolean isValid(String query) {
return Strings.isNullOrEmpty(query) || QueryType.isValid(query);
alphagov/locate-api
locate-api-service/src/test/uk/gov/gds/locate/api/helpers/DetailsBuilder.java
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/model/Details.java // @JsonInclude(JsonInclude.Include.NON_NULL) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Details { // // @JsonProperty("blpuCreatedAt") // private Date blpuCreatedAt; // // @JsonProperty("blpuUpdatedAt") // private Date blpuUpdatedAt; // // @JsonProperty("classification") // private String classification; // // @JsonProperty("state") // private String state; // // @JsonProperty("isPostalAddress") // private Boolean isPostalAddress; // // @JsonProperty("isCommercial") // private Boolean isCommercial; // // @JsonProperty("isResidential") // private Boolean isResidential; // // @JsonProperty("isHigherEducational") // private Boolean isHigherEducational; // // @JsonProperty("isElectoral") // private Boolean isElectoral; // // @JsonProperty("usrn") // private String usrn; // // @JsonProperty("file") // private String file; // // @JsonProperty("primaryClassification") // private String primaryClassification; // // @JsonProperty("secondaryClassification") // private String secondaryClassification; // // public Details() { // } // // public Details(Date blpuCreatedAt, // Date blpuUpdatedAt, // String classification, // String state, // Boolean isPostalAddress, // Boolean isCommercial, // Boolean isResidential, // Boolean isHigherEducational, // Boolean isElectoral, // String usrn, // String file, // String primaryClassification, // String secondaryClassification) { // // this.blpuCreatedAt = blpuCreatedAt; // this.blpuUpdatedAt = blpuUpdatedAt; // this.classification = classification; // this.state = state; // this.isPostalAddress = isPostalAddress; // this.isCommercial = isCommercial; // this.isResidential = isResidential; // this.isHigherEducational = isHigherEducational; // this.isElectoral = isElectoral; // this.usrn = usrn; // this.file = file; // this.primaryClassification = primaryClassification; // this.secondaryClassification = secondaryClassification; // } // // public Date getBlpuCreatedAt() { // return blpuCreatedAt; // } // // public Date getBlpuUpdatedAt() { // return blpuUpdatedAt; // } // // public String getClassification() { // return classification; // } // // public String getState() { // return state; // } // // public Boolean getIsPostalAddress() { // return isPostalAddress; // } // // public Boolean getIsCommercial() { // return isCommercial; // } // // public Boolean getIsResidential() { // return isResidential; // } // // public Boolean getIsHigherEducational() { // return isHigherEducational; // } // // public Boolean getIsElectoral() { // return isElectoral; // } // // public String getUsrn() { // return usrn; // } // // public String getFile() { // return file; // } // // public String getPrimaryClassification() { // return primaryClassification; // } // // public String getSecondaryClassification() { // return secondaryClassification; // } // // @Override // public String toString() { // return "Details{" + // "blpuCreatedAt=" + blpuCreatedAt + // ", blpuUpdatedAt=" + blpuUpdatedAt + // ", classification='" + classification + '\'' + // ", state='" + state + '\'' + // ", isPostalAddress=" + isPostalAddress + // ", isCommercial=" + isCommercial + // ", isResidential=" + isResidential + // ", isHigherEducational=" + isHigherEducational + // ", isElectoral=" + isElectoral + // ", usrn='" + usrn + '\'' + // ", file='" + file + '\'' + // ", primaryClassification='" + primaryClassification + '\'' + // ", secondaryClassification='" + secondaryClassification + '\'' + // '}'; // } // }
import uk.gov.gds.locate.api.model.Details; import java.util.Date;
file = "file-" + suffix; primaryClassification = "primaryClassification-" + suffix; secondaryClassification = "secondaryClassification-" + suffix; } public DetailsBuilder postal(Boolean isPostalAddress) { this.isPostalAddress = isPostalAddress; return this; } public DetailsBuilder residential(Boolean isResidential) { this.isResidential = isResidential; return this; } public DetailsBuilder commercial(Boolean isCommercial) { this.isCommercial = isCommercial; return this; } public DetailsBuilder electoral(Boolean isElectoral) { this.isElectoral = isElectoral; return this; } public DetailsBuilder higherEducational(Boolean isHigherEducational) { this.isHigherEducational = isHigherEducational; return this; }
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/model/Details.java // @JsonInclude(JsonInclude.Include.NON_NULL) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Details { // // @JsonProperty("blpuCreatedAt") // private Date blpuCreatedAt; // // @JsonProperty("blpuUpdatedAt") // private Date blpuUpdatedAt; // // @JsonProperty("classification") // private String classification; // // @JsonProperty("state") // private String state; // // @JsonProperty("isPostalAddress") // private Boolean isPostalAddress; // // @JsonProperty("isCommercial") // private Boolean isCommercial; // // @JsonProperty("isResidential") // private Boolean isResidential; // // @JsonProperty("isHigherEducational") // private Boolean isHigherEducational; // // @JsonProperty("isElectoral") // private Boolean isElectoral; // // @JsonProperty("usrn") // private String usrn; // // @JsonProperty("file") // private String file; // // @JsonProperty("primaryClassification") // private String primaryClassification; // // @JsonProperty("secondaryClassification") // private String secondaryClassification; // // public Details() { // } // // public Details(Date blpuCreatedAt, // Date blpuUpdatedAt, // String classification, // String state, // Boolean isPostalAddress, // Boolean isCommercial, // Boolean isResidential, // Boolean isHigherEducational, // Boolean isElectoral, // String usrn, // String file, // String primaryClassification, // String secondaryClassification) { // // this.blpuCreatedAt = blpuCreatedAt; // this.blpuUpdatedAt = blpuUpdatedAt; // this.classification = classification; // this.state = state; // this.isPostalAddress = isPostalAddress; // this.isCommercial = isCommercial; // this.isResidential = isResidential; // this.isHigherEducational = isHigherEducational; // this.isElectoral = isElectoral; // this.usrn = usrn; // this.file = file; // this.primaryClassification = primaryClassification; // this.secondaryClassification = secondaryClassification; // } // // public Date getBlpuCreatedAt() { // return blpuCreatedAt; // } // // public Date getBlpuUpdatedAt() { // return blpuUpdatedAt; // } // // public String getClassification() { // return classification; // } // // public String getState() { // return state; // } // // public Boolean getIsPostalAddress() { // return isPostalAddress; // } // // public Boolean getIsCommercial() { // return isCommercial; // } // // public Boolean getIsResidential() { // return isResidential; // } // // public Boolean getIsHigherEducational() { // return isHigherEducational; // } // // public Boolean getIsElectoral() { // return isElectoral; // } // // public String getUsrn() { // return usrn; // } // // public String getFile() { // return file; // } // // public String getPrimaryClassification() { // return primaryClassification; // } // // public String getSecondaryClassification() { // return secondaryClassification; // } // // @Override // public String toString() { // return "Details{" + // "blpuCreatedAt=" + blpuCreatedAt + // ", blpuUpdatedAt=" + blpuUpdatedAt + // ", classification='" + classification + '\'' + // ", state='" + state + '\'' + // ", isPostalAddress=" + isPostalAddress + // ", isCommercial=" + isCommercial + // ", isResidential=" + isResidential + // ", isHigherEducational=" + isHigherEducational + // ", isElectoral=" + isElectoral + // ", usrn='" + usrn + '\'' + // ", file='" + file + '\'' + // ", primaryClassification='" + primaryClassification + '\'' + // ", secondaryClassification='" + secondaryClassification + '\'' + // '}'; // } // } // Path: locate-api-service/src/test/uk/gov/gds/locate/api/helpers/DetailsBuilder.java import uk.gov.gds.locate.api.model.Details; import java.util.Date; file = "file-" + suffix; primaryClassification = "primaryClassification-" + suffix; secondaryClassification = "secondaryClassification-" + suffix; } public DetailsBuilder postal(Boolean isPostalAddress) { this.isPostalAddress = isPostalAddress; return this; } public DetailsBuilder residential(Boolean isResidential) { this.isResidential = isResidential; return this; } public DetailsBuilder commercial(Boolean isCommercial) { this.isCommercial = isCommercial; return this; } public DetailsBuilder electoral(Boolean isElectoral) { this.isElectoral = isElectoral; return this; } public DetailsBuilder higherEducational(Boolean isHigherEducational) { this.isHigherEducational = isHigherEducational; return this; }
public Details build() {
alphagov/locate-api
locate-api-service/src/test/uk/gov/gds/locate/api/helpers/PresentationBuilder.java
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/model/Presentation.java // @JsonInclude(JsonInclude.Include.NON_NULL) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Presentation { // // @JsonProperty("property") // private String property; // // @JsonProperty("street") // private String street; // // @JsonProperty("locality") // private String locality; // // @JsonProperty("town") // private String town; // // @JsonProperty("area") // private String area; // // @JsonProperty("postcode") // private String postcode; // // public Presentation() { // } // // public Presentation(String property, String street, String locality, String town, String area, String postcode) { // this.property = property; // this.street = street; // this.locality = locality; // this.town = town; // this.area = area; // this.postcode = postcode; // } // // public String getProperty() { // return property; // } // // public String getStreet() { // return street; // } // // public String getLocality() { // return locality; // } // // public String getTown() { // return town; // } // // public String getArea() { // return area; // } // // public String getPostcode() { // return postcode; // } // // public Presentation decrypt(String key, String iv) { // try { // return new Presentation( // Strings.isNullOrEmpty(this.property) ? this.property : AesEncryptionService.decrypt(this.property, key, iv), // Strings.isNullOrEmpty(this.street) ? this.street : AesEncryptionService.decrypt(this.street, key, iv), // Strings.isNullOrEmpty(this.locality) ? this.locality : AesEncryptionService.decrypt(this.locality, key, iv), // Strings.isNullOrEmpty(this.town) ? this.town : AesEncryptionService.decrypt(this.town, key, iv), // Strings.isNullOrEmpty(this.area) ? this.area : AesEncryptionService.decrypt(this.area, key, iv), // this.postcode // ); // } catch (Exception e) { // return this; // } // } // }
import uk.gov.gds.locate.api.model.Presentation;
this.town = "town-" + suffix; this.area = "area-" + suffix; this.postcode = "postcode-" + suffix; } public PresentationBuilder property(String p) { this.property = p; return this; } public PresentationBuilder street(String p) { this.street = p; return this; } public PresentationBuilder locality(String p) { this.locality = p; return this; } public PresentationBuilder town(String p) { this.town = p; return this; } public PresentationBuilder area(String p) { this.area = p; return this; }
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/model/Presentation.java // @JsonInclude(JsonInclude.Include.NON_NULL) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Presentation { // // @JsonProperty("property") // private String property; // // @JsonProperty("street") // private String street; // // @JsonProperty("locality") // private String locality; // // @JsonProperty("town") // private String town; // // @JsonProperty("area") // private String area; // // @JsonProperty("postcode") // private String postcode; // // public Presentation() { // } // // public Presentation(String property, String street, String locality, String town, String area, String postcode) { // this.property = property; // this.street = street; // this.locality = locality; // this.town = town; // this.area = area; // this.postcode = postcode; // } // // public String getProperty() { // return property; // } // // public String getStreet() { // return street; // } // // public String getLocality() { // return locality; // } // // public String getTown() { // return town; // } // // public String getArea() { // return area; // } // // public String getPostcode() { // return postcode; // } // // public Presentation decrypt(String key, String iv) { // try { // return new Presentation( // Strings.isNullOrEmpty(this.property) ? this.property : AesEncryptionService.decrypt(this.property, key, iv), // Strings.isNullOrEmpty(this.street) ? this.street : AesEncryptionService.decrypt(this.street, key, iv), // Strings.isNullOrEmpty(this.locality) ? this.locality : AesEncryptionService.decrypt(this.locality, key, iv), // Strings.isNullOrEmpty(this.town) ? this.town : AesEncryptionService.decrypt(this.town, key, iv), // Strings.isNullOrEmpty(this.area) ? this.area : AesEncryptionService.decrypt(this.area, key, iv), // this.postcode // ); // } catch (Exception e) { // return this; // } // } // } // Path: locate-api-service/src/test/uk/gov/gds/locate/api/helpers/PresentationBuilder.java import uk.gov.gds.locate.api.model.Presentation; this.town = "town-" + suffix; this.area = "area-" + suffix; this.postcode = "postcode-" + suffix; } public PresentationBuilder property(String p) { this.property = p; return this; } public PresentationBuilder street(String p) { this.street = p; return this; } public PresentationBuilder locality(String p) { this.locality = p; return this; } public PresentationBuilder town(String p) { this.town = p; return this; } public PresentationBuilder area(String p) { this.area = p; return this; }
public Presentation build() {
alphagov/locate-api
locate-api-service/src/main/java/uk/gov/gds/locate/api/validation/ValidateFormat.java
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/model/Format.java // public enum Format { // ALL("all"), // VCARD("vcard"), // PRESENTATION("presentation"); // // private String type; // // private Format(String type) { // this.type = type; // } // // public static Format parse(String value) throws IllegalArgumentException { // for (Format format : Format.values()) { // if (format.getType().equals(value)) { // return format; // } // } // throw new IllegalArgumentException(String.format("No QueryType with value '%s'", value)); // } // // public static Boolean isValid(String check) { // for (Format format : Format.values()) { // if (format.getType().equals(check)) { // return true; // } // } // return false; // // } // // public String getType() { // return this.type; // } // }
import com.google.common.base.Strings; import uk.gov.gds.locate.api.model.Format;
package uk.gov.gds.locate.api.validation; public abstract class ValidateFormat { public static Boolean isValid(String format) {
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/model/Format.java // public enum Format { // ALL("all"), // VCARD("vcard"), // PRESENTATION("presentation"); // // private String type; // // private Format(String type) { // this.type = type; // } // // public static Format parse(String value) throws IllegalArgumentException { // for (Format format : Format.values()) { // if (format.getType().equals(value)) { // return format; // } // } // throw new IllegalArgumentException(String.format("No QueryType with value '%s'", value)); // } // // public static Boolean isValid(String check) { // for (Format format : Format.values()) { // if (format.getType().equals(check)) { // return true; // } // } // return false; // // } // // public String getType() { // return this.type; // } // } // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/validation/ValidateFormat.java import com.google.common.base.Strings; import uk.gov.gds.locate.api.model.Format; package uk.gov.gds.locate.api.validation; public abstract class ValidateFormat { public static Boolean isValid(String format) {
return Strings.isNullOrEmpty(format) || Format.isValid(format);
alphagov/locate-api
locate-api-service/src/test/uk/gov/gds/locate/api/tasks/MongoIndexTaskTest.java
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/dao/AuthorizationTokenDao.java // public class AuthorizationTokenDao { // // private final JacksonDBCollection<AuthorizationToken, String> authorizationTokens; // // public AuthorizationTokenDao(JacksonDBCollection<AuthorizationToken, String> authorizationTokens) { // this.authorizationTokens = authorizationTokens; // } // // @Timed // public AuthorizationToken fetchCredentialsByBearerToken(String token) { // return authorizationTokens.findOne(new BasicDBObject("token", token)); // } // // @Timed // public Boolean create(AuthorizationToken authorizationToken) { // return authorizationTokens.insert(authorizationToken).getN() == 1; // } // // @Timed // public void applyIndexes() { // authorizationTokens.ensureIndex(new BasicDBObject("token", 1), "token_index", true); // authorizationTokens.ensureIndex(new BasicDBObject("identifier", 1), "identifier_index", true); // } // } // // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/dao/UsageDao.java // public class UsageDao { // // private final JacksonDBCollection<Usage, String> collection; // // public UsageDao(JacksonDBCollection<Usage, String> collection) { // this.collection = collection; // } // // @Timed // public Optional<Usage> findUsageByIdentifier(String identifier) { // return Optional.fromNullable(collection.findAndModify(new BasicDBObject("identifier", identifier), new DBUpdate.Builder().inc("count"))); // } // // @Timed // public Boolean create(String identifier) { // Date expiry = DateTime.now().withZone(DateTimeZone.UTC).withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59).withMillisOfSecond(999).toDate(); // return collection.insert(new Usage(org.bson.types.ObjectId.get().toString(), identifier, 1, expiry)).getN() == 1; // } // // @Timed // public void applyIndexes() { // collection.ensureIndex(new BasicDBObject("identifier", 1), "identifier_index", true); // collection.ensureIndex(new BasicDBObject("expireAt", 1), new BasicDBObject("expireAfterSeconds", 0)); // } // }
import com.google.common.collect.ImmutableMultimap; import org.junit.Test; import uk.gov.gds.locate.api.dao.AuthorizationTokenDao; import uk.gov.gds.locate.api.dao.UsageDao; import java.io.PrintWriter; import static org.mockito.Mockito.*;
package uk.gov.gds.locate.api.tasks; public class MongoIndexTaskTest { private AuthorizationTokenDao authorizationTokenDao = mock(AuthorizationTokenDao.class);
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/dao/AuthorizationTokenDao.java // public class AuthorizationTokenDao { // // private final JacksonDBCollection<AuthorizationToken, String> authorizationTokens; // // public AuthorizationTokenDao(JacksonDBCollection<AuthorizationToken, String> authorizationTokens) { // this.authorizationTokens = authorizationTokens; // } // // @Timed // public AuthorizationToken fetchCredentialsByBearerToken(String token) { // return authorizationTokens.findOne(new BasicDBObject("token", token)); // } // // @Timed // public Boolean create(AuthorizationToken authorizationToken) { // return authorizationTokens.insert(authorizationToken).getN() == 1; // } // // @Timed // public void applyIndexes() { // authorizationTokens.ensureIndex(new BasicDBObject("token", 1), "token_index", true); // authorizationTokens.ensureIndex(new BasicDBObject("identifier", 1), "identifier_index", true); // } // } // // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/dao/UsageDao.java // public class UsageDao { // // private final JacksonDBCollection<Usage, String> collection; // // public UsageDao(JacksonDBCollection<Usage, String> collection) { // this.collection = collection; // } // // @Timed // public Optional<Usage> findUsageByIdentifier(String identifier) { // return Optional.fromNullable(collection.findAndModify(new BasicDBObject("identifier", identifier), new DBUpdate.Builder().inc("count"))); // } // // @Timed // public Boolean create(String identifier) { // Date expiry = DateTime.now().withZone(DateTimeZone.UTC).withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59).withMillisOfSecond(999).toDate(); // return collection.insert(new Usage(org.bson.types.ObjectId.get().toString(), identifier, 1, expiry)).getN() == 1; // } // // @Timed // public void applyIndexes() { // collection.ensureIndex(new BasicDBObject("identifier", 1), "identifier_index", true); // collection.ensureIndex(new BasicDBObject("expireAt", 1), new BasicDBObject("expireAfterSeconds", 0)); // } // } // Path: locate-api-service/src/test/uk/gov/gds/locate/api/tasks/MongoIndexTaskTest.java import com.google.common.collect.ImmutableMultimap; import org.junit.Test; import uk.gov.gds.locate.api.dao.AuthorizationTokenDao; import uk.gov.gds.locate.api.dao.UsageDao; import java.io.PrintWriter; import static org.mockito.Mockito.*; package uk.gov.gds.locate.api.tasks; public class MongoIndexTaskTest { private AuthorizationTokenDao authorizationTokenDao = mock(AuthorizationTokenDao.class);
private UsageDao usageDao = mock(UsageDao.class);
alphagov/locate-api
locate-api-service/src/main/java/uk/gov/gds/locate/api/authentication/BearerTokenAuthProvider.java
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/configuration/LocateApiConfiguration.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class LocateApiConfiguration extends Configuration { // // @Valid // @NotNull // @JsonProperty // private MongoConfiguration mongoConfiguration = new MongoConfiguration(); // // @Valid // @NotNull // @JsonProperty // private Integer maxRequestsPerDay; // // @Valid // @NotNull // @JsonProperty // private String encryptionKey; // // @Valid // @NotNull // @JsonProperty // private Boolean encrypted; // // @Valid // @NotNull // @JsonProperty // private String allowedOrigins; // // public MongoConfiguration getMongoConfiguration() { // return mongoConfiguration; // } // // public Integer getMaxRequestsPerDay() { // return maxRequestsPerDay; // } // // public String getEncryptionKey() { // return encryptionKey; // } // // public Boolean getEncrypted() { // return encrypted; // } // // public String getAllowedOrigins() { // return allowedOrigins; // } // // @Override // public String toString() { // return "LocateApiConfiguration{" + // "mongoConfiguration=" + mongoConfiguration + // ", maxRequestsPerDay=" + maxRequestsPerDay + // ", encryptionKey='" + encryptionKey + '\'' + // ", encrypted=" + encrypted + // ", allowedOrigins='" + allowedOrigins + '\'' + // '}'; // } // } // // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/dao/UsageDao.java // public class UsageDao { // // private final JacksonDBCollection<Usage, String> collection; // // public UsageDao(JacksonDBCollection<Usage, String> collection) { // this.collection = collection; // } // // @Timed // public Optional<Usage> findUsageByIdentifier(String identifier) { // return Optional.fromNullable(collection.findAndModify(new BasicDBObject("identifier", identifier), new DBUpdate.Builder().inc("count"))); // } // // @Timed // public Boolean create(String identifier) { // Date expiry = DateTime.now().withZone(DateTimeZone.UTC).withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59).withMillisOfSecond(999).toDate(); // return collection.insert(new Usage(org.bson.types.ObjectId.get().toString(), identifier, 1, expiry)).getN() == 1; // } // // @Timed // public void applyIndexes() { // collection.ensureIndex(new BasicDBObject("identifier", 1), "identifier_index", true); // collection.ensureIndex(new BasicDBObject("expireAt", 1), new BasicDBObject("expireAfterSeconds", 0)); // } // } // // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/model/AuthorizationToken.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class AuthorizationToken { // // @JsonProperty("_id") // @ObjectId // private String id; // // @JsonProperty("name") // private String name; // // @JsonProperty("identifier") // private String identifier; // // @JsonProperty("organisation") // private String organisation; // // @JsonProperty("token") // private String token; // // public AuthorizationToken() { // } // // public AuthorizationToken(String id, String name, String identifier, String organisation, String token) { // this.id = id; // this.name = name; // this.identifier = identifier; // this.organisation = organisation; // this.token = token; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public String getIdentifier() { // return identifier; // } // // public String getOrganisation() { // return organisation; // } // // public String getToken() { // return token; // } // // @Override // public String toString() { // return "AuthorizationToken{" + // "id='" + id + '\'' + // ", name='" + name + '\'' + // ", identifier='" + identifier + '\'' + // ", organisation='" + organisation + '\'' + // ", token='" + token + '\'' + // '}'; // } // }
import com.sun.jersey.api.model.Parameter; import com.sun.jersey.core.spi.component.ComponentContext; import com.sun.jersey.core.spi.component.ComponentScope; import com.sun.jersey.spi.inject.Injectable; import com.sun.jersey.spi.inject.InjectableProvider; import com.yammer.dropwizard.auth.Auth; import com.yammer.dropwizard.auth.Authenticator; import uk.gov.gds.locate.api.configuration.LocateApiConfiguration; import uk.gov.gds.locate.api.dao.UsageDao; import uk.gov.gds.locate.api.model.AuthorizationToken;
package uk.gov.gds.locate.api.authentication; public class BearerTokenAuthProvider implements InjectableProvider<Auth, Parameter> { private final LocateApiConfiguration configuration;
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/configuration/LocateApiConfiguration.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class LocateApiConfiguration extends Configuration { // // @Valid // @NotNull // @JsonProperty // private MongoConfiguration mongoConfiguration = new MongoConfiguration(); // // @Valid // @NotNull // @JsonProperty // private Integer maxRequestsPerDay; // // @Valid // @NotNull // @JsonProperty // private String encryptionKey; // // @Valid // @NotNull // @JsonProperty // private Boolean encrypted; // // @Valid // @NotNull // @JsonProperty // private String allowedOrigins; // // public MongoConfiguration getMongoConfiguration() { // return mongoConfiguration; // } // // public Integer getMaxRequestsPerDay() { // return maxRequestsPerDay; // } // // public String getEncryptionKey() { // return encryptionKey; // } // // public Boolean getEncrypted() { // return encrypted; // } // // public String getAllowedOrigins() { // return allowedOrigins; // } // // @Override // public String toString() { // return "LocateApiConfiguration{" + // "mongoConfiguration=" + mongoConfiguration + // ", maxRequestsPerDay=" + maxRequestsPerDay + // ", encryptionKey='" + encryptionKey + '\'' + // ", encrypted=" + encrypted + // ", allowedOrigins='" + allowedOrigins + '\'' + // '}'; // } // } // // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/dao/UsageDao.java // public class UsageDao { // // private final JacksonDBCollection<Usage, String> collection; // // public UsageDao(JacksonDBCollection<Usage, String> collection) { // this.collection = collection; // } // // @Timed // public Optional<Usage> findUsageByIdentifier(String identifier) { // return Optional.fromNullable(collection.findAndModify(new BasicDBObject("identifier", identifier), new DBUpdate.Builder().inc("count"))); // } // // @Timed // public Boolean create(String identifier) { // Date expiry = DateTime.now().withZone(DateTimeZone.UTC).withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59).withMillisOfSecond(999).toDate(); // return collection.insert(new Usage(org.bson.types.ObjectId.get().toString(), identifier, 1, expiry)).getN() == 1; // } // // @Timed // public void applyIndexes() { // collection.ensureIndex(new BasicDBObject("identifier", 1), "identifier_index", true); // collection.ensureIndex(new BasicDBObject("expireAt", 1), new BasicDBObject("expireAfterSeconds", 0)); // } // } // // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/model/AuthorizationToken.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class AuthorizationToken { // // @JsonProperty("_id") // @ObjectId // private String id; // // @JsonProperty("name") // private String name; // // @JsonProperty("identifier") // private String identifier; // // @JsonProperty("organisation") // private String organisation; // // @JsonProperty("token") // private String token; // // public AuthorizationToken() { // } // // public AuthorizationToken(String id, String name, String identifier, String organisation, String token) { // this.id = id; // this.name = name; // this.identifier = identifier; // this.organisation = organisation; // this.token = token; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public String getIdentifier() { // return identifier; // } // // public String getOrganisation() { // return organisation; // } // // public String getToken() { // return token; // } // // @Override // public String toString() { // return "AuthorizationToken{" + // "id='" + id + '\'' + // ", name='" + name + '\'' + // ", identifier='" + identifier + '\'' + // ", organisation='" + organisation + '\'' + // ", token='" + token + '\'' + // '}'; // } // } // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/authentication/BearerTokenAuthProvider.java import com.sun.jersey.api.model.Parameter; import com.sun.jersey.core.spi.component.ComponentContext; import com.sun.jersey.core.spi.component.ComponentScope; import com.sun.jersey.spi.inject.Injectable; import com.sun.jersey.spi.inject.InjectableProvider; import com.yammer.dropwizard.auth.Auth; import com.yammer.dropwizard.auth.Authenticator; import uk.gov.gds.locate.api.configuration.LocateApiConfiguration; import uk.gov.gds.locate.api.dao.UsageDao; import uk.gov.gds.locate.api.model.AuthorizationToken; package uk.gov.gds.locate.api.authentication; public class BearerTokenAuthProvider implements InjectableProvider<Auth, Parameter> { private final LocateApiConfiguration configuration;
private final UsageDao usageDao;
alphagov/locate-api
locate-api-service/src/main/java/uk/gov/gds/locate/api/authentication/BearerTokenAuthProvider.java
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/configuration/LocateApiConfiguration.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class LocateApiConfiguration extends Configuration { // // @Valid // @NotNull // @JsonProperty // private MongoConfiguration mongoConfiguration = new MongoConfiguration(); // // @Valid // @NotNull // @JsonProperty // private Integer maxRequestsPerDay; // // @Valid // @NotNull // @JsonProperty // private String encryptionKey; // // @Valid // @NotNull // @JsonProperty // private Boolean encrypted; // // @Valid // @NotNull // @JsonProperty // private String allowedOrigins; // // public MongoConfiguration getMongoConfiguration() { // return mongoConfiguration; // } // // public Integer getMaxRequestsPerDay() { // return maxRequestsPerDay; // } // // public String getEncryptionKey() { // return encryptionKey; // } // // public Boolean getEncrypted() { // return encrypted; // } // // public String getAllowedOrigins() { // return allowedOrigins; // } // // @Override // public String toString() { // return "LocateApiConfiguration{" + // "mongoConfiguration=" + mongoConfiguration + // ", maxRequestsPerDay=" + maxRequestsPerDay + // ", encryptionKey='" + encryptionKey + '\'' + // ", encrypted=" + encrypted + // ", allowedOrigins='" + allowedOrigins + '\'' + // '}'; // } // } // // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/dao/UsageDao.java // public class UsageDao { // // private final JacksonDBCollection<Usage, String> collection; // // public UsageDao(JacksonDBCollection<Usage, String> collection) { // this.collection = collection; // } // // @Timed // public Optional<Usage> findUsageByIdentifier(String identifier) { // return Optional.fromNullable(collection.findAndModify(new BasicDBObject("identifier", identifier), new DBUpdate.Builder().inc("count"))); // } // // @Timed // public Boolean create(String identifier) { // Date expiry = DateTime.now().withZone(DateTimeZone.UTC).withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59).withMillisOfSecond(999).toDate(); // return collection.insert(new Usage(org.bson.types.ObjectId.get().toString(), identifier, 1, expiry)).getN() == 1; // } // // @Timed // public void applyIndexes() { // collection.ensureIndex(new BasicDBObject("identifier", 1), "identifier_index", true); // collection.ensureIndex(new BasicDBObject("expireAt", 1), new BasicDBObject("expireAfterSeconds", 0)); // } // } // // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/model/AuthorizationToken.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class AuthorizationToken { // // @JsonProperty("_id") // @ObjectId // private String id; // // @JsonProperty("name") // private String name; // // @JsonProperty("identifier") // private String identifier; // // @JsonProperty("organisation") // private String organisation; // // @JsonProperty("token") // private String token; // // public AuthorizationToken() { // } // // public AuthorizationToken(String id, String name, String identifier, String organisation, String token) { // this.id = id; // this.name = name; // this.identifier = identifier; // this.organisation = organisation; // this.token = token; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public String getIdentifier() { // return identifier; // } // // public String getOrganisation() { // return organisation; // } // // public String getToken() { // return token; // } // // @Override // public String toString() { // return "AuthorizationToken{" + // "id='" + id + '\'' + // ", name='" + name + '\'' + // ", identifier='" + identifier + '\'' + // ", organisation='" + organisation + '\'' + // ", token='" + token + '\'' + // '}'; // } // }
import com.sun.jersey.api.model.Parameter; import com.sun.jersey.core.spi.component.ComponentContext; import com.sun.jersey.core.spi.component.ComponentScope; import com.sun.jersey.spi.inject.Injectable; import com.sun.jersey.spi.inject.InjectableProvider; import com.yammer.dropwizard.auth.Auth; import com.yammer.dropwizard.auth.Authenticator; import uk.gov.gds.locate.api.configuration.LocateApiConfiguration; import uk.gov.gds.locate.api.dao.UsageDao; import uk.gov.gds.locate.api.model.AuthorizationToken;
package uk.gov.gds.locate.api.authentication; public class BearerTokenAuthProvider implements InjectableProvider<Auth, Parameter> { private final LocateApiConfiguration configuration; private final UsageDao usageDao;
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/configuration/LocateApiConfiguration.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class LocateApiConfiguration extends Configuration { // // @Valid // @NotNull // @JsonProperty // private MongoConfiguration mongoConfiguration = new MongoConfiguration(); // // @Valid // @NotNull // @JsonProperty // private Integer maxRequestsPerDay; // // @Valid // @NotNull // @JsonProperty // private String encryptionKey; // // @Valid // @NotNull // @JsonProperty // private Boolean encrypted; // // @Valid // @NotNull // @JsonProperty // private String allowedOrigins; // // public MongoConfiguration getMongoConfiguration() { // return mongoConfiguration; // } // // public Integer getMaxRequestsPerDay() { // return maxRequestsPerDay; // } // // public String getEncryptionKey() { // return encryptionKey; // } // // public Boolean getEncrypted() { // return encrypted; // } // // public String getAllowedOrigins() { // return allowedOrigins; // } // // @Override // public String toString() { // return "LocateApiConfiguration{" + // "mongoConfiguration=" + mongoConfiguration + // ", maxRequestsPerDay=" + maxRequestsPerDay + // ", encryptionKey='" + encryptionKey + '\'' + // ", encrypted=" + encrypted + // ", allowedOrigins='" + allowedOrigins + '\'' + // '}'; // } // } // // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/dao/UsageDao.java // public class UsageDao { // // private final JacksonDBCollection<Usage, String> collection; // // public UsageDao(JacksonDBCollection<Usage, String> collection) { // this.collection = collection; // } // // @Timed // public Optional<Usage> findUsageByIdentifier(String identifier) { // return Optional.fromNullable(collection.findAndModify(new BasicDBObject("identifier", identifier), new DBUpdate.Builder().inc("count"))); // } // // @Timed // public Boolean create(String identifier) { // Date expiry = DateTime.now().withZone(DateTimeZone.UTC).withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59).withMillisOfSecond(999).toDate(); // return collection.insert(new Usage(org.bson.types.ObjectId.get().toString(), identifier, 1, expiry)).getN() == 1; // } // // @Timed // public void applyIndexes() { // collection.ensureIndex(new BasicDBObject("identifier", 1), "identifier_index", true); // collection.ensureIndex(new BasicDBObject("expireAt", 1), new BasicDBObject("expireAfterSeconds", 0)); // } // } // // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/model/AuthorizationToken.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class AuthorizationToken { // // @JsonProperty("_id") // @ObjectId // private String id; // // @JsonProperty("name") // private String name; // // @JsonProperty("identifier") // private String identifier; // // @JsonProperty("organisation") // private String organisation; // // @JsonProperty("token") // private String token; // // public AuthorizationToken() { // } // // public AuthorizationToken(String id, String name, String identifier, String organisation, String token) { // this.id = id; // this.name = name; // this.identifier = identifier; // this.organisation = organisation; // this.token = token; // } // // public String getId() { // return id; // } // // public String getName() { // return name; // } // // public String getIdentifier() { // return identifier; // } // // public String getOrganisation() { // return organisation; // } // // public String getToken() { // return token; // } // // @Override // public String toString() { // return "AuthorizationToken{" + // "id='" + id + '\'' + // ", name='" + name + '\'' + // ", identifier='" + identifier + '\'' + // ", organisation='" + organisation + '\'' + // ", token='" + token + '\'' + // '}'; // } // } // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/authentication/BearerTokenAuthProvider.java import com.sun.jersey.api.model.Parameter; import com.sun.jersey.core.spi.component.ComponentContext; import com.sun.jersey.core.spi.component.ComponentScope; import com.sun.jersey.spi.inject.Injectable; import com.sun.jersey.spi.inject.InjectableProvider; import com.yammer.dropwizard.auth.Auth; import com.yammer.dropwizard.auth.Authenticator; import uk.gov.gds.locate.api.configuration.LocateApiConfiguration; import uk.gov.gds.locate.api.dao.UsageDao; import uk.gov.gds.locate.api.model.AuthorizationToken; package uk.gov.gds.locate.api.authentication; public class BearerTokenAuthProvider implements InjectableProvider<Auth, Parameter> { private final LocateApiConfiguration configuration; private final UsageDao usageDao;
private final Authenticator<String, AuthorizationToken> authenticator;
alphagov/locate-api
locate-api-service/src/main/java/uk/gov/gds/locate/api/model/Presentation.java
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/encryption/AesEncryptionService.java // public abstract class AesEncryptionService { // // private static final String algorithm = "AES/CBC/PKCS5Padding"; // // private static final SecureRandom random = new SecureRandom(); // // static { // random.setSeed(DateTime.now().getMillis()); // } // // public static SecretKeySpec aesKeyFromBase64EncodedString(String key) { // return new SecretKeySpec(Base64.decodeBase64(key), "AES"); // } // // private static byte[] decodeBase64(String content) { // return Base64.decodeBase64(content); // } // // private static IvParameterSpec generateInitializationVector() { // byte[] iv = new byte[16]; // random.nextBytes(iv); // return new IvParameterSpec(iv); // } // // public static AesEncryptionProduct encrypt(String content, Key aesKey) throws Exception { // Cipher cipher = Cipher.getInstance(algorithm); // IvParameterSpec ivSpec = generateInitializationVector(); // cipher.init(Cipher.ENCRYPT_MODE, aesKey, ivSpec); // return new AesEncryptionProduct(cipher.doFinal(content.getBytes()), ivSpec.getIV()); // } // // // public static String decrypt(String encryptedContent, String aesKey, String iv) throws Exception { // try { // Cipher cipher = Cipher.getInstance(algorithm); // cipher.init(Cipher.DECRYPT_MODE, aesKeyFromBase64EncodedString(aesKey), new IvParameterSpec(decodeBase64(iv))); // return new String(cipher.doFinal(decodeBase64(encryptedContent))); // // } catch (BadPaddingException ex) { // throw new Exception("AES decryption failed. Possible cause: incorrect private key", ex); // } catch (Exception ex) { // throw new Exception("AES decryption failed", ex); // } // } // }
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Strings; import uk.gov.gds.locate.api.encryption.AesEncryptionService;
this.postcode = postcode; } public String getProperty() { return property; } public String getStreet() { return street; } public String getLocality() { return locality; } public String getTown() { return town; } public String getArea() { return area; } public String getPostcode() { return postcode; } public Presentation decrypt(String key, String iv) { try { return new Presentation(
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/encryption/AesEncryptionService.java // public abstract class AesEncryptionService { // // private static final String algorithm = "AES/CBC/PKCS5Padding"; // // private static final SecureRandom random = new SecureRandom(); // // static { // random.setSeed(DateTime.now().getMillis()); // } // // public static SecretKeySpec aesKeyFromBase64EncodedString(String key) { // return new SecretKeySpec(Base64.decodeBase64(key), "AES"); // } // // private static byte[] decodeBase64(String content) { // return Base64.decodeBase64(content); // } // // private static IvParameterSpec generateInitializationVector() { // byte[] iv = new byte[16]; // random.nextBytes(iv); // return new IvParameterSpec(iv); // } // // public static AesEncryptionProduct encrypt(String content, Key aesKey) throws Exception { // Cipher cipher = Cipher.getInstance(algorithm); // IvParameterSpec ivSpec = generateInitializationVector(); // cipher.init(Cipher.ENCRYPT_MODE, aesKey, ivSpec); // return new AesEncryptionProduct(cipher.doFinal(content.getBytes()), ivSpec.getIV()); // } // // // public static String decrypt(String encryptedContent, String aesKey, String iv) throws Exception { // try { // Cipher cipher = Cipher.getInstance(algorithm); // cipher.init(Cipher.DECRYPT_MODE, aesKeyFromBase64EncodedString(aesKey), new IvParameterSpec(decodeBase64(iv))); // return new String(cipher.doFinal(decodeBase64(encryptedContent))); // // } catch (BadPaddingException ex) { // throw new Exception("AES decryption failed. Possible cause: incorrect private key", ex); // } catch (Exception ex) { // throw new Exception("AES decryption failed", ex); // } // } // } // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/model/Presentation.java import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Strings; import uk.gov.gds.locate.api.encryption.AesEncryptionService; this.postcode = postcode; } public String getProperty() { return property; } public String getStreet() { return street; } public String getLocality() { return locality; } public String getTown() { return town; } public String getArea() { return area; } public String getPostcode() { return postcode; } public Presentation decrypt(String key, String iv) { try { return new Presentation(
Strings.isNullOrEmpty(this.property) ? this.property : AesEncryptionService.decrypt(this.property, key, iv),
alphagov/locate-api
locate-api-service/src/main/java/uk/gov/gds/locate/api/authentication/BearerToken.java
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/authentication/Obfuscated.java // public static String getObfuscatedToken(String token) { // return String.format("%s...%s", token.substring(0, 2), token.substring(token.length() - 2)); // }
import com.google.common.base.Objects; import static com.google.common.base.Preconditions.checkNotNull; import static uk.gov.gds.locate.api.authentication.Obfuscated.getObfuscatedToken;
package uk.gov.gds.locate.api.authentication; public class BearerToken { private final String bearerToken; public BearerToken(String bearerToken) { this.bearerToken = checkNotNull(bearerToken); } public String getBearerToken() { return bearerToken; } @Override public String toString() { return Objects.toStringHelper(this)
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/authentication/Obfuscated.java // public static String getObfuscatedToken(String token) { // return String.format("%s...%s", token.substring(0, 2), token.substring(token.length() - 2)); // } // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/authentication/BearerToken.java import com.google.common.base.Objects; import static com.google.common.base.Preconditions.checkNotNull; import static uk.gov.gds.locate.api.authentication.Obfuscated.getObfuscatedToken; package uk.gov.gds.locate.api.authentication; public class BearerToken { private final String bearerToken; public BearerToken(String bearerToken) { this.bearerToken = checkNotNull(bearerToken); } public String getBearerToken() { return bearerToken; } @Override public String toString() { return Objects.toStringHelper(this)
.add("bearerToken", getObfuscatedToken(bearerToken))
alphagov/locate-api
locate-api-service/src/main/java/uk/gov/gds/locate/api/model/Ordering.java
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/encryption/AesEncryptionService.java // public abstract class AesEncryptionService { // // private static final String algorithm = "AES/CBC/PKCS5Padding"; // // private static final SecureRandom random = new SecureRandom(); // // static { // random.setSeed(DateTime.now().getMillis()); // } // // public static SecretKeySpec aesKeyFromBase64EncodedString(String key) { // return new SecretKeySpec(Base64.decodeBase64(key), "AES"); // } // // private static byte[] decodeBase64(String content) { // return Base64.decodeBase64(content); // } // // private static IvParameterSpec generateInitializationVector() { // byte[] iv = new byte[16]; // random.nextBytes(iv); // return new IvParameterSpec(iv); // } // // public static AesEncryptionProduct encrypt(String content, Key aesKey) throws Exception { // Cipher cipher = Cipher.getInstance(algorithm); // IvParameterSpec ivSpec = generateInitializationVector(); // cipher.init(Cipher.ENCRYPT_MODE, aesKey, ivSpec); // return new AesEncryptionProduct(cipher.doFinal(content.getBytes()), ivSpec.getIV()); // } // // // public static String decrypt(String encryptedContent, String aesKey, String iv) throws Exception { // try { // Cipher cipher = Cipher.getInstance(algorithm); // cipher.init(Cipher.DECRYPT_MODE, aesKeyFromBase64EncodedString(aesKey), new IvParameterSpec(decodeBase64(iv))); // return new String(cipher.doFinal(decodeBase64(encryptedContent))); // // } catch (BadPaddingException ex) { // throw new Exception("AES decryption failed. Possible cause: incorrect private key", ex); // } catch (Exception ex) { // throw new Exception("AES decryption failed", ex); // } // } // }
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Strings; import com.google.common.collect.ComparisonChain; import uk.gov.gds.locate.api.encryption.AesEncryptionService;
return paoEndNumber; } public String getPaoEndSuffix() { return paoEndSuffix; } public String getPaoText() { return paoText; } public String getSaoText() { return saoText; } public String getStreet() { return street; } public Ordering decrypt(String key, String iv) { try { return new Ordering( this.saoStartNumber, this.saoStartSuffix, this.saoEndNumber, this.saoEndSuffix, this.paoStartNumber, this.paoStartSuffix, this.paoEndNumber, this.paoEndSuffix,
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/encryption/AesEncryptionService.java // public abstract class AesEncryptionService { // // private static final String algorithm = "AES/CBC/PKCS5Padding"; // // private static final SecureRandom random = new SecureRandom(); // // static { // random.setSeed(DateTime.now().getMillis()); // } // // public static SecretKeySpec aesKeyFromBase64EncodedString(String key) { // return new SecretKeySpec(Base64.decodeBase64(key), "AES"); // } // // private static byte[] decodeBase64(String content) { // return Base64.decodeBase64(content); // } // // private static IvParameterSpec generateInitializationVector() { // byte[] iv = new byte[16]; // random.nextBytes(iv); // return new IvParameterSpec(iv); // } // // public static AesEncryptionProduct encrypt(String content, Key aesKey) throws Exception { // Cipher cipher = Cipher.getInstance(algorithm); // IvParameterSpec ivSpec = generateInitializationVector(); // cipher.init(Cipher.ENCRYPT_MODE, aesKey, ivSpec); // return new AesEncryptionProduct(cipher.doFinal(content.getBytes()), ivSpec.getIV()); // } // // // public static String decrypt(String encryptedContent, String aesKey, String iv) throws Exception { // try { // Cipher cipher = Cipher.getInstance(algorithm); // cipher.init(Cipher.DECRYPT_MODE, aesKeyFromBase64EncodedString(aesKey), new IvParameterSpec(decodeBase64(iv))); // return new String(cipher.doFinal(decodeBase64(encryptedContent))); // // } catch (BadPaddingException ex) { // throw new Exception("AES decryption failed. Possible cause: incorrect private key", ex); // } catch (Exception ex) { // throw new Exception("AES decryption failed", ex); // } // } // } // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/model/Ordering.java import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Strings; import com.google.common.collect.ComparisonChain; import uk.gov.gds.locate.api.encryption.AesEncryptionService; return paoEndNumber; } public String getPaoEndSuffix() { return paoEndSuffix; } public String getPaoText() { return paoText; } public String getSaoText() { return saoText; } public String getStreet() { return street; } public Ordering decrypt(String key, String iv) { try { return new Ordering( this.saoStartNumber, this.saoStartSuffix, this.saoEndNumber, this.saoEndSuffix, this.paoStartNumber, this.paoStartSuffix, this.paoEndNumber, this.paoEndSuffix,
Strings.isNullOrEmpty(this.paoText) ? this.paoText : AesEncryptionService.decrypt(this.paoText, key, iv),
alphagov/locate-api
locate-api-service/src/main/java/uk/gov/gds/locate/api/tasks/MongoIndexTask.java
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/dao/AuthorizationTokenDao.java // public class AuthorizationTokenDao { // // private final JacksonDBCollection<AuthorizationToken, String> authorizationTokens; // // public AuthorizationTokenDao(JacksonDBCollection<AuthorizationToken, String> authorizationTokens) { // this.authorizationTokens = authorizationTokens; // } // // @Timed // public AuthorizationToken fetchCredentialsByBearerToken(String token) { // return authorizationTokens.findOne(new BasicDBObject("token", token)); // } // // @Timed // public Boolean create(AuthorizationToken authorizationToken) { // return authorizationTokens.insert(authorizationToken).getN() == 1; // } // // @Timed // public void applyIndexes() { // authorizationTokens.ensureIndex(new BasicDBObject("token", 1), "token_index", true); // authorizationTokens.ensureIndex(new BasicDBObject("identifier", 1), "identifier_index", true); // } // } // // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/dao/UsageDao.java // public class UsageDao { // // private final JacksonDBCollection<Usage, String> collection; // // public UsageDao(JacksonDBCollection<Usage, String> collection) { // this.collection = collection; // } // // @Timed // public Optional<Usage> findUsageByIdentifier(String identifier) { // return Optional.fromNullable(collection.findAndModify(new BasicDBObject("identifier", identifier), new DBUpdate.Builder().inc("count"))); // } // // @Timed // public Boolean create(String identifier) { // Date expiry = DateTime.now().withZone(DateTimeZone.UTC).withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59).withMillisOfSecond(999).toDate(); // return collection.insert(new Usage(org.bson.types.ObjectId.get().toString(), identifier, 1, expiry)).getN() == 1; // } // // @Timed // public void applyIndexes() { // collection.ensureIndex(new BasicDBObject("identifier", 1), "identifier_index", true); // collection.ensureIndex(new BasicDBObject("expireAt", 1), new BasicDBObject("expireAfterSeconds", 0)); // } // }
import com.google.common.collect.ImmutableMultimap; import com.yammer.dropwizard.tasks.Task; import com.yammer.metrics.annotation.Timed; import uk.gov.gds.locate.api.dao.AuthorizationTokenDao; import uk.gov.gds.locate.api.dao.UsageDao; import java.io.PrintWriter;
package uk.gov.gds.locate.api.tasks; public class MongoIndexTask extends Task { private final AuthorizationTokenDao authorizationTokenDao;
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/dao/AuthorizationTokenDao.java // public class AuthorizationTokenDao { // // private final JacksonDBCollection<AuthorizationToken, String> authorizationTokens; // // public AuthorizationTokenDao(JacksonDBCollection<AuthorizationToken, String> authorizationTokens) { // this.authorizationTokens = authorizationTokens; // } // // @Timed // public AuthorizationToken fetchCredentialsByBearerToken(String token) { // return authorizationTokens.findOne(new BasicDBObject("token", token)); // } // // @Timed // public Boolean create(AuthorizationToken authorizationToken) { // return authorizationTokens.insert(authorizationToken).getN() == 1; // } // // @Timed // public void applyIndexes() { // authorizationTokens.ensureIndex(new BasicDBObject("token", 1), "token_index", true); // authorizationTokens.ensureIndex(new BasicDBObject("identifier", 1), "identifier_index", true); // } // } // // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/dao/UsageDao.java // public class UsageDao { // // private final JacksonDBCollection<Usage, String> collection; // // public UsageDao(JacksonDBCollection<Usage, String> collection) { // this.collection = collection; // } // // @Timed // public Optional<Usage> findUsageByIdentifier(String identifier) { // return Optional.fromNullable(collection.findAndModify(new BasicDBObject("identifier", identifier), new DBUpdate.Builder().inc("count"))); // } // // @Timed // public Boolean create(String identifier) { // Date expiry = DateTime.now().withZone(DateTimeZone.UTC).withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59).withMillisOfSecond(999).toDate(); // return collection.insert(new Usage(org.bson.types.ObjectId.get().toString(), identifier, 1, expiry)).getN() == 1; // } // // @Timed // public void applyIndexes() { // collection.ensureIndex(new BasicDBObject("identifier", 1), "identifier_index", true); // collection.ensureIndex(new BasicDBObject("expireAt", 1), new BasicDBObject("expireAfterSeconds", 0)); // } // } // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/tasks/MongoIndexTask.java import com.google.common.collect.ImmutableMultimap; import com.yammer.dropwizard.tasks.Task; import com.yammer.metrics.annotation.Timed; import uk.gov.gds.locate.api.dao.AuthorizationTokenDao; import uk.gov.gds.locate.api.dao.UsageDao; import java.io.PrintWriter; package uk.gov.gds.locate.api.tasks; public class MongoIndexTask extends Task { private final AuthorizationTokenDao authorizationTokenDao;
private final UsageDao usageDao;
alphagov/locate-api
locate-api-service/src/main/java/uk/gov/gds/locate/api/LocateExceptionMapper.java
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/exceptions/LocateWebException.java // public class LocateWebException extends Exception { // // protected static final String CONTENT_TYPE = "application/json; charset=utf-8"; // protected static final String CONTENT_TYPE_HEADER = "Content-Type"; // // private final int statusCode; // private final Object body; // // // public LocateWebException(int statusCode, Object body) { // this.statusCode = statusCode; // this.body = body; // } // // public int getStatusCode() { // return statusCode; // } // // public Object getBody() { // return body; // } // // public Response getResponse() { // return Response // .status(statusCode) // .header(CONTENT_TYPE_HEADER, CONTENT_TYPE) // .entity(body) // .build(); // } // // // @Override // public String toString() { // return "LocateWebException{" + // "statusCode=" + statusCode + // ", body=" + body + // '}'; // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.gov.gds.locate.api.exceptions.LocateWebException; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider;
package uk.gov.gds.locate.api; @Provider @Produces(MediaType.APPLICATION_JSON) public class LocateExceptionMapper implements javax.ws.rs.ext.ExceptionMapper<Throwable> { private static final Logger LOGGER = LoggerFactory.getLogger(LocateExceptionMapper.class); protected static final String CONTENT_TYPE = "application/json; charset=utf-8"; protected static final String CONTENT_TYPE_HEADER = "Content-Type"; @Override public Response toResponse(Throwable exception) {
// Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/exceptions/LocateWebException.java // public class LocateWebException extends Exception { // // protected static final String CONTENT_TYPE = "application/json; charset=utf-8"; // protected static final String CONTENT_TYPE_HEADER = "Content-Type"; // // private final int statusCode; // private final Object body; // // // public LocateWebException(int statusCode, Object body) { // this.statusCode = statusCode; // this.body = body; // } // // public int getStatusCode() { // return statusCode; // } // // public Object getBody() { // return body; // } // // public Response getResponse() { // return Response // .status(statusCode) // .header(CONTENT_TYPE_HEADER, CONTENT_TYPE) // .entity(body) // .build(); // } // // // @Override // public String toString() { // return "LocateWebException{" + // "statusCode=" + statusCode + // ", body=" + body + // '}'; // } // } // Path: locate-api-service/src/main/java/uk/gov/gds/locate/api/LocateExceptionMapper.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.gov.gds.locate.api.exceptions.LocateWebException; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; package uk.gov.gds.locate.api; @Provider @Produces(MediaType.APPLICATION_JSON) public class LocateExceptionMapper implements javax.ws.rs.ext.ExceptionMapper<Throwable> { private static final Logger LOGGER = LoggerFactory.getLogger(LocateExceptionMapper.class); protected static final String CONTENT_TYPE = "application/json; charset=utf-8"; protected static final String CONTENT_TYPE_HEADER = "Content-Type"; @Override public Response toResponse(Throwable exception) {
if (exception instanceof LocateWebException) {
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/test/java/com/caseystella/ds/nlp/SentimentAnalysisTest.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/test/java/com/caseystella/ds/util/ReservoirSampler.java // public class ReservoirSampler<T> { // private final List<T> reservoir = new ArrayList<T>(); // private final int numSamples; // // private final Random random; // private int numItemsSeen = 0; // // /** // * Create a new sampler with a certain reservoir size using // * a supplied random number generator. // * // * @param numSamples Maximum number of samples to // * retain in the reservoir. Must be non-negative. // * @param random Instance of the random number generator // * to use for sampling // */ // public ReservoirSampler(int numSamples, Random random) { // Preconditions.checkArgument(numSamples > 0, // "numSamples should be positive"); // Preconditions.checkNotNull(random); // this.numSamples = numSamples; // this.random = random; // } // // /** // * Create a new sampler with a certain reservoir size using // * the default random number generator. // * // * @param numSamples Maximum number of samples to // * retain in the reservoir. Must be non-negative. // */ // public ReservoirSampler(int numSamples) { // this(numSamples, new Random(0)); // } // // /** // * Sample an item and store in the reservoir if needed. // * // * @param item The item to sample - may not be null. // */ // public void sample(T item) { // Preconditions.checkNotNull(item); // if (reservoir.size() < numSamples) { // // reservoir not yet full, just append // reservoir.add(item); // } else { // // find a sample to replace // int rIndex = random.nextInt(numItemsSeen + 1); // if (rIndex < numSamples) { // reservoir.set(rIndex, item); // } // } // numItemsSeen++; // } // // /** // * Get samples collected in the reservoir. // * // * @return A sequence of the samples. No guarantee is provided on the order of the samples. // */ // public Iterable<T> getSamples() { // return reservoir; // } // }
import com.caseystella.ds.util.ReservoirSampler; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import edu.stanford.nlp.io.IOUtils; import edu.stanford.nlp.util.StringUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.util.EnumMap; import java.util.List;
package com.caseystella.ds.nlp; /** * Created by cstella on 3/21/14. */ public class SentimentAnalysisTest { private static Iterable<String> readFile(String filename) throws IOException { return Splitter.on('\n').split(IOUtils.slurpFile(filename)); } private static int[][] initializeConfusionMatrix() { int numClasses = SentimentClass.values().length; int[][] confusionMatrix = new int[numClasses][numClasses]; for(int i = 0;i < numClasses;++i) { for(int j = 0;j < numClasses;++j) { confusionMatrix[i][j] = 0; } } return confusionMatrix; } @Test public void testIMDBSentimentAnalysis() throws Exception { int[][] confusionMatrix = initializeConfusionMatrix(); int totalNumDocs = 100;
// Path: Hadoop_Summit_Pig_for_Data_Science/src/test/java/com/caseystella/ds/util/ReservoirSampler.java // public class ReservoirSampler<T> { // private final List<T> reservoir = new ArrayList<T>(); // private final int numSamples; // // private final Random random; // private int numItemsSeen = 0; // // /** // * Create a new sampler with a certain reservoir size using // * a supplied random number generator. // * // * @param numSamples Maximum number of samples to // * retain in the reservoir. Must be non-negative. // * @param random Instance of the random number generator // * to use for sampling // */ // public ReservoirSampler(int numSamples, Random random) { // Preconditions.checkArgument(numSamples > 0, // "numSamples should be positive"); // Preconditions.checkNotNull(random); // this.numSamples = numSamples; // this.random = random; // } // // /** // * Create a new sampler with a certain reservoir size using // * the default random number generator. // * // * @param numSamples Maximum number of samples to // * retain in the reservoir. Must be non-negative. // */ // public ReservoirSampler(int numSamples) { // this(numSamples, new Random(0)); // } // // /** // * Sample an item and store in the reservoir if needed. // * // * @param item The item to sample - may not be null. // */ // public void sample(T item) { // Preconditions.checkNotNull(item); // if (reservoir.size() < numSamples) { // // reservoir not yet full, just append // reservoir.add(item); // } else { // // find a sample to replace // int rIndex = random.nextInt(numItemsSeen + 1); // if (rIndex < numSamples) { // reservoir.set(rIndex, item); // } // } // numItemsSeen++; // } // // /** // * Get samples collected in the reservoir. // * // * @return A sequence of the samples. No guarantee is provided on the order of the samples. // */ // public Iterable<T> getSamples() { // return reservoir; // } // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/test/java/com/caseystella/ds/nlp/SentimentAnalysisTest.java import com.caseystella.ds.util.ReservoirSampler; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import edu.stanford.nlp.io.IOUtils; import edu.stanford.nlp.util.StringUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.util.EnumMap; import java.util.List; package com.caseystella.ds.nlp; /** * Created by cstella on 3/21/14. */ public class SentimentAnalysisTest { private static Iterable<String> readFile(String filename) throws IOException { return Splitter.on('\n').split(IOUtils.slurpFile(filename)); } private static int[][] initializeConfusionMatrix() { int numClasses = SentimentClass.values().length; int[][] confusionMatrix = new int[numClasses][numClasses]; for(int i = 0;i < numClasses;++i) { for(int j = 0;j < numClasses;++j) { confusionMatrix[i][j] = 0; } } return confusionMatrix; } @Test public void testIMDBSentimentAnalysis() throws Exception { int[][] confusionMatrix = initializeConfusionMatrix(); int totalNumDocs = 100;
ReservoirSampler<String> positiveReservoir = new ReservoirSampler<String>(totalNumDocs/2);
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/SentimentRollup.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // }
import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.strategy.*; import java.util.List;
package com.caseystella.ds.nlp.rollup; /** * Created by cstella on 3/25/14. */ public enum SentimentRollup implements ISentimentRollup { SIMPLE_VOTE(new SimpleVoteRollup()) ,AVERAGE_PROBABILITIES(new AverageProbabilitiesRollup()) , LAST_SENTENCE_WINS(new LastSentenceWins()) , LONGEST_SENTENCE_WINS(new LongestSentenceWins()) , WILSON_SCORE(new WilsonScore()) ; private ISentimentRollup proxy; SentimentRollup(ISentimentRollup proxy) { this.proxy = proxy;} @Override
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/SentimentRollup.java import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.strategy.*; import java.util.List; package com.caseystella.ds.nlp.rollup; /** * Created by cstella on 3/25/14. */ public enum SentimentRollup implements ISentimentRollup { SIMPLE_VOTE(new SimpleVoteRollup()) ,AVERAGE_PROBABILITIES(new AverageProbabilitiesRollup()) , LAST_SENTENCE_WINS(new LastSentenceWins()) , LONGEST_SENTENCE_WINS(new LongestSentenceWins()) , WILSON_SCORE(new WilsonScore()) ; private ISentimentRollup proxy; SentimentRollup(ISentimentRollup proxy) { this.proxy = proxy;} @Override
public SentimentClass apply(List<Sentence> input) {
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/util/GenerateTrainingData.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // }
import com.caseystella.ds.nlp.SentimentClass; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Iterables; import edu.stanford.nlp.ie.machinereading.structure.AnnotationUtils; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.sentiment.SentimentCoreAnnotations; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.util.CoreMap; import org.ejml.simple.SimpleMatrix; import java.io.*; import java.util.*;
package com.caseystella.ds.nlp.rollup.util; /** * This generates training data for the rollup approach analysis * * @see com.caseystella.ds.nlp.rollup.util.EvaluateRollupApproaches */ public class GenerateTrainingData { private static List<Map.Entry<String, String>> getSentiment(StanfordCoreNLP pipeline, String document) { List<Map.Entry<String, String>> ret = new ArrayList<Map.Entry<String, String>>(); Annotation annotation = pipeline.process(document); /* * We're going to iterate over all of the sentences and extract the sentiment. We'll adopt a majority rule policy */ for( CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) { //for each sentence, we get the sentiment annotation //this comes in the form of a tree of annotations Tree sentimentTree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class); //Letting CoreNLP roll up the sentiment for us int sentimentClassIdx = RNNCoreAnnotations.getPredictedClass(sentimentTree); //now we add to our list of sentences and sentiments
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/util/GenerateTrainingData.java import com.caseystella.ds.nlp.SentimentClass; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Iterables; import edu.stanford.nlp.ie.machinereading.structure.AnnotationUtils; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.sentiment.SentimentCoreAnnotations; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.util.CoreMap; import org.ejml.simple.SimpleMatrix; import java.io.*; import java.util.*; package com.caseystella.ds.nlp.rollup.util; /** * This generates training data for the rollup approach analysis * * @see com.caseystella.ds.nlp.rollup.util.EvaluateRollupApproaches */ public class GenerateTrainingData { private static List<Map.Entry<String, String>> getSentiment(StanfordCoreNLP pipeline, String document) { List<Map.Entry<String, String>> ret = new ArrayList<Map.Entry<String, String>>(); Annotation annotation = pipeline.process(document); /* * We're going to iterate over all of the sentences and extract the sentiment. We'll adopt a majority rule policy */ for( CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) { //for each sentence, we get the sentiment annotation //this comes in the form of a tree of annotations Tree sentimentTree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class); //Letting CoreNLP roll up the sentiment for us int sentimentClassIdx = RNNCoreAnnotations.getPredictedClass(sentimentTree); //now we add to our list of sentences and sentiments
SentimentClass sentimentClass = SentimentClass.getGeneral(sentimentClassIdx);
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/SimpleVoteRollup.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // }
import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.EnumMap; import java.util.List;
package com.caseystella.ds.nlp.rollup.strategy; /** * Created by cstella on 3/25/14. */ public class SimpleVoteRollup implements ISentimentRollup { @Override
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/SimpleVoteRollup.java import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.EnumMap; import java.util.List; package com.caseystella.ds.nlp.rollup.strategy; /** * Created by cstella on 3/25/14. */ public class SimpleVoteRollup implements ISentimentRollup { @Override
public SentimentClass apply(List<Sentence> input)
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/SimpleVoteRollup.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // }
import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.EnumMap; import java.util.List;
package com.caseystella.ds.nlp.rollup.strategy; /** * Created by cstella on 3/25/14. */ public class SimpleVoteRollup implements ISentimentRollup { @Override
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/SimpleVoteRollup.java import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.EnumMap; import java.util.List; package com.caseystella.ds.nlp.rollup.strategy; /** * Created by cstella on 3/25/14. */ public class SimpleVoteRollup implements ISentimentRollup { @Override
public SentimentClass apply(List<Sentence> input)
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/pig/ANALYZE_SENTIMENT.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentAnalyzer.java // public enum SentimentAnalyzer implements Function<String, SentimentClass> { // INSTANCE; // // @Override // public SentimentClass apply(String document) // { // // shut off the annoying intialization messages // Properties props = new Properties(); // //specify the annotators that we want to use to annotate the text. We need a tokenized sentence with POS tags to extract sentiment. // //this forms our pipeline // props.setProperty("annotators", "tokenize, ssplit, parse, sentiment"); // StanfordCoreNLP pipeline = new StanfordCoreNLP(props); // Annotation annotation = pipeline.process(document); // List<Sentence> sentences = new ArrayList<Sentence>(); // /* // * We're going to iterate over all of the sentences and extract the sentiment. We'll adopt a majority rule policy // */ // for( CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) // { // //for each sentence, we get the sentiment that CoreNLP thinks this sentence indicates. // Tree sentimentTree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class); // int sentimentClassIdx = RNNCoreAnnotations.getPredictedClass(sentimentTree); // SentimentClass sentimentClass = SentimentClass.getSpecific(sentimentClassIdx); // // /* // * Each possible sentiment has an associated probability, so let's pull the entire // * set of probabilities across all sentiment classes. // */ // double[] probs = new double[SentimentClass.values().length]; // { // SimpleMatrix mat = RNNCoreAnnotations.getPredictions(sentimentTree); // for(int i = 0;i < SentimentClass.values().length;++i) // { // probs[i] = mat.get(i); // } // } // /* // * Add the sentence and the associated probabilities to our list. // */ // String sentenceStr = AnnotationUtils.sentenceToString(sentence).replace("\n", ""); // sentences.add(new Sentence(probs, sentenceStr, sentimentClass)); // } // // /* // * Finally, rollup the score of the entire document given the list of sentiments // * for each sentence. // * // * I have found that this is a surprisingly difficult thing. We're going to use the fact that // * we are mapping these documents onto Positive, Negative to use a technique that people use // * to figure out overall product ratings from individual star ratings, the Wilson Score. // * See http://www.evanmiller.org/how-not-to-sort-by-average-rating.html. // * // * For your convenience, I have implemented a number of other approaches, including: // * * Basic majority-rule voting // * * Max probability across all sentiments for all sentences // * * Last sentence wins // * * Longest sentence wins // * // */ // return SentimentRollup.WILSON_SCORE.apply(sentences); // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // }
import com.caseystella.ds.nlp.SentimentAnalyzer; import com.caseystella.ds.nlp.SentimentClass; import edu.stanford.nlp.util.logging.RedwoodConfiguration; import org.apache.pig.EvalFunc; import org.apache.pig.data.Tuple; import java.io.IOException;
package com.caseystella.ds.pig; /** * A pig UDF which accepts a document and returns a sentiment class: Positive or Negative * The assumptions are that this document is a movie review and uses, under the hood, the * Stanford CoreNLP Sentiment classifier. */ public class ANALYZE_SENTIMENT extends EvalFunc<String> { @Override public String exec(Tuple objects) throws IOException { //stop CoreNLP from printing to stdout RedwoodConfiguration.empty().capture(System.err).apply(); //grab the document String document = (String)objects.get(0); if(document == null || document.length() == 0) { //if the document is malformed, return null, which is to say, we don't know how to //handle it return null; } //Call out to our handler that we wrote to do the sentiment analysis
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentAnalyzer.java // public enum SentimentAnalyzer implements Function<String, SentimentClass> { // INSTANCE; // // @Override // public SentimentClass apply(String document) // { // // shut off the annoying intialization messages // Properties props = new Properties(); // //specify the annotators that we want to use to annotate the text. We need a tokenized sentence with POS tags to extract sentiment. // //this forms our pipeline // props.setProperty("annotators", "tokenize, ssplit, parse, sentiment"); // StanfordCoreNLP pipeline = new StanfordCoreNLP(props); // Annotation annotation = pipeline.process(document); // List<Sentence> sentences = new ArrayList<Sentence>(); // /* // * We're going to iterate over all of the sentences and extract the sentiment. We'll adopt a majority rule policy // */ // for( CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) // { // //for each sentence, we get the sentiment that CoreNLP thinks this sentence indicates. // Tree sentimentTree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class); // int sentimentClassIdx = RNNCoreAnnotations.getPredictedClass(sentimentTree); // SentimentClass sentimentClass = SentimentClass.getSpecific(sentimentClassIdx); // // /* // * Each possible sentiment has an associated probability, so let's pull the entire // * set of probabilities across all sentiment classes. // */ // double[] probs = new double[SentimentClass.values().length]; // { // SimpleMatrix mat = RNNCoreAnnotations.getPredictions(sentimentTree); // for(int i = 0;i < SentimentClass.values().length;++i) // { // probs[i] = mat.get(i); // } // } // /* // * Add the sentence and the associated probabilities to our list. // */ // String sentenceStr = AnnotationUtils.sentenceToString(sentence).replace("\n", ""); // sentences.add(new Sentence(probs, sentenceStr, sentimentClass)); // } // // /* // * Finally, rollup the score of the entire document given the list of sentiments // * for each sentence. // * // * I have found that this is a surprisingly difficult thing. We're going to use the fact that // * we are mapping these documents onto Positive, Negative to use a technique that people use // * to figure out overall product ratings from individual star ratings, the Wilson Score. // * See http://www.evanmiller.org/how-not-to-sort-by-average-rating.html. // * // * For your convenience, I have implemented a number of other approaches, including: // * * Basic majority-rule voting // * * Max probability across all sentiments for all sentences // * * Last sentence wins // * * Longest sentence wins // * // */ // return SentimentRollup.WILSON_SCORE.apply(sentences); // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/pig/ANALYZE_SENTIMENT.java import com.caseystella.ds.nlp.SentimentAnalyzer; import com.caseystella.ds.nlp.SentimentClass; import edu.stanford.nlp.util.logging.RedwoodConfiguration; import org.apache.pig.EvalFunc; import org.apache.pig.data.Tuple; import java.io.IOException; package com.caseystella.ds.pig; /** * A pig UDF which accepts a document and returns a sentiment class: Positive or Negative * The assumptions are that this document is a movie review and uses, under the hood, the * Stanford CoreNLP Sentiment classifier. */ public class ANALYZE_SENTIMENT extends EvalFunc<String> { @Override public String exec(Tuple objects) throws IOException { //stop CoreNLP from printing to stdout RedwoodConfiguration.empty().capture(System.err).apply(); //grab the document String document = (String)objects.get(0); if(document == null || document.length() == 0) { //if the document is malformed, return null, which is to say, we don't know how to //handle it return null; } //Call out to our handler that we wrote to do the sentiment analysis
SentimentClass sentimentClass = SentimentAnalyzer.INSTANCE.apply(document);
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/pig/ANALYZE_SENTIMENT.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentAnalyzer.java // public enum SentimentAnalyzer implements Function<String, SentimentClass> { // INSTANCE; // // @Override // public SentimentClass apply(String document) // { // // shut off the annoying intialization messages // Properties props = new Properties(); // //specify the annotators that we want to use to annotate the text. We need a tokenized sentence with POS tags to extract sentiment. // //this forms our pipeline // props.setProperty("annotators", "tokenize, ssplit, parse, sentiment"); // StanfordCoreNLP pipeline = new StanfordCoreNLP(props); // Annotation annotation = pipeline.process(document); // List<Sentence> sentences = new ArrayList<Sentence>(); // /* // * We're going to iterate over all of the sentences and extract the sentiment. We'll adopt a majority rule policy // */ // for( CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) // { // //for each sentence, we get the sentiment that CoreNLP thinks this sentence indicates. // Tree sentimentTree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class); // int sentimentClassIdx = RNNCoreAnnotations.getPredictedClass(sentimentTree); // SentimentClass sentimentClass = SentimentClass.getSpecific(sentimentClassIdx); // // /* // * Each possible sentiment has an associated probability, so let's pull the entire // * set of probabilities across all sentiment classes. // */ // double[] probs = new double[SentimentClass.values().length]; // { // SimpleMatrix mat = RNNCoreAnnotations.getPredictions(sentimentTree); // for(int i = 0;i < SentimentClass.values().length;++i) // { // probs[i] = mat.get(i); // } // } // /* // * Add the sentence and the associated probabilities to our list. // */ // String sentenceStr = AnnotationUtils.sentenceToString(sentence).replace("\n", ""); // sentences.add(new Sentence(probs, sentenceStr, sentimentClass)); // } // // /* // * Finally, rollup the score of the entire document given the list of sentiments // * for each sentence. // * // * I have found that this is a surprisingly difficult thing. We're going to use the fact that // * we are mapping these documents onto Positive, Negative to use a technique that people use // * to figure out overall product ratings from individual star ratings, the Wilson Score. // * See http://www.evanmiller.org/how-not-to-sort-by-average-rating.html. // * // * For your convenience, I have implemented a number of other approaches, including: // * * Basic majority-rule voting // * * Max probability across all sentiments for all sentences // * * Last sentence wins // * * Longest sentence wins // * // */ // return SentimentRollup.WILSON_SCORE.apply(sentences); // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // }
import com.caseystella.ds.nlp.SentimentAnalyzer; import com.caseystella.ds.nlp.SentimentClass; import edu.stanford.nlp.util.logging.RedwoodConfiguration; import org.apache.pig.EvalFunc; import org.apache.pig.data.Tuple; import java.io.IOException;
package com.caseystella.ds.pig; /** * A pig UDF which accepts a document and returns a sentiment class: Positive or Negative * The assumptions are that this document is a movie review and uses, under the hood, the * Stanford CoreNLP Sentiment classifier. */ public class ANALYZE_SENTIMENT extends EvalFunc<String> { @Override public String exec(Tuple objects) throws IOException { //stop CoreNLP from printing to stdout RedwoodConfiguration.empty().capture(System.err).apply(); //grab the document String document = (String)objects.get(0); if(document == null || document.length() == 0) { //if the document is malformed, return null, which is to say, we don't know how to //handle it return null; } //Call out to our handler that we wrote to do the sentiment analysis
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentAnalyzer.java // public enum SentimentAnalyzer implements Function<String, SentimentClass> { // INSTANCE; // // @Override // public SentimentClass apply(String document) // { // // shut off the annoying intialization messages // Properties props = new Properties(); // //specify the annotators that we want to use to annotate the text. We need a tokenized sentence with POS tags to extract sentiment. // //this forms our pipeline // props.setProperty("annotators", "tokenize, ssplit, parse, sentiment"); // StanfordCoreNLP pipeline = new StanfordCoreNLP(props); // Annotation annotation = pipeline.process(document); // List<Sentence> sentences = new ArrayList<Sentence>(); // /* // * We're going to iterate over all of the sentences and extract the sentiment. We'll adopt a majority rule policy // */ // for( CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) // { // //for each sentence, we get the sentiment that CoreNLP thinks this sentence indicates. // Tree sentimentTree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class); // int sentimentClassIdx = RNNCoreAnnotations.getPredictedClass(sentimentTree); // SentimentClass sentimentClass = SentimentClass.getSpecific(sentimentClassIdx); // // /* // * Each possible sentiment has an associated probability, so let's pull the entire // * set of probabilities across all sentiment classes. // */ // double[] probs = new double[SentimentClass.values().length]; // { // SimpleMatrix mat = RNNCoreAnnotations.getPredictions(sentimentTree); // for(int i = 0;i < SentimentClass.values().length;++i) // { // probs[i] = mat.get(i); // } // } // /* // * Add the sentence and the associated probabilities to our list. // */ // String sentenceStr = AnnotationUtils.sentenceToString(sentence).replace("\n", ""); // sentences.add(new Sentence(probs, sentenceStr, sentimentClass)); // } // // /* // * Finally, rollup the score of the entire document given the list of sentiments // * for each sentence. // * // * I have found that this is a surprisingly difficult thing. We're going to use the fact that // * we are mapping these documents onto Positive, Negative to use a technique that people use // * to figure out overall product ratings from individual star ratings, the Wilson Score. // * See http://www.evanmiller.org/how-not-to-sort-by-average-rating.html. // * // * For your convenience, I have implemented a number of other approaches, including: // * * Basic majority-rule voting // * * Max probability across all sentiments for all sentences // * * Last sentence wins // * * Longest sentence wins // * // */ // return SentimentRollup.WILSON_SCORE.apply(sentences); // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/pig/ANALYZE_SENTIMENT.java import com.caseystella.ds.nlp.SentimentAnalyzer; import com.caseystella.ds.nlp.SentimentClass; import edu.stanford.nlp.util.logging.RedwoodConfiguration; import org.apache.pig.EvalFunc; import org.apache.pig.data.Tuple; import java.io.IOException; package com.caseystella.ds.pig; /** * A pig UDF which accepts a document and returns a sentiment class: Positive or Negative * The assumptions are that this document is a movie review and uses, under the hood, the * Stanford CoreNLP Sentiment classifier. */ public class ANALYZE_SENTIMENT extends EvalFunc<String> { @Override public String exec(Tuple objects) throws IOException { //stop CoreNLP from printing to stdout RedwoodConfiguration.empty().capture(System.err).apply(); //grab the document String document = (String)objects.get(0); if(document == null || document.length() == 0) { //if the document is malformed, return null, which is to say, we don't know how to //handle it return null; } //Call out to our handler that we wrote to do the sentiment analysis
SentimentClass sentimentClass = SentimentAnalyzer.INSTANCE.apply(document);
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/LastSentenceWins.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // }
import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.List;
package com.caseystella.ds.nlp.rollup.strategy; /** * Created by cstella on 3/26/14. */ public class LastSentenceWins implements ISentimentRollup{ @Override
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/LastSentenceWins.java import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.List; package com.caseystella.ds.nlp.rollup.strategy; /** * Created by cstella on 3/26/14. */ public class LastSentenceWins implements ISentimentRollup{ @Override
public SentimentClass apply(List<Sentence> input) {
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/LastSentenceWins.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // }
import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.List;
package com.caseystella.ds.nlp.rollup.strategy; /** * Created by cstella on 3/26/14. */ public class LastSentenceWins implements ISentimentRollup{ @Override
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/LastSentenceWins.java import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.List; package com.caseystella.ds.nlp.rollup.strategy; /** * Created by cstella on 3/26/14. */ public class LastSentenceWins implements ISentimentRollup{ @Override
public SentimentClass apply(List<Sentence> input) {
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/LongestSentenceWins.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // }
import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.List;
package com.caseystella.ds.nlp.rollup.strategy; /** * Created by cstella on 3/26/14. */ public class LongestSentenceWins implements ISentimentRollup { @Override
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/LongestSentenceWins.java import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.List; package com.caseystella.ds.nlp.rollup.strategy; /** * Created by cstella on 3/26/14. */ public class LongestSentenceWins implements ISentimentRollup { @Override
public SentimentClass apply(List<Sentence> input) {
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/LongestSentenceWins.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // }
import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.List;
package com.caseystella.ds.nlp.rollup.strategy; /** * Created by cstella on 3/26/14. */ public class LongestSentenceWins implements ISentimentRollup { @Override
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/LongestSentenceWins.java import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.List; package com.caseystella.ds.nlp.rollup.strategy; /** * Created by cstella on 3/26/14. */ public class LongestSentenceWins implements ISentimentRollup { @Override
public SentimentClass apply(List<Sentence> input) {
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/WilsonScore.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // }
import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.List;
if (qn < 0.0 || 1.0 < qn) return 0.0; if (qn == 0.5) return 0.0; double w1 = qn; if (qn > 0.5) w1 = 1.0 - w1; double w3 = -Math.log(4.0 * w1 * (1.0 - w1)); w1 = b[0]; int i = 1; for (; i < 11; i++) w1 += b[i] * Math.pow(w3, i); if (qn > 0.5) return Math.sqrt(w1 * w3); return -Math.sqrt(w1 * w3); } public static double ci_lower_bound(int pos, int n, double power) { if (n == 0) return 0.0; double z = pnormaldist(1 - power / 2); double phat = 1.0 * pos / n; return (phat + z * z / (2 * n) - z * Math.sqrt((phat * (1 - phat) + z * z / (4 * n)) / n)) / (1 + z * z / n); } @Override
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/WilsonScore.java import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.List; if (qn < 0.0 || 1.0 < qn) return 0.0; if (qn == 0.5) return 0.0; double w1 = qn; if (qn > 0.5) w1 = 1.0 - w1; double w3 = -Math.log(4.0 * w1 * (1.0 - w1)); w1 = b[0]; int i = 1; for (; i < 11; i++) w1 += b[i] * Math.pow(w3, i); if (qn > 0.5) return Math.sqrt(w1 * w3); return -Math.sqrt(w1 * w3); } public static double ci_lower_bound(int pos, int n, double power) { if (n == 0) return 0.0; double z = pnormaldist(1 - power / 2); double phat = 1.0 * pos / n; return (phat + z * z / (2 * n) - z * Math.sqrt((phat * (1 - phat) + z * z / (4 * n)) / n)) / (1 + z * z / n); } @Override
public SentimentClass apply(List<Sentence> input) {
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/WilsonScore.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // }
import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.List;
if (qn < 0.0 || 1.0 < qn) return 0.0; if (qn == 0.5) return 0.0; double w1 = qn; if (qn > 0.5) w1 = 1.0 - w1; double w3 = -Math.log(4.0 * w1 * (1.0 - w1)); w1 = b[0]; int i = 1; for (; i < 11; i++) w1 += b[i] * Math.pow(w3, i); if (qn > 0.5) return Math.sqrt(w1 * w3); return -Math.sqrt(w1 * w3); } public static double ci_lower_bound(int pos, int n, double power) { if (n == 0) return 0.0; double z = pnormaldist(1 - power / 2); double phat = 1.0 * pos / n; return (phat + z * z / (2 * n) - z * Math.sqrt((phat * (1 - phat) + z * z / (4 * n)) / n)) / (1 + z * z / n); } @Override
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/WilsonScore.java import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.List; if (qn < 0.0 || 1.0 < qn) return 0.0; if (qn == 0.5) return 0.0; double w1 = qn; if (qn > 0.5) w1 = 1.0 - w1; double w3 = -Math.log(4.0 * w1 * (1.0 - w1)); w1 = b[0]; int i = 1; for (; i < 11; i++) w1 += b[i] * Math.pow(w3, i); if (qn > 0.5) return Math.sqrt(w1 * w3); return -Math.sqrt(w1 * w3); } public static double ci_lower_bound(int pos, int n, double power) { if (n == 0) return 0.0; double z = pnormaldist(1 - power / 2); double phat = 1.0 * pos / n; return (phat + z * z / (2 * n) - z * Math.sqrt((phat * (1 - phat) + z * z / (4 * n)) / n)) / (1 + z * z / n); } @Override
public SentimentClass apply(List<Sentence> input) {
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/util/EvaluateRollupApproaches.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/SentimentRollup.java // public enum SentimentRollup implements ISentimentRollup { // SIMPLE_VOTE(new SimpleVoteRollup()) // ,AVERAGE_PROBABILITIES(new AverageProbabilitiesRollup()) // , LAST_SENTENCE_WINS(new LastSentenceWins()) // , LONGEST_SENTENCE_WINS(new LongestSentenceWins()) // , WILSON_SCORE(new WilsonScore()) // ; // // private ISentimentRollup proxy; // SentimentRollup(ISentimentRollup proxy) { this.proxy = proxy;} // // @Override // public SentimentClass apply(List<Sentence> input) { // return proxy.apply(input); // } // }
import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.Sentence; import com.caseystella.ds.nlp.rollup.SentimentRollup; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import java.io.*; import java.util.ArrayList; import java.util.List;
package com.caseystella.ds.nlp.rollup.util; /** * This is a utility that is intended to evaluate rollup approaches from some pre-processed data. */ public class EvaluateRollupApproaches { private static class Document {
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/SentimentRollup.java // public enum SentimentRollup implements ISentimentRollup { // SIMPLE_VOTE(new SimpleVoteRollup()) // ,AVERAGE_PROBABILITIES(new AverageProbabilitiesRollup()) // , LAST_SENTENCE_WINS(new LastSentenceWins()) // , LONGEST_SENTENCE_WINS(new LongestSentenceWins()) // , WILSON_SCORE(new WilsonScore()) // ; // // private ISentimentRollup proxy; // SentimentRollup(ISentimentRollup proxy) { this.proxy = proxy;} // // @Override // public SentimentClass apply(List<Sentence> input) { // return proxy.apply(input); // } // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/util/EvaluateRollupApproaches.java import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.Sentence; import com.caseystella.ds.nlp.rollup.SentimentRollup; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import java.io.*; import java.util.ArrayList; import java.util.List; package com.caseystella.ds.nlp.rollup.util; /** * This is a utility that is intended to evaluate rollup approaches from some pre-processed data. */ public class EvaluateRollupApproaches { private static class Document {
List<Sentence> sentences;
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/util/EvaluateRollupApproaches.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/SentimentRollup.java // public enum SentimentRollup implements ISentimentRollup { // SIMPLE_VOTE(new SimpleVoteRollup()) // ,AVERAGE_PROBABILITIES(new AverageProbabilitiesRollup()) // , LAST_SENTENCE_WINS(new LastSentenceWins()) // , LONGEST_SENTENCE_WINS(new LongestSentenceWins()) // , WILSON_SCORE(new WilsonScore()) // ; // // private ISentimentRollup proxy; // SentimentRollup(ISentimentRollup proxy) { this.proxy = proxy;} // // @Override // public SentimentClass apply(List<Sentence> input) { // return proxy.apply(input); // } // }
import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.Sentence; import com.caseystella.ds.nlp.rollup.SentimentRollup; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import java.io.*; import java.util.ArrayList; import java.util.List;
package com.caseystella.ds.nlp.rollup.util; /** * This is a utility that is intended to evaluate rollup approaches from some pre-processed data. */ public class EvaluateRollupApproaches { private static class Document { List<Sentence> sentences;
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/SentimentRollup.java // public enum SentimentRollup implements ISentimentRollup { // SIMPLE_VOTE(new SimpleVoteRollup()) // ,AVERAGE_PROBABILITIES(new AverageProbabilitiesRollup()) // , LAST_SENTENCE_WINS(new LastSentenceWins()) // , LONGEST_SENTENCE_WINS(new LongestSentenceWins()) // , WILSON_SCORE(new WilsonScore()) // ; // // private ISentimentRollup proxy; // SentimentRollup(ISentimentRollup proxy) { this.proxy = proxy;} // // @Override // public SentimentClass apply(List<Sentence> input) { // return proxy.apply(input); // } // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/util/EvaluateRollupApproaches.java import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.Sentence; import com.caseystella.ds.nlp.rollup.SentimentRollup; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import java.io.*; import java.util.ArrayList; import java.util.List; package com.caseystella.ds.nlp.rollup.util; /** * This is a utility that is intended to evaluate rollup approaches from some pre-processed data. */ public class EvaluateRollupApproaches { private static class Document { List<Sentence> sentences;
SentimentClass actualSentiment;
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/util/EvaluateRollupApproaches.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/SentimentRollup.java // public enum SentimentRollup implements ISentimentRollup { // SIMPLE_VOTE(new SimpleVoteRollup()) // ,AVERAGE_PROBABILITIES(new AverageProbabilitiesRollup()) // , LAST_SENTENCE_WINS(new LastSentenceWins()) // , LONGEST_SENTENCE_WINS(new LongestSentenceWins()) // , WILSON_SCORE(new WilsonScore()) // ; // // private ISentimentRollup proxy; // SentimentRollup(ISentimentRollup proxy) { this.proxy = proxy;} // // @Override // public SentimentClass apply(List<Sentence> input) { // return proxy.apply(input); // } // }
import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.Sentence; import com.caseystella.ds.nlp.rollup.SentimentRollup; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import java.io.*; import java.util.ArrayList; import java.util.List;
} private static void addFile(File inputFile, List<Document> documents, SentimentClass actualSentiment) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(inputFile)); for(String line = null; (line = reader.readLine()) != null;) { Iterable<String> sentences = Splitter.on('\u0001').split(line); Document document = new Document(); document.actualSentiment = actualSentiment; document.sentences = new ArrayList<Sentence>(); for(String sentenceStr : sentences) { Iterable<String> split = Splitter.on('\u0002').split(sentenceStr); String content = Iterables.getFirst(split, ""); Iterable<String> tmpStr= Splitter.on(',').split(Iterables.getLast(split, "")); SentimentClass sentenceClass = SentimentClass.valueOf(Iterables.getFirst(tmpStr, "")); Iterable<String> probsStr = Splitter.on(';').split(Iterables.getLast(tmpStr, "")); double[] probs = new double[SentimentClass.values().length]; int i = 0; for(String probStr : probsStr) { probs[i++] = Double.parseDouble(probStr); } Sentence sentence = new Sentence(probs, content, sentenceClass); document.sentences.add(sentence); } documents.add(document); } }
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/SentimentRollup.java // public enum SentimentRollup implements ISentimentRollup { // SIMPLE_VOTE(new SimpleVoteRollup()) // ,AVERAGE_PROBABILITIES(new AverageProbabilitiesRollup()) // , LAST_SENTENCE_WINS(new LastSentenceWins()) // , LONGEST_SENTENCE_WINS(new LongestSentenceWins()) // , WILSON_SCORE(new WilsonScore()) // ; // // private ISentimentRollup proxy; // SentimentRollup(ISentimentRollup proxy) { this.proxy = proxy;} // // @Override // public SentimentClass apply(List<Sentence> input) { // return proxy.apply(input); // } // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/util/EvaluateRollupApproaches.java import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.Sentence; import com.caseystella.ds.nlp.rollup.SentimentRollup; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import java.io.*; import java.util.ArrayList; import java.util.List; } private static void addFile(File inputFile, List<Document> documents, SentimentClass actualSentiment) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(inputFile)); for(String line = null; (line = reader.readLine()) != null;) { Iterable<String> sentences = Splitter.on('\u0001').split(line); Document document = new Document(); document.actualSentiment = actualSentiment; document.sentences = new ArrayList<Sentence>(); for(String sentenceStr : sentences) { Iterable<String> split = Splitter.on('\u0002').split(sentenceStr); String content = Iterables.getFirst(split, ""); Iterable<String> tmpStr= Splitter.on(',').split(Iterables.getLast(split, "")); SentimentClass sentenceClass = SentimentClass.valueOf(Iterables.getFirst(tmpStr, "")); Iterable<String> probsStr = Splitter.on(';').split(Iterables.getLast(tmpStr, "")); double[] probs = new double[SentimentClass.values().length]; int i = 0; for(String probStr : probsStr) { probs[i++] = Double.parseDouble(probStr); } Sentence sentence = new Sentence(probs, content, sentenceClass); document.sentences.add(sentence); } documents.add(document); } }
public static void evaluate(SentimentRollup rollup, List<Document> documents )
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentAnalyzer.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/SentimentRollup.java // public enum SentimentRollup implements ISentimentRollup { // SIMPLE_VOTE(new SimpleVoteRollup()) // ,AVERAGE_PROBABILITIES(new AverageProbabilitiesRollup()) // , LAST_SENTENCE_WINS(new LastSentenceWins()) // , LONGEST_SENTENCE_WINS(new LongestSentenceWins()) // , WILSON_SCORE(new WilsonScore()) // ; // // private ISentimentRollup proxy; // SentimentRollup(ISentimentRollup proxy) { this.proxy = proxy;} // // @Override // public SentimentClass apply(List<Sentence> input) { // return proxy.apply(input); // } // }
import com.caseystella.ds.nlp.rollup.Sentence; import com.caseystella.ds.nlp.rollup.SentimentRollup; import com.google.common.base.Function; import edu.stanford.nlp.ie.machinereading.structure.AnnotationUtils; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.sentiment.SentimentCoreAnnotations; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.util.CoreMap; import edu.stanford.nlp.util.logging.RedwoodConfiguration; import org.ejml.simple.SimpleMatrix; import java.util.*;
package com.caseystella.ds.nlp; /** * Created by cstella on 3/21/14. */ public enum SentimentAnalyzer implements Function<String, SentimentClass> { INSTANCE; @Override public SentimentClass apply(String document) { // shut off the annoying intialization messages Properties props = new Properties(); //specify the annotators that we want to use to annotate the text. We need a tokenized sentence with POS tags to extract sentiment. //this forms our pipeline props.setProperty("annotators", "tokenize, ssplit, parse, sentiment"); StanfordCoreNLP pipeline = new StanfordCoreNLP(props); Annotation annotation = pipeline.process(document);
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/SentimentRollup.java // public enum SentimentRollup implements ISentimentRollup { // SIMPLE_VOTE(new SimpleVoteRollup()) // ,AVERAGE_PROBABILITIES(new AverageProbabilitiesRollup()) // , LAST_SENTENCE_WINS(new LastSentenceWins()) // , LONGEST_SENTENCE_WINS(new LongestSentenceWins()) // , WILSON_SCORE(new WilsonScore()) // ; // // private ISentimentRollup proxy; // SentimentRollup(ISentimentRollup proxy) { this.proxy = proxy;} // // @Override // public SentimentClass apply(List<Sentence> input) { // return proxy.apply(input); // } // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentAnalyzer.java import com.caseystella.ds.nlp.rollup.Sentence; import com.caseystella.ds.nlp.rollup.SentimentRollup; import com.google.common.base.Function; import edu.stanford.nlp.ie.machinereading.structure.AnnotationUtils; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.sentiment.SentimentCoreAnnotations; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.util.CoreMap; import edu.stanford.nlp.util.logging.RedwoodConfiguration; import org.ejml.simple.SimpleMatrix; import java.util.*; package com.caseystella.ds.nlp; /** * Created by cstella on 3/21/14. */ public enum SentimentAnalyzer implements Function<String, SentimentClass> { INSTANCE; @Override public SentimentClass apply(String document) { // shut off the annoying intialization messages Properties props = new Properties(); //specify the annotators that we want to use to annotate the text. We need a tokenized sentence with POS tags to extract sentiment. //this forms our pipeline props.setProperty("annotators", "tokenize, ssplit, parse, sentiment"); StanfordCoreNLP pipeline = new StanfordCoreNLP(props); Annotation annotation = pipeline.process(document);
List<Sentence> sentences = new ArrayList<Sentence>();
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentAnalyzer.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/SentimentRollup.java // public enum SentimentRollup implements ISentimentRollup { // SIMPLE_VOTE(new SimpleVoteRollup()) // ,AVERAGE_PROBABILITIES(new AverageProbabilitiesRollup()) // , LAST_SENTENCE_WINS(new LastSentenceWins()) // , LONGEST_SENTENCE_WINS(new LongestSentenceWins()) // , WILSON_SCORE(new WilsonScore()) // ; // // private ISentimentRollup proxy; // SentimentRollup(ISentimentRollup proxy) { this.proxy = proxy;} // // @Override // public SentimentClass apply(List<Sentence> input) { // return proxy.apply(input); // } // }
import com.caseystella.ds.nlp.rollup.Sentence; import com.caseystella.ds.nlp.rollup.SentimentRollup; import com.google.common.base.Function; import edu.stanford.nlp.ie.machinereading.structure.AnnotationUtils; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.sentiment.SentimentCoreAnnotations; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.util.CoreMap; import edu.stanford.nlp.util.logging.RedwoodConfiguration; import org.ejml.simple.SimpleMatrix; import java.util.*;
package com.caseystella.ds.nlp; /** * Created by cstella on 3/21/14. */ public enum SentimentAnalyzer implements Function<String, SentimentClass> { INSTANCE; @Override public SentimentClass apply(String document) { // shut off the annoying intialization messages Properties props = new Properties(); //specify the annotators that we want to use to annotate the text. We need a tokenized sentence with POS tags to extract sentiment. //this forms our pipeline props.setProperty("annotators", "tokenize, ssplit, parse, sentiment"); StanfordCoreNLP pipeline = new StanfordCoreNLP(props); Annotation annotation = pipeline.process(document); List<Sentence> sentences = new ArrayList<Sentence>(); /* * We're going to iterate over all of the sentences and extract the sentiment. We'll adopt a majority rule policy */ for( CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) { //for each sentence, we get the sentiment that CoreNLP thinks this sentence indicates. Tree sentimentTree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class); int sentimentClassIdx = RNNCoreAnnotations.getPredictedClass(sentimentTree); SentimentClass sentimentClass = SentimentClass.getSpecific(sentimentClassIdx); /* * Each possible sentiment has an associated probability, so let's pull the entire * set of probabilities across all sentiment classes. */ double[] probs = new double[SentimentClass.values().length]; { SimpleMatrix mat = RNNCoreAnnotations.getPredictions(sentimentTree); for(int i = 0;i < SentimentClass.values().length;++i) { probs[i] = mat.get(i); } } /* * Add the sentence and the associated probabilities to our list. */ String sentenceStr = AnnotationUtils.sentenceToString(sentence).replace("\n", ""); sentences.add(new Sentence(probs, sentenceStr, sentimentClass)); } /* * Finally, rollup the score of the entire document given the list of sentiments * for each sentence. * * I have found that this is a surprisingly difficult thing. We're going to use the fact that * we are mapping these documents onto Positive, Negative to use a technique that people use * to figure out overall product ratings from individual star ratings, the Wilson Score. * See http://www.evanmiller.org/how-not-to-sort-by-average-rating.html. * * For your convenience, I have implemented a number of other approaches, including: * * Basic majority-rule voting * * Max probability across all sentiments for all sentences * * Last sentence wins * * Longest sentence wins * */
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/SentimentRollup.java // public enum SentimentRollup implements ISentimentRollup { // SIMPLE_VOTE(new SimpleVoteRollup()) // ,AVERAGE_PROBABILITIES(new AverageProbabilitiesRollup()) // , LAST_SENTENCE_WINS(new LastSentenceWins()) // , LONGEST_SENTENCE_WINS(new LongestSentenceWins()) // , WILSON_SCORE(new WilsonScore()) // ; // // private ISentimentRollup proxy; // SentimentRollup(ISentimentRollup proxy) { this.proxy = proxy;} // // @Override // public SentimentClass apply(List<Sentence> input) { // return proxy.apply(input); // } // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentAnalyzer.java import com.caseystella.ds.nlp.rollup.Sentence; import com.caseystella.ds.nlp.rollup.SentimentRollup; import com.google.common.base.Function; import edu.stanford.nlp.ie.machinereading.structure.AnnotationUtils; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.sentiment.SentimentCoreAnnotations; import edu.stanford.nlp.trees.Tree; import edu.stanford.nlp.util.CoreMap; import edu.stanford.nlp.util.logging.RedwoodConfiguration; import org.ejml.simple.SimpleMatrix; import java.util.*; package com.caseystella.ds.nlp; /** * Created by cstella on 3/21/14. */ public enum SentimentAnalyzer implements Function<String, SentimentClass> { INSTANCE; @Override public SentimentClass apply(String document) { // shut off the annoying intialization messages Properties props = new Properties(); //specify the annotators that we want to use to annotate the text. We need a tokenized sentence with POS tags to extract sentiment. //this forms our pipeline props.setProperty("annotators", "tokenize, ssplit, parse, sentiment"); StanfordCoreNLP pipeline = new StanfordCoreNLP(props); Annotation annotation = pipeline.process(document); List<Sentence> sentences = new ArrayList<Sentence>(); /* * We're going to iterate over all of the sentences and extract the sentiment. We'll adopt a majority rule policy */ for( CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) { //for each sentence, we get the sentiment that CoreNLP thinks this sentence indicates. Tree sentimentTree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class); int sentimentClassIdx = RNNCoreAnnotations.getPredictedClass(sentimentTree); SentimentClass sentimentClass = SentimentClass.getSpecific(sentimentClassIdx); /* * Each possible sentiment has an associated probability, so let's pull the entire * set of probabilities across all sentiment classes. */ double[] probs = new double[SentimentClass.values().length]; { SimpleMatrix mat = RNNCoreAnnotations.getPredictions(sentimentTree); for(int i = 0;i < SentimentClass.values().length;++i) { probs[i] = mat.get(i); } } /* * Add the sentence and the associated probabilities to our list. */ String sentenceStr = AnnotationUtils.sentenceToString(sentence).replace("\n", ""); sentences.add(new Sentence(probs, sentenceStr, sentimentClass)); } /* * Finally, rollup the score of the entire document given the list of sentiments * for each sentence. * * I have found that this is a surprisingly difficult thing. We're going to use the fact that * we are mapping these documents onto Positive, Negative to use a technique that people use * to figure out overall product ratings from individual star ratings, the Wilson Score. * See http://www.evanmiller.org/how-not-to-sort-by-average-rating.html. * * For your convenience, I have implemented a number of other approaches, including: * * Basic majority-rule voting * * Max probability across all sentiments for all sentences * * Last sentence wins * * Longest sentence wins * */
return SentimentRollup.WILSON_SCORE.apply(sentences);
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/AverageProbabilitiesRollup.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // }
import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.List;
package com.caseystella.ds.nlp.rollup.strategy; /** * Created by cstella on 3/25/14. */ public class AverageProbabilitiesRollup implements ISentimentRollup { @Override
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/AverageProbabilitiesRollup.java import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.List; package com.caseystella.ds.nlp.rollup.strategy; /** * Created by cstella on 3/25/14. */ public class AverageProbabilitiesRollup implements ISentimentRollup { @Override
public SentimentClass apply(List<Sentence> input)
cestella/presentations
Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/AverageProbabilitiesRollup.java
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // }
import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.List;
package com.caseystella.ds.nlp.rollup.strategy; /** * Created by cstella on 3/25/14. */ public class AverageProbabilitiesRollup implements ISentimentRollup { @Override
// Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/SentimentClass.java // public enum SentimentClass { // VERY_NEGATIVE(0) // , NEGATIVE(1) // , NEUTRAL(2) // , POSITIVE(3) // , VERY_POSITIVE(4) // ; // private int index = -1; // SentimentClass(int idx) // { // index = idx; // } // public int getIndex() { return index;} // public static SentimentClass getSpecific(int sentimentClass) // { // return SentimentClass.values()[sentimentClass]; // } // // public static SentimentClass getGeneral(int sentimentClass) // { // //remove the extreme cases // if(sentimentClass == 0) sentimentClass = 1; // if(sentimentClass == 4) sentimentClass = 3; // return SentimentClass.values()[sentimentClass]; // } // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/ISentimentRollup.java // public interface ISentimentRollup extends Function<List<Sentence>, SentimentClass> // { // // } // // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/Sentence.java // public class Sentence { // private EnumMap<SentimentClass, Double> sentimentProbabilities; // private String sentence; // private SentimentClass sentimentClass; // // public Sentence( double[] sentimentProbabilities // , String sentence // , SentimentClass sentimentClass // ) // { // this.sentence = sentence; // this.sentimentClass = sentimentClass; // this.sentimentProbabilities = new EnumMap<SentimentClass, Double>(SentimentClass.class); // for(int i = 0;i < sentimentProbabilities.length;++i) // { // this.sentimentProbabilities.put(SentimentClass.values()[i], sentimentProbabilities[i]); // } // } // // public String getSentence() { return sentence;} // public EnumMap<SentimentClass, Double> getSentimentProbabilities() { return sentimentProbabilities;} // public SentimentClass getSentiment() { return sentimentClass;} // } // Path: Hadoop_Summit_Pig_for_Data_Science/src/main/java/com/caseystella/ds/nlp/rollup/strategy/AverageProbabilitiesRollup.java import com.caseystella.ds.nlp.SentimentClass; import com.caseystella.ds.nlp.rollup.ISentimentRollup; import com.caseystella.ds.nlp.rollup.Sentence; import java.util.List; package com.caseystella.ds.nlp.rollup.strategy; /** * Created by cstella on 3/25/14. */ public class AverageProbabilitiesRollup implements ISentimentRollup { @Override
public SentimentClass apply(List<Sentence> input)
BartoszJarocki/android-starter
app/src/main/java/com/starter/data/local/model/ContributorEntity.java
// Path: app/src/main/java/com/starter/data/remote/model/ContributorJson.java // public final class ContributorJson { // private static final String LOGIN = "login"; // private static final String CONTRIBUTIONS = "contributions"; // private static final String AVATAR_URL = "avatar_url"; // // @SerializedName(LOGIN) public final String login; // @SerializedName(CONTRIBUTIONS) public final int contributions; // @SerializedName(AVATAR_URL) public final String avatarUrl; // // public ContributorJson(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final ContributorJson that = (ContributorJson) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // }
import com.starter.data.remote.model.ContributorJson; import io.objectbox.annotation.Entity; import io.objectbox.annotation.Generated; import io.objectbox.annotation.Id;
package com.starter.data.local.model; @Entity public final class ContributorEntity { @Id private long id; private String login; private int contributions; private String avatarUrl; public ContributorEntity(final String login, final int contributions, final String avatarUrl) { this.login = login; this.contributions = contributions; this.avatarUrl = avatarUrl; } @Generated(hash = 605867117) public ContributorEntity(long id, String login, int contributions, String avatarUrl) { this.id = id; this.login = login; this.contributions = contributions; this.avatarUrl = avatarUrl; } @Generated(hash = 536984865) public ContributorEntity() { }
// Path: app/src/main/java/com/starter/data/remote/model/ContributorJson.java // public final class ContributorJson { // private static final String LOGIN = "login"; // private static final String CONTRIBUTIONS = "contributions"; // private static final String AVATAR_URL = "avatar_url"; // // @SerializedName(LOGIN) public final String login; // @SerializedName(CONTRIBUTIONS) public final int contributions; // @SerializedName(AVATAR_URL) public final String avatarUrl; // // public ContributorJson(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final ContributorJson that = (ContributorJson) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // } // Path: app/src/main/java/com/starter/data/local/model/ContributorEntity.java import com.starter.data.remote.model.ContributorJson; import io.objectbox.annotation.Entity; import io.objectbox.annotation.Generated; import io.objectbox.annotation.Id; package com.starter.data.local.model; @Entity public final class ContributorEntity { @Id private long id; private String login; private int contributions; private String avatarUrl; public ContributorEntity(final String login, final int contributions, final String avatarUrl) { this.login = login; this.contributions = contributions; this.avatarUrl = avatarUrl; } @Generated(hash = 605867117) public ContributorEntity(long id, String login, int contributions, String avatarUrl) { this.id = id; this.login = login; this.contributions = contributions; this.avatarUrl = avatarUrl; } @Generated(hash = 536984865) public ContributorEntity() { }
public ContributorEntity(final ContributorJson contributor) {
BartoszJarocki/android-starter
app/src/main/java/com/starter/data/model/Contributor.java
// Path: app/src/main/java/com/starter/data/local/model/ContributorEntity.java // @Entity // public final class ContributorEntity { // @Id private long id; // // private String login; // private int contributions; // private String avatarUrl; // // public ContributorEntity(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // @Generated(hash = 605867117) // public ContributorEntity(long id, String login, int contributions, String avatarUrl) { // this.id = id; // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // @Generated(hash = 536984865) // public ContributorEntity() { // } // // public ContributorEntity(final ContributorJson contributor) { // this.login = contributor.getLogin(); // this.contributions = contributor.getContributions(); // this.avatarUrl = contributor.getAvatarUrl(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final ContributorEntity that = (ContributorEntity) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public long getId() { // return id; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // // public void setId(long id) { // this.id = id; // } // // public void setLogin(String login) { // this.login = login; // } // // public void setContributions(int contributions) { // this.contributions = contributions; // } // // public void setAvatarUrl(String avatarUrl) { // this.avatarUrl = avatarUrl; // } // } // // Path: app/src/main/java/com/starter/data/remote/model/ContributorJson.java // public final class ContributorJson { // private static final String LOGIN = "login"; // private static final String CONTRIBUTIONS = "contributions"; // private static final String AVATAR_URL = "avatar_url"; // // @SerializedName(LOGIN) public final String login; // @SerializedName(CONTRIBUTIONS) public final int contributions; // @SerializedName(AVATAR_URL) public final String avatarUrl; // // public ContributorJson(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final ContributorJson that = (ContributorJson) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // }
import com.starter.data.local.model.ContributorEntity; import com.starter.data.remote.model.ContributorJson;
package com.starter.data.model; public final class Contributor { private final String login; private final int contributions; private final String avatarUrl; public Contributor(final String login, final int contributions, final String avatarUrl) { this.login = login; this.contributions = contributions; this.avatarUrl = avatarUrl; }
// Path: app/src/main/java/com/starter/data/local/model/ContributorEntity.java // @Entity // public final class ContributorEntity { // @Id private long id; // // private String login; // private int contributions; // private String avatarUrl; // // public ContributorEntity(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // @Generated(hash = 605867117) // public ContributorEntity(long id, String login, int contributions, String avatarUrl) { // this.id = id; // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // @Generated(hash = 536984865) // public ContributorEntity() { // } // // public ContributorEntity(final ContributorJson contributor) { // this.login = contributor.getLogin(); // this.contributions = contributor.getContributions(); // this.avatarUrl = contributor.getAvatarUrl(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final ContributorEntity that = (ContributorEntity) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public long getId() { // return id; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // // public void setId(long id) { // this.id = id; // } // // public void setLogin(String login) { // this.login = login; // } // // public void setContributions(int contributions) { // this.contributions = contributions; // } // // public void setAvatarUrl(String avatarUrl) { // this.avatarUrl = avatarUrl; // } // } // // Path: app/src/main/java/com/starter/data/remote/model/ContributorJson.java // public final class ContributorJson { // private static final String LOGIN = "login"; // private static final String CONTRIBUTIONS = "contributions"; // private static final String AVATAR_URL = "avatar_url"; // // @SerializedName(LOGIN) public final String login; // @SerializedName(CONTRIBUTIONS) public final int contributions; // @SerializedName(AVATAR_URL) public final String avatarUrl; // // public ContributorJson(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final ContributorJson that = (ContributorJson) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // } // Path: app/src/main/java/com/starter/data/model/Contributor.java import com.starter.data.local.model.ContributorEntity; import com.starter.data.remote.model.ContributorJson; package com.starter.data.model; public final class Contributor { private final String login; private final int contributions; private final String avatarUrl; public Contributor(final String login, final int contributions, final String avatarUrl) { this.login = login; this.contributions = contributions; this.avatarUrl = avatarUrl; }
public Contributor(final ContributorJson contributorJson) {
BartoszJarocki/android-starter
app/src/main/java/com/starter/data/model/Contributor.java
// Path: app/src/main/java/com/starter/data/local/model/ContributorEntity.java // @Entity // public final class ContributorEntity { // @Id private long id; // // private String login; // private int contributions; // private String avatarUrl; // // public ContributorEntity(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // @Generated(hash = 605867117) // public ContributorEntity(long id, String login, int contributions, String avatarUrl) { // this.id = id; // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // @Generated(hash = 536984865) // public ContributorEntity() { // } // // public ContributorEntity(final ContributorJson contributor) { // this.login = contributor.getLogin(); // this.contributions = contributor.getContributions(); // this.avatarUrl = contributor.getAvatarUrl(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final ContributorEntity that = (ContributorEntity) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public long getId() { // return id; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // // public void setId(long id) { // this.id = id; // } // // public void setLogin(String login) { // this.login = login; // } // // public void setContributions(int contributions) { // this.contributions = contributions; // } // // public void setAvatarUrl(String avatarUrl) { // this.avatarUrl = avatarUrl; // } // } // // Path: app/src/main/java/com/starter/data/remote/model/ContributorJson.java // public final class ContributorJson { // private static final String LOGIN = "login"; // private static final String CONTRIBUTIONS = "contributions"; // private static final String AVATAR_URL = "avatar_url"; // // @SerializedName(LOGIN) public final String login; // @SerializedName(CONTRIBUTIONS) public final int contributions; // @SerializedName(AVATAR_URL) public final String avatarUrl; // // public ContributorJson(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final ContributorJson that = (ContributorJson) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // }
import com.starter.data.local.model.ContributorEntity; import com.starter.data.remote.model.ContributorJson;
package com.starter.data.model; public final class Contributor { private final String login; private final int contributions; private final String avatarUrl; public Contributor(final String login, final int contributions, final String avatarUrl) { this.login = login; this.contributions = contributions; this.avatarUrl = avatarUrl; } public Contributor(final ContributorJson contributorJson) { this.login = contributorJson.getLogin(); this.contributions = contributorJson.getContributions(); this.avatarUrl = contributorJson.getAvatarUrl(); }
// Path: app/src/main/java/com/starter/data/local/model/ContributorEntity.java // @Entity // public final class ContributorEntity { // @Id private long id; // // private String login; // private int contributions; // private String avatarUrl; // // public ContributorEntity(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // @Generated(hash = 605867117) // public ContributorEntity(long id, String login, int contributions, String avatarUrl) { // this.id = id; // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // @Generated(hash = 536984865) // public ContributorEntity() { // } // // public ContributorEntity(final ContributorJson contributor) { // this.login = contributor.getLogin(); // this.contributions = contributor.getContributions(); // this.avatarUrl = contributor.getAvatarUrl(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final ContributorEntity that = (ContributorEntity) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public long getId() { // return id; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // // public void setId(long id) { // this.id = id; // } // // public void setLogin(String login) { // this.login = login; // } // // public void setContributions(int contributions) { // this.contributions = contributions; // } // // public void setAvatarUrl(String avatarUrl) { // this.avatarUrl = avatarUrl; // } // } // // Path: app/src/main/java/com/starter/data/remote/model/ContributorJson.java // public final class ContributorJson { // private static final String LOGIN = "login"; // private static final String CONTRIBUTIONS = "contributions"; // private static final String AVATAR_URL = "avatar_url"; // // @SerializedName(LOGIN) public final String login; // @SerializedName(CONTRIBUTIONS) public final int contributions; // @SerializedName(AVATAR_URL) public final String avatarUrl; // // public ContributorJson(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final ContributorJson that = (ContributorJson) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // } // Path: app/src/main/java/com/starter/data/model/Contributor.java import com.starter.data.local.model.ContributorEntity; import com.starter.data.remote.model.ContributorJson; package com.starter.data.model; public final class Contributor { private final String login; private final int contributions; private final String avatarUrl; public Contributor(final String login, final int contributions, final String avatarUrl) { this.login = login; this.contributions = contributions; this.avatarUrl = avatarUrl; } public Contributor(final ContributorJson contributorJson) { this.login = contributorJson.getLogin(); this.contributions = contributorJson.getContributions(); this.avatarUrl = contributorJson.getAvatarUrl(); }
public Contributor(final ContributorEntity contributorEntity) {
BartoszJarocki/android-starter
app/src/main/java/com/starter/ui/contributors/ContributorsPresenter.java
// Path: app/src/main/java/com/starter/data/AppRepository.java // public class AppRepository implements Repository { // // private final LocalRepository localRepository; // private final RemoteRepository remoteRepository; // // @Inject // public AppRepository(final LocalRepository localRepository, // final RemoteRepository remoteRepository) { // this.localRepository = localRepository; // this.remoteRepository = remoteRepository; // } // // @Override // public Observable<List<Contributor>> contributors(final String owner, final String repo) { // return Observable.concat(remoteRepository.contributors(owner, repo), // localRepository.contributors(owner, repo)) // .first(contributorsResponse -> !contributorsResponse.isEmpty()); // } // } // // Path: app/src/main/java/com/starter/data/model/Contributor.java // public final class Contributor { // private final String login; // private final int contributions; // private final String avatarUrl; // // public Contributor(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // public Contributor(final ContributorJson contributorJson) { // this.login = contributorJson.getLogin(); // this.contributions = contributorJson.getContributions(); // this.avatarUrl = contributorJson.getAvatarUrl(); // } // // public Contributor(final ContributorEntity contributorEntity) { // this.login = contributorEntity.getLogin(); // this.contributions = contributorEntity.getContributions(); // this.avatarUrl = contributorEntity.getAvatarUrl(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final Contributor that = (Contributor) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // } // // Path: app/src/main/java/com/starter/ui/base/mvp/core/MvpBasePresenter.java // public class MvpBasePresenter<V extends MvpView> implements MvpPresenter<V> { // // private WeakReference<V> viewRef; // // @Override // public void attachView(V view) { // viewRef = new WeakReference<V>(view); // } // // @Override // public void detachView() { // if (viewRef != null) { // viewRef.clear(); // viewRef = null; // } // } // // /** // * Get the attached view. You should always call {@link #isViewAttached()} to check if the view // * is // * attached to avoid NullPointerExceptions. // * // * @return <code>null</code>, if view is not attached, otherwise the concrete view instance // */ // @Nullable // public V getView() { // return viewRef == null ? null : viewRef.get(); // } // // /** // * Checks if a view is attached to this presenter. You should always call this method before // * calling {@link #getView()} to get the view instance. // */ // public boolean isViewAttached() { // return viewRef != null && viewRef.get() != null; // } // }
import com.starter.data.AppRepository; import com.starter.data.model.Contributor; import com.starter.ui.base.mvp.core.MvpBasePresenter; import java.util.List; import rx.Subscriber; import rx.Subscription; import timber.log.Timber;
package com.starter.ui.contributors; public class ContributorsPresenter extends MvpBasePresenter<ContributorsView> { private AppRepository appRepository; private Subscription subscription; public ContributorsPresenter(final AppRepository appRepository) { this.appRepository = appRepository; } public void loadContributors(String owner, String repo, boolean pullToRefresh) { if (isViewAttached()) { getView().showProgress(pullToRefresh); } subscription =
// Path: app/src/main/java/com/starter/data/AppRepository.java // public class AppRepository implements Repository { // // private final LocalRepository localRepository; // private final RemoteRepository remoteRepository; // // @Inject // public AppRepository(final LocalRepository localRepository, // final RemoteRepository remoteRepository) { // this.localRepository = localRepository; // this.remoteRepository = remoteRepository; // } // // @Override // public Observable<List<Contributor>> contributors(final String owner, final String repo) { // return Observable.concat(remoteRepository.contributors(owner, repo), // localRepository.contributors(owner, repo)) // .first(contributorsResponse -> !contributorsResponse.isEmpty()); // } // } // // Path: app/src/main/java/com/starter/data/model/Contributor.java // public final class Contributor { // private final String login; // private final int contributions; // private final String avatarUrl; // // public Contributor(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // public Contributor(final ContributorJson contributorJson) { // this.login = contributorJson.getLogin(); // this.contributions = contributorJson.getContributions(); // this.avatarUrl = contributorJson.getAvatarUrl(); // } // // public Contributor(final ContributorEntity contributorEntity) { // this.login = contributorEntity.getLogin(); // this.contributions = contributorEntity.getContributions(); // this.avatarUrl = contributorEntity.getAvatarUrl(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final Contributor that = (Contributor) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // } // // Path: app/src/main/java/com/starter/ui/base/mvp/core/MvpBasePresenter.java // public class MvpBasePresenter<V extends MvpView> implements MvpPresenter<V> { // // private WeakReference<V> viewRef; // // @Override // public void attachView(V view) { // viewRef = new WeakReference<V>(view); // } // // @Override // public void detachView() { // if (viewRef != null) { // viewRef.clear(); // viewRef = null; // } // } // // /** // * Get the attached view. You should always call {@link #isViewAttached()} to check if the view // * is // * attached to avoid NullPointerExceptions. // * // * @return <code>null</code>, if view is not attached, otherwise the concrete view instance // */ // @Nullable // public V getView() { // return viewRef == null ? null : viewRef.get(); // } // // /** // * Checks if a view is attached to this presenter. You should always call this method before // * calling {@link #getView()} to get the view instance. // */ // public boolean isViewAttached() { // return viewRef != null && viewRef.get() != null; // } // } // Path: app/src/main/java/com/starter/ui/contributors/ContributorsPresenter.java import com.starter.data.AppRepository; import com.starter.data.model.Contributor; import com.starter.ui.base.mvp.core.MvpBasePresenter; import java.util.List; import rx.Subscriber; import rx.Subscription; import timber.log.Timber; package com.starter.ui.contributors; public class ContributorsPresenter extends MvpBasePresenter<ContributorsView> { private AppRepository appRepository; private Subscription subscription; public ContributorsPresenter(final AppRepository appRepository) { this.appRepository = appRepository; } public void loadContributors(String owner, String repo, boolean pullToRefresh) { if (isViewAttached()) { getView().showProgress(pullToRefresh); } subscription =
appRepository.contributors(owner, repo).subscribe(new Subscriber<List<Contributor>>() {
BartoszJarocki/android-starter
app/src/main/java/com/starter/di/AppModule.java
// Path: app/src/main/java/com/starter/data/preferences/ApplicationPreferences.java // public class ApplicationPreferences { // private static final String KEY_SENT_GCM_TOKEN_TO_SERVER = "KEY_SENT_GCM_TOKEN_TO_SERVER"; // // SharedPreferences sharedPreferences = null; // // public ApplicationPreferences(SharedPreferences sharedPreferences) { // this.sharedPreferences = sharedPreferences; // } // } // // Path: app/src/main/java/com/starter/utils/ThreadConfiguration.java // public class ThreadConfiguration { // private Scheduler subscribeOnScheduler; // private Scheduler observeOnScheduler; // // public ThreadConfiguration(final Scheduler subscribeOnScheduler, // final Scheduler observeOnScheduler) { // this.subscribeOnScheduler = subscribeOnScheduler; // this.observeOnScheduler = observeOnScheduler; // } // // public <T> Observable.Transformer<T, T> applySchedulers() { // return observable -> observable.subscribeOn(subscribeOnScheduler) // .observeOn(observeOnScheduler); // } // }
import android.app.Application; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.jakewharton.picasso.OkHttp3Downloader; import com.squareup.picasso.Picasso; import com.starter.data.preferences.ApplicationPreferences; import com.starter.utils.ThreadConfiguration; import dagger.Module; import dagger.Provides; import java.io.File; import javax.inject.Singleton; import okhttp3.Cache; import okhttp3.OkHttpClient; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package com.starter.di; @Module public class AppModule { private static final String IMAGE_CACHE_DIR = "cache_images"; private static final int IMAGE_DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB private final Application application; public AppModule(Application application) { this.application = application; } @Provides @Singleton Application provideApplication() { return application; } @Provides @Singleton Picasso providePicasso(final Application app) { final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); File cacheDir = new File(app.getCacheDir(), IMAGE_CACHE_DIR); httpBuilder.cache(new Cache(cacheDir, IMAGE_DISK_CACHE_SIZE)); final OkHttp3Downloader okHttpDownloader = new OkHttp3Downloader(httpBuilder.build()); return new Picasso.Builder(app).downloader(okHttpDownloader).indicatorsEnabled(true).build(); } @Provides @Singleton SharedPreferences provideSharedPreferences(Application app) { return PreferenceManager.getDefaultSharedPreferences(app); } @Provides @Singleton
// Path: app/src/main/java/com/starter/data/preferences/ApplicationPreferences.java // public class ApplicationPreferences { // private static final String KEY_SENT_GCM_TOKEN_TO_SERVER = "KEY_SENT_GCM_TOKEN_TO_SERVER"; // // SharedPreferences sharedPreferences = null; // // public ApplicationPreferences(SharedPreferences sharedPreferences) { // this.sharedPreferences = sharedPreferences; // } // } // // Path: app/src/main/java/com/starter/utils/ThreadConfiguration.java // public class ThreadConfiguration { // private Scheduler subscribeOnScheduler; // private Scheduler observeOnScheduler; // // public ThreadConfiguration(final Scheduler subscribeOnScheduler, // final Scheduler observeOnScheduler) { // this.subscribeOnScheduler = subscribeOnScheduler; // this.observeOnScheduler = observeOnScheduler; // } // // public <T> Observable.Transformer<T, T> applySchedulers() { // return observable -> observable.subscribeOn(subscribeOnScheduler) // .observeOn(observeOnScheduler); // } // } // Path: app/src/main/java/com/starter/di/AppModule.java import android.app.Application; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.jakewharton.picasso.OkHttp3Downloader; import com.squareup.picasso.Picasso; import com.starter.data.preferences.ApplicationPreferences; import com.starter.utils.ThreadConfiguration; import dagger.Module; import dagger.Provides; import java.io.File; import javax.inject.Singleton; import okhttp3.Cache; import okhttp3.OkHttpClient; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; package com.starter.di; @Module public class AppModule { private static final String IMAGE_CACHE_DIR = "cache_images"; private static final int IMAGE_DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB private final Application application; public AppModule(Application application) { this.application = application; } @Provides @Singleton Application provideApplication() { return application; } @Provides @Singleton Picasso providePicasso(final Application app) { final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); File cacheDir = new File(app.getCacheDir(), IMAGE_CACHE_DIR); httpBuilder.cache(new Cache(cacheDir, IMAGE_DISK_CACHE_SIZE)); final OkHttp3Downloader okHttpDownloader = new OkHttp3Downloader(httpBuilder.build()); return new Picasso.Builder(app).downloader(okHttpDownloader).indicatorsEnabled(true).build(); } @Provides @Singleton SharedPreferences provideSharedPreferences(Application app) { return PreferenceManager.getDefaultSharedPreferences(app); } @Provides @Singleton
ThreadConfiguration provideThreadConfiguration() {
BartoszJarocki/android-starter
app/src/main/java/com/starter/di/AppModule.java
// Path: app/src/main/java/com/starter/data/preferences/ApplicationPreferences.java // public class ApplicationPreferences { // private static final String KEY_SENT_GCM_TOKEN_TO_SERVER = "KEY_SENT_GCM_TOKEN_TO_SERVER"; // // SharedPreferences sharedPreferences = null; // // public ApplicationPreferences(SharedPreferences sharedPreferences) { // this.sharedPreferences = sharedPreferences; // } // } // // Path: app/src/main/java/com/starter/utils/ThreadConfiguration.java // public class ThreadConfiguration { // private Scheduler subscribeOnScheduler; // private Scheduler observeOnScheduler; // // public ThreadConfiguration(final Scheduler subscribeOnScheduler, // final Scheduler observeOnScheduler) { // this.subscribeOnScheduler = subscribeOnScheduler; // this.observeOnScheduler = observeOnScheduler; // } // // public <T> Observable.Transformer<T, T> applySchedulers() { // return observable -> observable.subscribeOn(subscribeOnScheduler) // .observeOn(observeOnScheduler); // } // }
import android.app.Application; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.jakewharton.picasso.OkHttp3Downloader; import com.squareup.picasso.Picasso; import com.starter.data.preferences.ApplicationPreferences; import com.starter.utils.ThreadConfiguration; import dagger.Module; import dagger.Provides; import java.io.File; import javax.inject.Singleton; import okhttp3.Cache; import okhttp3.OkHttpClient; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
Application provideApplication() { return application; } @Provides @Singleton Picasso providePicasso(final Application app) { final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); File cacheDir = new File(app.getCacheDir(), IMAGE_CACHE_DIR); httpBuilder.cache(new Cache(cacheDir, IMAGE_DISK_CACHE_SIZE)); final OkHttp3Downloader okHttpDownloader = new OkHttp3Downloader(httpBuilder.build()); return new Picasso.Builder(app).downloader(okHttpDownloader).indicatorsEnabled(true).build(); } @Provides @Singleton SharedPreferences provideSharedPreferences(Application app) { return PreferenceManager.getDefaultSharedPreferences(app); } @Provides @Singleton ThreadConfiguration provideThreadConfiguration() { return new ThreadConfiguration(Schedulers.io(), AndroidSchedulers.mainThread()); } @Provides @Singleton
// Path: app/src/main/java/com/starter/data/preferences/ApplicationPreferences.java // public class ApplicationPreferences { // private static final String KEY_SENT_GCM_TOKEN_TO_SERVER = "KEY_SENT_GCM_TOKEN_TO_SERVER"; // // SharedPreferences sharedPreferences = null; // // public ApplicationPreferences(SharedPreferences sharedPreferences) { // this.sharedPreferences = sharedPreferences; // } // } // // Path: app/src/main/java/com/starter/utils/ThreadConfiguration.java // public class ThreadConfiguration { // private Scheduler subscribeOnScheduler; // private Scheduler observeOnScheduler; // // public ThreadConfiguration(final Scheduler subscribeOnScheduler, // final Scheduler observeOnScheduler) { // this.subscribeOnScheduler = subscribeOnScheduler; // this.observeOnScheduler = observeOnScheduler; // } // // public <T> Observable.Transformer<T, T> applySchedulers() { // return observable -> observable.subscribeOn(subscribeOnScheduler) // .observeOn(observeOnScheduler); // } // } // Path: app/src/main/java/com/starter/di/AppModule.java import android.app.Application; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.jakewharton.picasso.OkHttp3Downloader; import com.squareup.picasso.Picasso; import com.starter.data.preferences.ApplicationPreferences; import com.starter.utils.ThreadConfiguration; import dagger.Module; import dagger.Provides; import java.io.File; import javax.inject.Singleton; import okhttp3.Cache; import okhttp3.OkHttpClient; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; Application provideApplication() { return application; } @Provides @Singleton Picasso providePicasso(final Application app) { final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); File cacheDir = new File(app.getCacheDir(), IMAGE_CACHE_DIR); httpBuilder.cache(new Cache(cacheDir, IMAGE_DISK_CACHE_SIZE)); final OkHttp3Downloader okHttpDownloader = new OkHttp3Downloader(httpBuilder.build()); return new Picasso.Builder(app).downloader(okHttpDownloader).indicatorsEnabled(true).build(); } @Provides @Singleton SharedPreferences provideSharedPreferences(Application app) { return PreferenceManager.getDefaultSharedPreferences(app); } @Provides @Singleton ThreadConfiguration provideThreadConfiguration() { return new ThreadConfiguration(Schedulers.io(), AndroidSchedulers.mainThread()); } @Provides @Singleton
ApplicationPreferences provideApplicationPreferences(SharedPreferences sharedPreferences) {
BartoszJarocki/android-starter
app/src/main/java/com/starter/data/remote/RemoteRepository.java
// Path: app/src/main/java/com/starter/data/Repository.java // public interface Repository { // Observable<List<Contributor>> contributors(String owner, String repo); // } // // Path: app/src/main/java/com/starter/data/local/LocalRepository.java // public class LocalRepository implements Repository { // private final Box<ContributorEntity> localContributorBox; // private final ThreadConfiguration threadConfiguration; // private final ContributorsJsonsToContributorEntitiesMapper // contributorsJsonsToContributorEntitiesMapper = // new ContributorsJsonsToContributorEntitiesMapper(); // private final ContributorsEntitiesToContributorsMapper entitiesToContributorsMapper = // new ContributorsEntitiesToContributorsMapper(); // // public LocalRepository(final Box<ContributorEntity> localContributorBox, // final ThreadConfiguration threadConfiguration) { // this.localContributorBox = localContributorBox; // this.threadConfiguration = threadConfiguration; // } // // @Override // public Observable<List<Contributor>> contributors(final String owner, final String repo) { // return Observable.defer(() -> Observable.just(localContributorBox.getAll())) // .flatMap(contributorEntities -> Observable.just( // entitiesToContributorsMapper.map(contributorEntities))) // .compose(threadConfiguration.applySchedulers()); // } // // public void put(final List<ContributorJson> contributorJsons) { // localContributorBox.put(contributorsJsonsToContributorEntitiesMapper.map(contributorJsons)); // } // } // // Path: app/src/main/java/com/starter/data/model/Contributor.java // public final class Contributor { // private final String login; // private final int contributions; // private final String avatarUrl; // // public Contributor(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // public Contributor(final ContributorJson contributorJson) { // this.login = contributorJson.getLogin(); // this.contributions = contributorJson.getContributions(); // this.avatarUrl = contributorJson.getAvatarUrl(); // } // // public Contributor(final ContributorEntity contributorEntity) { // this.login = contributorEntity.getLogin(); // this.contributions = contributorEntity.getContributions(); // this.avatarUrl = contributorEntity.getAvatarUrl(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final Contributor that = (Contributor) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // } // // Path: app/src/main/java/com/starter/data/model/mappers/ContributorsJsonsToContributorListMapper.java // public class ContributorsJsonsToContributorListMapper // implements Mapper<List<ContributorJson>, List<Contributor>> { // // @Override // public List<Contributor> map(final List<ContributorJson> contributors) { // List<Contributor> contributorEntities = new ArrayList<>(); // for (ContributorJson contributor : contributors) { // contributorEntities.add(new Contributor(contributor)); // } // // return contributorEntities; // } // } // // Path: app/src/main/java/com/starter/utils/ThreadConfiguration.java // public class ThreadConfiguration { // private Scheduler subscribeOnScheduler; // private Scheduler observeOnScheduler; // // public ThreadConfiguration(final Scheduler subscribeOnScheduler, // final Scheduler observeOnScheduler) { // this.subscribeOnScheduler = subscribeOnScheduler; // this.observeOnScheduler = observeOnScheduler; // } // // public <T> Observable.Transformer<T, T> applySchedulers() { // return observable -> observable.subscribeOn(subscribeOnScheduler) // .observeOn(observeOnScheduler); // } // }
import android.support.annotation.NonNull; import com.starter.data.Repository; import com.starter.data.local.LocalRepository; import com.starter.data.model.Contributor; import com.starter.data.model.mappers.ContributorsJsonsToContributorListMapper; import com.starter.utils.ThreadConfiguration; import java.io.IOException; import java.util.List; import javax.inject.Inject; import rx.Observable;
package com.starter.data.remote; public class RemoteRepository implements Repository { private final LocalRepository localRepository;
// Path: app/src/main/java/com/starter/data/Repository.java // public interface Repository { // Observable<List<Contributor>> contributors(String owner, String repo); // } // // Path: app/src/main/java/com/starter/data/local/LocalRepository.java // public class LocalRepository implements Repository { // private final Box<ContributorEntity> localContributorBox; // private final ThreadConfiguration threadConfiguration; // private final ContributorsJsonsToContributorEntitiesMapper // contributorsJsonsToContributorEntitiesMapper = // new ContributorsJsonsToContributorEntitiesMapper(); // private final ContributorsEntitiesToContributorsMapper entitiesToContributorsMapper = // new ContributorsEntitiesToContributorsMapper(); // // public LocalRepository(final Box<ContributorEntity> localContributorBox, // final ThreadConfiguration threadConfiguration) { // this.localContributorBox = localContributorBox; // this.threadConfiguration = threadConfiguration; // } // // @Override // public Observable<List<Contributor>> contributors(final String owner, final String repo) { // return Observable.defer(() -> Observable.just(localContributorBox.getAll())) // .flatMap(contributorEntities -> Observable.just( // entitiesToContributorsMapper.map(contributorEntities))) // .compose(threadConfiguration.applySchedulers()); // } // // public void put(final List<ContributorJson> contributorJsons) { // localContributorBox.put(contributorsJsonsToContributorEntitiesMapper.map(contributorJsons)); // } // } // // Path: app/src/main/java/com/starter/data/model/Contributor.java // public final class Contributor { // private final String login; // private final int contributions; // private final String avatarUrl; // // public Contributor(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // public Contributor(final ContributorJson contributorJson) { // this.login = contributorJson.getLogin(); // this.contributions = contributorJson.getContributions(); // this.avatarUrl = contributorJson.getAvatarUrl(); // } // // public Contributor(final ContributorEntity contributorEntity) { // this.login = contributorEntity.getLogin(); // this.contributions = contributorEntity.getContributions(); // this.avatarUrl = contributorEntity.getAvatarUrl(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final Contributor that = (Contributor) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // } // // Path: app/src/main/java/com/starter/data/model/mappers/ContributorsJsonsToContributorListMapper.java // public class ContributorsJsonsToContributorListMapper // implements Mapper<List<ContributorJson>, List<Contributor>> { // // @Override // public List<Contributor> map(final List<ContributorJson> contributors) { // List<Contributor> contributorEntities = new ArrayList<>(); // for (ContributorJson contributor : contributors) { // contributorEntities.add(new Contributor(contributor)); // } // // return contributorEntities; // } // } // // Path: app/src/main/java/com/starter/utils/ThreadConfiguration.java // public class ThreadConfiguration { // private Scheduler subscribeOnScheduler; // private Scheduler observeOnScheduler; // // public ThreadConfiguration(final Scheduler subscribeOnScheduler, // final Scheduler observeOnScheduler) { // this.subscribeOnScheduler = subscribeOnScheduler; // this.observeOnScheduler = observeOnScheduler; // } // // public <T> Observable.Transformer<T, T> applySchedulers() { // return observable -> observable.subscribeOn(subscribeOnScheduler) // .observeOn(observeOnScheduler); // } // } // Path: app/src/main/java/com/starter/data/remote/RemoteRepository.java import android.support.annotation.NonNull; import com.starter.data.Repository; import com.starter.data.local.LocalRepository; import com.starter.data.model.Contributor; import com.starter.data.model.mappers.ContributorsJsonsToContributorListMapper; import com.starter.utils.ThreadConfiguration; import java.io.IOException; import java.util.List; import javax.inject.Inject; import rx.Observable; package com.starter.data.remote; public class RemoteRepository implements Repository { private final LocalRepository localRepository;
private final ThreadConfiguration threadConfiguration;
BartoszJarocki/android-starter
app/src/main/java/com/starter/data/remote/RemoteRepository.java
// Path: app/src/main/java/com/starter/data/Repository.java // public interface Repository { // Observable<List<Contributor>> contributors(String owner, String repo); // } // // Path: app/src/main/java/com/starter/data/local/LocalRepository.java // public class LocalRepository implements Repository { // private final Box<ContributorEntity> localContributorBox; // private final ThreadConfiguration threadConfiguration; // private final ContributorsJsonsToContributorEntitiesMapper // contributorsJsonsToContributorEntitiesMapper = // new ContributorsJsonsToContributorEntitiesMapper(); // private final ContributorsEntitiesToContributorsMapper entitiesToContributorsMapper = // new ContributorsEntitiesToContributorsMapper(); // // public LocalRepository(final Box<ContributorEntity> localContributorBox, // final ThreadConfiguration threadConfiguration) { // this.localContributorBox = localContributorBox; // this.threadConfiguration = threadConfiguration; // } // // @Override // public Observable<List<Contributor>> contributors(final String owner, final String repo) { // return Observable.defer(() -> Observable.just(localContributorBox.getAll())) // .flatMap(contributorEntities -> Observable.just( // entitiesToContributorsMapper.map(contributorEntities))) // .compose(threadConfiguration.applySchedulers()); // } // // public void put(final List<ContributorJson> contributorJsons) { // localContributorBox.put(contributorsJsonsToContributorEntitiesMapper.map(contributorJsons)); // } // } // // Path: app/src/main/java/com/starter/data/model/Contributor.java // public final class Contributor { // private final String login; // private final int contributions; // private final String avatarUrl; // // public Contributor(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // public Contributor(final ContributorJson contributorJson) { // this.login = contributorJson.getLogin(); // this.contributions = contributorJson.getContributions(); // this.avatarUrl = contributorJson.getAvatarUrl(); // } // // public Contributor(final ContributorEntity contributorEntity) { // this.login = contributorEntity.getLogin(); // this.contributions = contributorEntity.getContributions(); // this.avatarUrl = contributorEntity.getAvatarUrl(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final Contributor that = (Contributor) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // } // // Path: app/src/main/java/com/starter/data/model/mappers/ContributorsJsonsToContributorListMapper.java // public class ContributorsJsonsToContributorListMapper // implements Mapper<List<ContributorJson>, List<Contributor>> { // // @Override // public List<Contributor> map(final List<ContributorJson> contributors) { // List<Contributor> contributorEntities = new ArrayList<>(); // for (ContributorJson contributor : contributors) { // contributorEntities.add(new Contributor(contributor)); // } // // return contributorEntities; // } // } // // Path: app/src/main/java/com/starter/utils/ThreadConfiguration.java // public class ThreadConfiguration { // private Scheduler subscribeOnScheduler; // private Scheduler observeOnScheduler; // // public ThreadConfiguration(final Scheduler subscribeOnScheduler, // final Scheduler observeOnScheduler) { // this.subscribeOnScheduler = subscribeOnScheduler; // this.observeOnScheduler = observeOnScheduler; // } // // public <T> Observable.Transformer<T, T> applySchedulers() { // return observable -> observable.subscribeOn(subscribeOnScheduler) // .observeOn(observeOnScheduler); // } // }
import android.support.annotation.NonNull; import com.starter.data.Repository; import com.starter.data.local.LocalRepository; import com.starter.data.model.Contributor; import com.starter.data.model.mappers.ContributorsJsonsToContributorListMapper; import com.starter.utils.ThreadConfiguration; import java.io.IOException; import java.util.List; import javax.inject.Inject; import rx.Observable;
package com.starter.data.remote; public class RemoteRepository implements Repository { private final LocalRepository localRepository; private final ThreadConfiguration threadConfiguration; private final GithubApi githubApi;
// Path: app/src/main/java/com/starter/data/Repository.java // public interface Repository { // Observable<List<Contributor>> contributors(String owner, String repo); // } // // Path: app/src/main/java/com/starter/data/local/LocalRepository.java // public class LocalRepository implements Repository { // private final Box<ContributorEntity> localContributorBox; // private final ThreadConfiguration threadConfiguration; // private final ContributorsJsonsToContributorEntitiesMapper // contributorsJsonsToContributorEntitiesMapper = // new ContributorsJsonsToContributorEntitiesMapper(); // private final ContributorsEntitiesToContributorsMapper entitiesToContributorsMapper = // new ContributorsEntitiesToContributorsMapper(); // // public LocalRepository(final Box<ContributorEntity> localContributorBox, // final ThreadConfiguration threadConfiguration) { // this.localContributorBox = localContributorBox; // this.threadConfiguration = threadConfiguration; // } // // @Override // public Observable<List<Contributor>> contributors(final String owner, final String repo) { // return Observable.defer(() -> Observable.just(localContributorBox.getAll())) // .flatMap(contributorEntities -> Observable.just( // entitiesToContributorsMapper.map(contributorEntities))) // .compose(threadConfiguration.applySchedulers()); // } // // public void put(final List<ContributorJson> contributorJsons) { // localContributorBox.put(contributorsJsonsToContributorEntitiesMapper.map(contributorJsons)); // } // } // // Path: app/src/main/java/com/starter/data/model/Contributor.java // public final class Contributor { // private final String login; // private final int contributions; // private final String avatarUrl; // // public Contributor(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // public Contributor(final ContributorJson contributorJson) { // this.login = contributorJson.getLogin(); // this.contributions = contributorJson.getContributions(); // this.avatarUrl = contributorJson.getAvatarUrl(); // } // // public Contributor(final ContributorEntity contributorEntity) { // this.login = contributorEntity.getLogin(); // this.contributions = contributorEntity.getContributions(); // this.avatarUrl = contributorEntity.getAvatarUrl(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final Contributor that = (Contributor) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // } // // Path: app/src/main/java/com/starter/data/model/mappers/ContributorsJsonsToContributorListMapper.java // public class ContributorsJsonsToContributorListMapper // implements Mapper<List<ContributorJson>, List<Contributor>> { // // @Override // public List<Contributor> map(final List<ContributorJson> contributors) { // List<Contributor> contributorEntities = new ArrayList<>(); // for (ContributorJson contributor : contributors) { // contributorEntities.add(new Contributor(contributor)); // } // // return contributorEntities; // } // } // // Path: app/src/main/java/com/starter/utils/ThreadConfiguration.java // public class ThreadConfiguration { // private Scheduler subscribeOnScheduler; // private Scheduler observeOnScheduler; // // public ThreadConfiguration(final Scheduler subscribeOnScheduler, // final Scheduler observeOnScheduler) { // this.subscribeOnScheduler = subscribeOnScheduler; // this.observeOnScheduler = observeOnScheduler; // } // // public <T> Observable.Transformer<T, T> applySchedulers() { // return observable -> observable.subscribeOn(subscribeOnScheduler) // .observeOn(observeOnScheduler); // } // } // Path: app/src/main/java/com/starter/data/remote/RemoteRepository.java import android.support.annotation.NonNull; import com.starter.data.Repository; import com.starter.data.local.LocalRepository; import com.starter.data.model.Contributor; import com.starter.data.model.mappers.ContributorsJsonsToContributorListMapper; import com.starter.utils.ThreadConfiguration; import java.io.IOException; import java.util.List; import javax.inject.Inject; import rx.Observable; package com.starter.data.remote; public class RemoteRepository implements Repository { private final LocalRepository localRepository; private final ThreadConfiguration threadConfiguration; private final GithubApi githubApi;
private final ContributorsJsonsToContributorListMapper
BartoszJarocki/android-starter
app/src/main/java/com/starter/data/remote/RemoteRepository.java
// Path: app/src/main/java/com/starter/data/Repository.java // public interface Repository { // Observable<List<Contributor>> contributors(String owner, String repo); // } // // Path: app/src/main/java/com/starter/data/local/LocalRepository.java // public class LocalRepository implements Repository { // private final Box<ContributorEntity> localContributorBox; // private final ThreadConfiguration threadConfiguration; // private final ContributorsJsonsToContributorEntitiesMapper // contributorsJsonsToContributorEntitiesMapper = // new ContributorsJsonsToContributorEntitiesMapper(); // private final ContributorsEntitiesToContributorsMapper entitiesToContributorsMapper = // new ContributorsEntitiesToContributorsMapper(); // // public LocalRepository(final Box<ContributorEntity> localContributorBox, // final ThreadConfiguration threadConfiguration) { // this.localContributorBox = localContributorBox; // this.threadConfiguration = threadConfiguration; // } // // @Override // public Observable<List<Contributor>> contributors(final String owner, final String repo) { // return Observable.defer(() -> Observable.just(localContributorBox.getAll())) // .flatMap(contributorEntities -> Observable.just( // entitiesToContributorsMapper.map(contributorEntities))) // .compose(threadConfiguration.applySchedulers()); // } // // public void put(final List<ContributorJson> contributorJsons) { // localContributorBox.put(contributorsJsonsToContributorEntitiesMapper.map(contributorJsons)); // } // } // // Path: app/src/main/java/com/starter/data/model/Contributor.java // public final class Contributor { // private final String login; // private final int contributions; // private final String avatarUrl; // // public Contributor(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // public Contributor(final ContributorJson contributorJson) { // this.login = contributorJson.getLogin(); // this.contributions = contributorJson.getContributions(); // this.avatarUrl = contributorJson.getAvatarUrl(); // } // // public Contributor(final ContributorEntity contributorEntity) { // this.login = contributorEntity.getLogin(); // this.contributions = contributorEntity.getContributions(); // this.avatarUrl = contributorEntity.getAvatarUrl(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final Contributor that = (Contributor) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // } // // Path: app/src/main/java/com/starter/data/model/mappers/ContributorsJsonsToContributorListMapper.java // public class ContributorsJsonsToContributorListMapper // implements Mapper<List<ContributorJson>, List<Contributor>> { // // @Override // public List<Contributor> map(final List<ContributorJson> contributors) { // List<Contributor> contributorEntities = new ArrayList<>(); // for (ContributorJson contributor : contributors) { // contributorEntities.add(new Contributor(contributor)); // } // // return contributorEntities; // } // } // // Path: app/src/main/java/com/starter/utils/ThreadConfiguration.java // public class ThreadConfiguration { // private Scheduler subscribeOnScheduler; // private Scheduler observeOnScheduler; // // public ThreadConfiguration(final Scheduler subscribeOnScheduler, // final Scheduler observeOnScheduler) { // this.subscribeOnScheduler = subscribeOnScheduler; // this.observeOnScheduler = observeOnScheduler; // } // // public <T> Observable.Transformer<T, T> applySchedulers() { // return observable -> observable.subscribeOn(subscribeOnScheduler) // .observeOn(observeOnScheduler); // } // }
import android.support.annotation.NonNull; import com.starter.data.Repository; import com.starter.data.local.LocalRepository; import com.starter.data.model.Contributor; import com.starter.data.model.mappers.ContributorsJsonsToContributorListMapper; import com.starter.utils.ThreadConfiguration; import java.io.IOException; import java.util.List; import javax.inject.Inject; import rx.Observable;
package com.starter.data.remote; public class RemoteRepository implements Repository { private final LocalRepository localRepository; private final ThreadConfiguration threadConfiguration; private final GithubApi githubApi; private final ContributorsJsonsToContributorListMapper contributorsJsonsToContributorListMapper = new ContributorsJsonsToContributorListMapper(); @Inject public RemoteRepository(final LocalRepository localRepository, @NonNull GithubApi githubApi, @NonNull ThreadConfiguration threadConfiguration) { this.localRepository = localRepository; this.githubApi = githubApi; this.threadConfiguration = threadConfiguration; }
// Path: app/src/main/java/com/starter/data/Repository.java // public interface Repository { // Observable<List<Contributor>> contributors(String owner, String repo); // } // // Path: app/src/main/java/com/starter/data/local/LocalRepository.java // public class LocalRepository implements Repository { // private final Box<ContributorEntity> localContributorBox; // private final ThreadConfiguration threadConfiguration; // private final ContributorsJsonsToContributorEntitiesMapper // contributorsJsonsToContributorEntitiesMapper = // new ContributorsJsonsToContributorEntitiesMapper(); // private final ContributorsEntitiesToContributorsMapper entitiesToContributorsMapper = // new ContributorsEntitiesToContributorsMapper(); // // public LocalRepository(final Box<ContributorEntity> localContributorBox, // final ThreadConfiguration threadConfiguration) { // this.localContributorBox = localContributorBox; // this.threadConfiguration = threadConfiguration; // } // // @Override // public Observable<List<Contributor>> contributors(final String owner, final String repo) { // return Observable.defer(() -> Observable.just(localContributorBox.getAll())) // .flatMap(contributorEntities -> Observable.just( // entitiesToContributorsMapper.map(contributorEntities))) // .compose(threadConfiguration.applySchedulers()); // } // // public void put(final List<ContributorJson> contributorJsons) { // localContributorBox.put(contributorsJsonsToContributorEntitiesMapper.map(contributorJsons)); // } // } // // Path: app/src/main/java/com/starter/data/model/Contributor.java // public final class Contributor { // private final String login; // private final int contributions; // private final String avatarUrl; // // public Contributor(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // public Contributor(final ContributorJson contributorJson) { // this.login = contributorJson.getLogin(); // this.contributions = contributorJson.getContributions(); // this.avatarUrl = contributorJson.getAvatarUrl(); // } // // public Contributor(final ContributorEntity contributorEntity) { // this.login = contributorEntity.getLogin(); // this.contributions = contributorEntity.getContributions(); // this.avatarUrl = contributorEntity.getAvatarUrl(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final Contributor that = (Contributor) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // } // // Path: app/src/main/java/com/starter/data/model/mappers/ContributorsJsonsToContributorListMapper.java // public class ContributorsJsonsToContributorListMapper // implements Mapper<List<ContributorJson>, List<Contributor>> { // // @Override // public List<Contributor> map(final List<ContributorJson> contributors) { // List<Contributor> contributorEntities = new ArrayList<>(); // for (ContributorJson contributor : contributors) { // contributorEntities.add(new Contributor(contributor)); // } // // return contributorEntities; // } // } // // Path: app/src/main/java/com/starter/utils/ThreadConfiguration.java // public class ThreadConfiguration { // private Scheduler subscribeOnScheduler; // private Scheduler observeOnScheduler; // // public ThreadConfiguration(final Scheduler subscribeOnScheduler, // final Scheduler observeOnScheduler) { // this.subscribeOnScheduler = subscribeOnScheduler; // this.observeOnScheduler = observeOnScheduler; // } // // public <T> Observable.Transformer<T, T> applySchedulers() { // return observable -> observable.subscribeOn(subscribeOnScheduler) // .observeOn(observeOnScheduler); // } // } // Path: app/src/main/java/com/starter/data/remote/RemoteRepository.java import android.support.annotation.NonNull; import com.starter.data.Repository; import com.starter.data.local.LocalRepository; import com.starter.data.model.Contributor; import com.starter.data.model.mappers.ContributorsJsonsToContributorListMapper; import com.starter.utils.ThreadConfiguration; import java.io.IOException; import java.util.List; import javax.inject.Inject; import rx.Observable; package com.starter.data.remote; public class RemoteRepository implements Repository { private final LocalRepository localRepository; private final ThreadConfiguration threadConfiguration; private final GithubApi githubApi; private final ContributorsJsonsToContributorListMapper contributorsJsonsToContributorListMapper = new ContributorsJsonsToContributorListMapper(); @Inject public RemoteRepository(final LocalRepository localRepository, @NonNull GithubApi githubApi, @NonNull ThreadConfiguration threadConfiguration) { this.localRepository = localRepository; this.githubApi = githubApi; this.threadConfiguration = threadConfiguration; }
public Observable<List<Contributor>> contributors(String owner, String repo) {
BartoszJarocki/android-starter
app/src/main/java/com/starter/data/remote/GithubApi.java
// Path: app/src/main/java/com/starter/data/remote/model/ContributorJson.java // public final class ContributorJson { // private static final String LOGIN = "login"; // private static final String CONTRIBUTIONS = "contributions"; // private static final String AVATAR_URL = "avatar_url"; // // @SerializedName(LOGIN) public final String login; // @SerializedName(CONTRIBUTIONS) public final int contributions; // @SerializedName(AVATAR_URL) public final String avatarUrl; // // public ContributorJson(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final ContributorJson that = (ContributorJson) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // }
import com.starter.data.remote.model.ContributorJson; import java.util.List; import retrofit2.Response; import retrofit2.http.GET; import retrofit2.http.Path; import rx.Observable;
package com.starter.data.remote; public interface GithubApi { @GET("/repos/{owner}/{repo}/contributors")
// Path: app/src/main/java/com/starter/data/remote/model/ContributorJson.java // public final class ContributorJson { // private static final String LOGIN = "login"; // private static final String CONTRIBUTIONS = "contributions"; // private static final String AVATAR_URL = "avatar_url"; // // @SerializedName(LOGIN) public final String login; // @SerializedName(CONTRIBUTIONS) public final int contributions; // @SerializedName(AVATAR_URL) public final String avatarUrl; // // public ContributorJson(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final ContributorJson that = (ContributorJson) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // } // Path: app/src/main/java/com/starter/data/remote/GithubApi.java import com.starter.data.remote.model.ContributorJson; import java.util.List; import retrofit2.Response; import retrofit2.http.GET; import retrofit2.http.Path; import rx.Observable; package com.starter.data.remote; public interface GithubApi { @GET("/repos/{owner}/{repo}/contributors")
Observable<Response<List<ContributorJson>>> contributors(@Path("owner") String owner,
BartoszJarocki/android-starter
app/src/androidTest/java/com/starter/StarterTestRunner.java
// Path: app/src/androidTest/java/com/starter/util/RxIdlingResource.java // public class RxIdlingResource implements IdlingResource { // // private final AtomicInteger activeSubscriptionsCount = new AtomicInteger(0); // private ResourceCallback resourceCallback; // // @Override // public String getName() { // return getClass().getSimpleName(); // } // // @Override // public void registerIdleTransitionCallback(ResourceCallback callback) { // resourceCallback = callback; // } // // public void incrementActiveSubscriptionsCount() { // int count = activeSubscriptionsCount.incrementAndGet(); // Timber.i("Active subscriptions count increased to %d", count); // } // // public void decrementActiveSubscriptionsCount() { // int count = activeSubscriptionsCount.decrementAndGet(); // Timber.i("Active subscriptions count decreased to %d", count); // if (isIdleNow()) { // Timber.i("There is no active subscriptions, transitioning to Idle"); // resourceCallback.onTransitionToIdle(); // } // } // // @Override // public boolean isIdleNow() { // return activeSubscriptionsCount.get() == 0; // } // }
import android.app.Application; import android.content.Context; import android.os.Bundle; import android.support.test.espresso.Espresso; import android.support.test.runner.AndroidJUnitRunner; import com.starter.util.RxIdlingResource; import io.appflate.restmock.RESTMockServerStarter; import io.appflate.restmock.android.AndroidAssetsFileParser; import io.appflate.restmock.android.AndroidLogger; import rx.plugins.RxJavaHooks;
package com.starter; public class StarterTestRunner extends AndroidJUnitRunner { @Override public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException { String testApplicationClassName = TestApplication.class.getCanonicalName(); return super.newApplication(cl, testApplicationClassName, context); } @Override public void onCreate(Bundle arguments) { super.onCreate(arguments); RESTMockServerStarter.startSync(new AndroidAssetsFileParser(this.getContext()), new AndroidLogger()); registerRxJavaIdlingResources(); } private void registerRxJavaIdlingResources() {
// Path: app/src/androidTest/java/com/starter/util/RxIdlingResource.java // public class RxIdlingResource implements IdlingResource { // // private final AtomicInteger activeSubscriptionsCount = new AtomicInteger(0); // private ResourceCallback resourceCallback; // // @Override // public String getName() { // return getClass().getSimpleName(); // } // // @Override // public void registerIdleTransitionCallback(ResourceCallback callback) { // resourceCallback = callback; // } // // public void incrementActiveSubscriptionsCount() { // int count = activeSubscriptionsCount.incrementAndGet(); // Timber.i("Active subscriptions count increased to %d", count); // } // // public void decrementActiveSubscriptionsCount() { // int count = activeSubscriptionsCount.decrementAndGet(); // Timber.i("Active subscriptions count decreased to %d", count); // if (isIdleNow()) { // Timber.i("There is no active subscriptions, transitioning to Idle"); // resourceCallback.onTransitionToIdle(); // } // } // // @Override // public boolean isIdleNow() { // return activeSubscriptionsCount.get() == 0; // } // } // Path: app/src/androidTest/java/com/starter/StarterTestRunner.java import android.app.Application; import android.content.Context; import android.os.Bundle; import android.support.test.espresso.Espresso; import android.support.test.runner.AndroidJUnitRunner; import com.starter.util.RxIdlingResource; import io.appflate.restmock.RESTMockServerStarter; import io.appflate.restmock.android.AndroidAssetsFileParser; import io.appflate.restmock.android.AndroidLogger; import rx.plugins.RxJavaHooks; package com.starter; public class StarterTestRunner extends AndroidJUnitRunner { @Override public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException { String testApplicationClassName = TestApplication.class.getCanonicalName(); return super.newApplication(cl, testApplicationClassName, context); } @Override public void onCreate(Bundle arguments) { super.onCreate(arguments); RESTMockServerStarter.startSync(new AndroidAssetsFileParser(this.getContext()), new AndroidLogger()); registerRxJavaIdlingResources(); } private void registerRxJavaIdlingResources() {
RxIdlingResource rxIdlingResource = new RxIdlingResource();
BartoszJarocki/android-starter
app/src/main/java/com/starter/StarterApplication.java
// Path: app/src/main/java/com/starter/data/di/DataModule.java // @Module // public class DataModule { // private static final int HTTP_DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB // private static final String HTTP_CACHE_DIR = "cache_http"; // private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm"; // // private final String apiBaseUrl; // // public DataModule(final String apiBaseUrl) { // this.apiBaseUrl = apiBaseUrl; // } // // @Provides // @Singleton // public Gson provideGson() { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.setDateFormat(DATE_FORMAT); // // return gsonBuilder.create(); // } // // @Provides // @Singleton // public OkHttpClient provideOkHttpClient(Application application) { // final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); // // // Install an HTTP cache in the application cache directory. // File cacheDir = new File(application.getCacheDir(), HTTP_CACHE_DIR); // Cache cache = new Cache(cacheDir, HTTP_DISK_CACHE_SIZE); // // final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS); // // httpBuilder.addInterceptor(interceptor); // httpBuilder.cache(cache); // // if (BuildConfig.DEBUG) { // httpBuilder.addNetworkInterceptor(new StethoInterceptor()); // } // // return httpBuilder.build(); // } // // @Provides // @Singleton // public Retrofit provideRetrofit(OkHttpClient client, Gson gson) { // return new Retrofit.Builder().baseUrl(apiBaseUrl) // .client(client) // .addConverterFactory(new ToStringConverterFactory()) // .addConverterFactory(GsonConverterFactory.create(gson)) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // } // // @Provides // @Singleton // public BoxStore providesObjectBox(Application application) { // return MyObjectBox.builder().androidContext(application).build(); // } // // @Provides // @Singleton // public Box<ContributorEntity> providesContributorsObjectBox(BoxStore boxStore) { // return boxStore.boxFor(ContributorEntity.class); // } // // @Provides // @Singleton // public GithubApi providesGithubApi(Retrofit retrofit) { // return retrofit.create(GithubApi.class); // } // // @Provides // @NonNull // @Singleton // public LocalRepository providesLocalRepository(Box<ContributorEntity> localContributorBox, // ThreadConfiguration threadConfiguration) { // return new LocalRepository(localContributorBox, threadConfiguration); // } // // @Provides // @Singleton // public RemoteRepository providesRemoteRepository(LocalRepository localRepository, // GithubApi githubApi, ThreadConfiguration threadConfiguration) { // return new RemoteRepository(localRepository, githubApi, threadConfiguration); // } // // @Provides // @Singleton // public AppRepository provideAppRepository(RemoteRepository remoteRepository, // LocalRepository localRepository) { // return new AppRepository(localRepository, remoteRepository); // } // } // // Path: app/src/main/java/com/starter/di/AppComponent.java // @Singleton // @Component(modules = { AppModule.class, DataModule.class }) // public interface AppComponent { // // Application getApplication(); // // SharedPreferences getSharedPreferences(); // // void inject(Application application); // // void inject(ContributorsActivity contributorsActivity); // } // // Path: app/src/main/java/com/starter/di/AppModule.java // @Module // public class AppModule { // private static final String IMAGE_CACHE_DIR = "cache_images"; // private static final int IMAGE_DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB // private final Application application; // // public AppModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // Application provideApplication() { // return application; // } // // @Provides // @Singleton // Picasso providePicasso(final Application app) { // final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); // // File cacheDir = new File(app.getCacheDir(), IMAGE_CACHE_DIR); // httpBuilder.cache(new Cache(cacheDir, IMAGE_DISK_CACHE_SIZE)); // final OkHttp3Downloader okHttpDownloader = new OkHttp3Downloader(httpBuilder.build()); // // return new Picasso.Builder(app).downloader(okHttpDownloader).indicatorsEnabled(true).build(); // } // // @Provides // @Singleton // SharedPreferences provideSharedPreferences(Application app) { // return PreferenceManager.getDefaultSharedPreferences(app); // } // // @Provides // @Singleton // ThreadConfiguration provideThreadConfiguration() { // return new ThreadConfiguration(Schedulers.io(), AndroidSchedulers.mainThread()); // } // // @Provides // @Singleton // ApplicationPreferences provideApplicationPreferences(SharedPreferences sharedPreferences) { // return new ApplicationPreferences(sharedPreferences); // } // }
import android.annotation.SuppressLint; import android.app.Application; import android.content.Context; import android.os.StrictMode; import android.util.Log; import com.squareup.leakcanary.LeakCanary; import com.starter.data.di.DataModule; import com.starter.di.AppComponent; import com.starter.di.AppModule; import com.starter.di.DaggerAppComponent; import timber.log.Timber;
package com.starter; public class StarterApplication extends Application { @SuppressLint("StaticFieldLeak") private static Context context;
// Path: app/src/main/java/com/starter/data/di/DataModule.java // @Module // public class DataModule { // private static final int HTTP_DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB // private static final String HTTP_CACHE_DIR = "cache_http"; // private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm"; // // private final String apiBaseUrl; // // public DataModule(final String apiBaseUrl) { // this.apiBaseUrl = apiBaseUrl; // } // // @Provides // @Singleton // public Gson provideGson() { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.setDateFormat(DATE_FORMAT); // // return gsonBuilder.create(); // } // // @Provides // @Singleton // public OkHttpClient provideOkHttpClient(Application application) { // final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); // // // Install an HTTP cache in the application cache directory. // File cacheDir = new File(application.getCacheDir(), HTTP_CACHE_DIR); // Cache cache = new Cache(cacheDir, HTTP_DISK_CACHE_SIZE); // // final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS); // // httpBuilder.addInterceptor(interceptor); // httpBuilder.cache(cache); // // if (BuildConfig.DEBUG) { // httpBuilder.addNetworkInterceptor(new StethoInterceptor()); // } // // return httpBuilder.build(); // } // // @Provides // @Singleton // public Retrofit provideRetrofit(OkHttpClient client, Gson gson) { // return new Retrofit.Builder().baseUrl(apiBaseUrl) // .client(client) // .addConverterFactory(new ToStringConverterFactory()) // .addConverterFactory(GsonConverterFactory.create(gson)) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // } // // @Provides // @Singleton // public BoxStore providesObjectBox(Application application) { // return MyObjectBox.builder().androidContext(application).build(); // } // // @Provides // @Singleton // public Box<ContributorEntity> providesContributorsObjectBox(BoxStore boxStore) { // return boxStore.boxFor(ContributorEntity.class); // } // // @Provides // @Singleton // public GithubApi providesGithubApi(Retrofit retrofit) { // return retrofit.create(GithubApi.class); // } // // @Provides // @NonNull // @Singleton // public LocalRepository providesLocalRepository(Box<ContributorEntity> localContributorBox, // ThreadConfiguration threadConfiguration) { // return new LocalRepository(localContributorBox, threadConfiguration); // } // // @Provides // @Singleton // public RemoteRepository providesRemoteRepository(LocalRepository localRepository, // GithubApi githubApi, ThreadConfiguration threadConfiguration) { // return new RemoteRepository(localRepository, githubApi, threadConfiguration); // } // // @Provides // @Singleton // public AppRepository provideAppRepository(RemoteRepository remoteRepository, // LocalRepository localRepository) { // return new AppRepository(localRepository, remoteRepository); // } // } // // Path: app/src/main/java/com/starter/di/AppComponent.java // @Singleton // @Component(modules = { AppModule.class, DataModule.class }) // public interface AppComponent { // // Application getApplication(); // // SharedPreferences getSharedPreferences(); // // void inject(Application application); // // void inject(ContributorsActivity contributorsActivity); // } // // Path: app/src/main/java/com/starter/di/AppModule.java // @Module // public class AppModule { // private static final String IMAGE_CACHE_DIR = "cache_images"; // private static final int IMAGE_DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB // private final Application application; // // public AppModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // Application provideApplication() { // return application; // } // // @Provides // @Singleton // Picasso providePicasso(final Application app) { // final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); // // File cacheDir = new File(app.getCacheDir(), IMAGE_CACHE_DIR); // httpBuilder.cache(new Cache(cacheDir, IMAGE_DISK_CACHE_SIZE)); // final OkHttp3Downloader okHttpDownloader = new OkHttp3Downloader(httpBuilder.build()); // // return new Picasso.Builder(app).downloader(okHttpDownloader).indicatorsEnabled(true).build(); // } // // @Provides // @Singleton // SharedPreferences provideSharedPreferences(Application app) { // return PreferenceManager.getDefaultSharedPreferences(app); // } // // @Provides // @Singleton // ThreadConfiguration provideThreadConfiguration() { // return new ThreadConfiguration(Schedulers.io(), AndroidSchedulers.mainThread()); // } // // @Provides // @Singleton // ApplicationPreferences provideApplicationPreferences(SharedPreferences sharedPreferences) { // return new ApplicationPreferences(sharedPreferences); // } // } // Path: app/src/main/java/com/starter/StarterApplication.java import android.annotation.SuppressLint; import android.app.Application; import android.content.Context; import android.os.StrictMode; import android.util.Log; import com.squareup.leakcanary.LeakCanary; import com.starter.data.di.DataModule; import com.starter.di.AppComponent; import com.starter.di.AppModule; import com.starter.di.DaggerAppComponent; import timber.log.Timber; package com.starter; public class StarterApplication extends Application { @SuppressLint("StaticFieldLeak") private static Context context;
protected AppComponent appComponent;
BartoszJarocki/android-starter
app/src/main/java/com/starter/StarterApplication.java
// Path: app/src/main/java/com/starter/data/di/DataModule.java // @Module // public class DataModule { // private static final int HTTP_DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB // private static final String HTTP_CACHE_DIR = "cache_http"; // private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm"; // // private final String apiBaseUrl; // // public DataModule(final String apiBaseUrl) { // this.apiBaseUrl = apiBaseUrl; // } // // @Provides // @Singleton // public Gson provideGson() { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.setDateFormat(DATE_FORMAT); // // return gsonBuilder.create(); // } // // @Provides // @Singleton // public OkHttpClient provideOkHttpClient(Application application) { // final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); // // // Install an HTTP cache in the application cache directory. // File cacheDir = new File(application.getCacheDir(), HTTP_CACHE_DIR); // Cache cache = new Cache(cacheDir, HTTP_DISK_CACHE_SIZE); // // final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS); // // httpBuilder.addInterceptor(interceptor); // httpBuilder.cache(cache); // // if (BuildConfig.DEBUG) { // httpBuilder.addNetworkInterceptor(new StethoInterceptor()); // } // // return httpBuilder.build(); // } // // @Provides // @Singleton // public Retrofit provideRetrofit(OkHttpClient client, Gson gson) { // return new Retrofit.Builder().baseUrl(apiBaseUrl) // .client(client) // .addConverterFactory(new ToStringConverterFactory()) // .addConverterFactory(GsonConverterFactory.create(gson)) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // } // // @Provides // @Singleton // public BoxStore providesObjectBox(Application application) { // return MyObjectBox.builder().androidContext(application).build(); // } // // @Provides // @Singleton // public Box<ContributorEntity> providesContributorsObjectBox(BoxStore boxStore) { // return boxStore.boxFor(ContributorEntity.class); // } // // @Provides // @Singleton // public GithubApi providesGithubApi(Retrofit retrofit) { // return retrofit.create(GithubApi.class); // } // // @Provides // @NonNull // @Singleton // public LocalRepository providesLocalRepository(Box<ContributorEntity> localContributorBox, // ThreadConfiguration threadConfiguration) { // return new LocalRepository(localContributorBox, threadConfiguration); // } // // @Provides // @Singleton // public RemoteRepository providesRemoteRepository(LocalRepository localRepository, // GithubApi githubApi, ThreadConfiguration threadConfiguration) { // return new RemoteRepository(localRepository, githubApi, threadConfiguration); // } // // @Provides // @Singleton // public AppRepository provideAppRepository(RemoteRepository remoteRepository, // LocalRepository localRepository) { // return new AppRepository(localRepository, remoteRepository); // } // } // // Path: app/src/main/java/com/starter/di/AppComponent.java // @Singleton // @Component(modules = { AppModule.class, DataModule.class }) // public interface AppComponent { // // Application getApplication(); // // SharedPreferences getSharedPreferences(); // // void inject(Application application); // // void inject(ContributorsActivity contributorsActivity); // } // // Path: app/src/main/java/com/starter/di/AppModule.java // @Module // public class AppModule { // private static final String IMAGE_CACHE_DIR = "cache_images"; // private static final int IMAGE_DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB // private final Application application; // // public AppModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // Application provideApplication() { // return application; // } // // @Provides // @Singleton // Picasso providePicasso(final Application app) { // final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); // // File cacheDir = new File(app.getCacheDir(), IMAGE_CACHE_DIR); // httpBuilder.cache(new Cache(cacheDir, IMAGE_DISK_CACHE_SIZE)); // final OkHttp3Downloader okHttpDownloader = new OkHttp3Downloader(httpBuilder.build()); // // return new Picasso.Builder(app).downloader(okHttpDownloader).indicatorsEnabled(true).build(); // } // // @Provides // @Singleton // SharedPreferences provideSharedPreferences(Application app) { // return PreferenceManager.getDefaultSharedPreferences(app); // } // // @Provides // @Singleton // ThreadConfiguration provideThreadConfiguration() { // return new ThreadConfiguration(Schedulers.io(), AndroidSchedulers.mainThread()); // } // // @Provides // @Singleton // ApplicationPreferences provideApplicationPreferences(SharedPreferences sharedPreferences) { // return new ApplicationPreferences(sharedPreferences); // } // }
import android.annotation.SuppressLint; import android.app.Application; import android.content.Context; import android.os.StrictMode; import android.util.Log; import com.squareup.leakcanary.LeakCanary; import com.starter.data.di.DataModule; import com.starter.di.AppComponent; import com.starter.di.AppModule; import com.starter.di.DaggerAppComponent; import timber.log.Timber;
package com.starter; public class StarterApplication extends Application { @SuppressLint("StaticFieldLeak") private static Context context; protected AppComponent appComponent;
// Path: app/src/main/java/com/starter/data/di/DataModule.java // @Module // public class DataModule { // private static final int HTTP_DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB // private static final String HTTP_CACHE_DIR = "cache_http"; // private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm"; // // private final String apiBaseUrl; // // public DataModule(final String apiBaseUrl) { // this.apiBaseUrl = apiBaseUrl; // } // // @Provides // @Singleton // public Gson provideGson() { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.setDateFormat(DATE_FORMAT); // // return gsonBuilder.create(); // } // // @Provides // @Singleton // public OkHttpClient provideOkHttpClient(Application application) { // final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); // // // Install an HTTP cache in the application cache directory. // File cacheDir = new File(application.getCacheDir(), HTTP_CACHE_DIR); // Cache cache = new Cache(cacheDir, HTTP_DISK_CACHE_SIZE); // // final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS); // // httpBuilder.addInterceptor(interceptor); // httpBuilder.cache(cache); // // if (BuildConfig.DEBUG) { // httpBuilder.addNetworkInterceptor(new StethoInterceptor()); // } // // return httpBuilder.build(); // } // // @Provides // @Singleton // public Retrofit provideRetrofit(OkHttpClient client, Gson gson) { // return new Retrofit.Builder().baseUrl(apiBaseUrl) // .client(client) // .addConverterFactory(new ToStringConverterFactory()) // .addConverterFactory(GsonConverterFactory.create(gson)) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // } // // @Provides // @Singleton // public BoxStore providesObjectBox(Application application) { // return MyObjectBox.builder().androidContext(application).build(); // } // // @Provides // @Singleton // public Box<ContributorEntity> providesContributorsObjectBox(BoxStore boxStore) { // return boxStore.boxFor(ContributorEntity.class); // } // // @Provides // @Singleton // public GithubApi providesGithubApi(Retrofit retrofit) { // return retrofit.create(GithubApi.class); // } // // @Provides // @NonNull // @Singleton // public LocalRepository providesLocalRepository(Box<ContributorEntity> localContributorBox, // ThreadConfiguration threadConfiguration) { // return new LocalRepository(localContributorBox, threadConfiguration); // } // // @Provides // @Singleton // public RemoteRepository providesRemoteRepository(LocalRepository localRepository, // GithubApi githubApi, ThreadConfiguration threadConfiguration) { // return new RemoteRepository(localRepository, githubApi, threadConfiguration); // } // // @Provides // @Singleton // public AppRepository provideAppRepository(RemoteRepository remoteRepository, // LocalRepository localRepository) { // return new AppRepository(localRepository, remoteRepository); // } // } // // Path: app/src/main/java/com/starter/di/AppComponent.java // @Singleton // @Component(modules = { AppModule.class, DataModule.class }) // public interface AppComponent { // // Application getApplication(); // // SharedPreferences getSharedPreferences(); // // void inject(Application application); // // void inject(ContributorsActivity contributorsActivity); // } // // Path: app/src/main/java/com/starter/di/AppModule.java // @Module // public class AppModule { // private static final String IMAGE_CACHE_DIR = "cache_images"; // private static final int IMAGE_DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB // private final Application application; // // public AppModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // Application provideApplication() { // return application; // } // // @Provides // @Singleton // Picasso providePicasso(final Application app) { // final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); // // File cacheDir = new File(app.getCacheDir(), IMAGE_CACHE_DIR); // httpBuilder.cache(new Cache(cacheDir, IMAGE_DISK_CACHE_SIZE)); // final OkHttp3Downloader okHttpDownloader = new OkHttp3Downloader(httpBuilder.build()); // // return new Picasso.Builder(app).downloader(okHttpDownloader).indicatorsEnabled(true).build(); // } // // @Provides // @Singleton // SharedPreferences provideSharedPreferences(Application app) { // return PreferenceManager.getDefaultSharedPreferences(app); // } // // @Provides // @Singleton // ThreadConfiguration provideThreadConfiguration() { // return new ThreadConfiguration(Schedulers.io(), AndroidSchedulers.mainThread()); // } // // @Provides // @Singleton // ApplicationPreferences provideApplicationPreferences(SharedPreferences sharedPreferences) { // return new ApplicationPreferences(sharedPreferences); // } // } // Path: app/src/main/java/com/starter/StarterApplication.java import android.annotation.SuppressLint; import android.app.Application; import android.content.Context; import android.os.StrictMode; import android.util.Log; import com.squareup.leakcanary.LeakCanary; import com.starter.data.di.DataModule; import com.starter.di.AppComponent; import com.starter.di.AppModule; import com.starter.di.DaggerAppComponent; import timber.log.Timber; package com.starter; public class StarterApplication extends Application { @SuppressLint("StaticFieldLeak") private static Context context; protected AppComponent appComponent;
protected AppModule appModule;
BartoszJarocki/android-starter
app/src/androidTest/java/com/starter/ui/contributors/ContributorsActivityTest.java
// Path: app/src/androidTest/java/com/starter/util/DeviceAnimationTestRule.java // public final class DeviceAnimationTestRule implements TestRule { // private static final String ANIMATION_PERMISSION = "android.permission.SET_ANIMATION_SCALE"; // private static final float DISABLED = 0.0f; // private static final float DEFAULT = 1.0f; // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // disableAnimations(); // try { // base.evaluate(); // } finally { // enableAnimations(); // } // } // }; // } // // private void disableAnimations() throws Exception { // Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); // // UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) // .executeShellCommand("pm grant " + InstrumentationRegistry.getInstrumentation() // .getTargetContext() // .getPackageName() + " android.permission.SET_ANIMATION_SCALE"); // // Context context = instrumentation.getContext(); // // int permStatus = context.checkCallingOrSelfPermission(ANIMATION_PERMISSION); // if (permStatus == PackageManager.PERMISSION_GRANTED) { // setSystemAnimationsScale(DISABLED); // } // } // // private void enableAnimations() throws Exception { // Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); // Context context = instrumentation.getContext(); // // int permStatus = context.checkCallingOrSelfPermission(ANIMATION_PERMISSION); // if (permStatus == PackageManager.PERMISSION_GRANTED) { // setSystemAnimationsScale(DEFAULT); // } // } // // private void setSystemAnimationsScale(float animationScale) throws Exception { // Class<?> windowManagerStubClazz = Class.forName("android.view.IWindowManager$Stub"); // Method asInterface = windowManagerStubClazz.getDeclaredMethod("asInterface", IBinder.class); // Class<?> serviceManagerClazz = Class.forName("android.os.ServiceManager"); // Method getService = serviceManagerClazz.getDeclaredMethod("getService", String.class); // Class<?> windowManagerClazz = Class.forName("android.view.IWindowManager"); // Method setAnimationScales = // windowManagerClazz.getDeclaredMethod("setAnimationScales", float[].class); // Method getAnimationScales = windowManagerClazz.getDeclaredMethod("getAnimationScales"); // // IBinder windowManagerBinder = (IBinder) getService.invoke(null, "window"); // Object windowManagerObj = asInterface.invoke(null, windowManagerBinder); // float[] currentScales = (float[]) getAnimationScales.invoke(windowManagerObj); // for (int i = 0; i < currentScales.length; i++) { // currentScales[i] = animationScale; // } // setAnimationScales.invoke(windowManagerObj, new Object[] { currentScales }); // } // }
import android.support.test.rule.ActivityTestRule; import com.starter.R; import com.starter.util.DeviceAnimationTestRule; import io.appflate.restmock.RESTMockServer; import io.appflate.restmock.RequestsVerifier; import okhttp3.mockwebserver.MockResponse; import org.junit.Before; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static io.appflate.restmock.utils.RequestMatchers.pathContains; import static org.hamcrest.CoreMatchers.not;
package com.starter.ui.contributors; public class ContributorsActivityTest { private static final String CONTRIBUTORS_JSON = "contributors.json"; private static final String EMPTY_JSON = "empty_array.json"; private static final String CONTRIBUTORS_ENDPOINT = "contributors";
// Path: app/src/androidTest/java/com/starter/util/DeviceAnimationTestRule.java // public final class DeviceAnimationTestRule implements TestRule { // private static final String ANIMATION_PERMISSION = "android.permission.SET_ANIMATION_SCALE"; // private static final float DISABLED = 0.0f; // private static final float DEFAULT = 1.0f; // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // disableAnimations(); // try { // base.evaluate(); // } finally { // enableAnimations(); // } // } // }; // } // // private void disableAnimations() throws Exception { // Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); // // UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) // .executeShellCommand("pm grant " + InstrumentationRegistry.getInstrumentation() // .getTargetContext() // .getPackageName() + " android.permission.SET_ANIMATION_SCALE"); // // Context context = instrumentation.getContext(); // // int permStatus = context.checkCallingOrSelfPermission(ANIMATION_PERMISSION); // if (permStatus == PackageManager.PERMISSION_GRANTED) { // setSystemAnimationsScale(DISABLED); // } // } // // private void enableAnimations() throws Exception { // Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); // Context context = instrumentation.getContext(); // // int permStatus = context.checkCallingOrSelfPermission(ANIMATION_PERMISSION); // if (permStatus == PackageManager.PERMISSION_GRANTED) { // setSystemAnimationsScale(DEFAULT); // } // } // // private void setSystemAnimationsScale(float animationScale) throws Exception { // Class<?> windowManagerStubClazz = Class.forName("android.view.IWindowManager$Stub"); // Method asInterface = windowManagerStubClazz.getDeclaredMethod("asInterface", IBinder.class); // Class<?> serviceManagerClazz = Class.forName("android.os.ServiceManager"); // Method getService = serviceManagerClazz.getDeclaredMethod("getService", String.class); // Class<?> windowManagerClazz = Class.forName("android.view.IWindowManager"); // Method setAnimationScales = // windowManagerClazz.getDeclaredMethod("setAnimationScales", float[].class); // Method getAnimationScales = windowManagerClazz.getDeclaredMethod("getAnimationScales"); // // IBinder windowManagerBinder = (IBinder) getService.invoke(null, "window"); // Object windowManagerObj = asInterface.invoke(null, windowManagerBinder); // float[] currentScales = (float[]) getAnimationScales.invoke(windowManagerObj); // for (int i = 0; i < currentScales.length; i++) { // currentScales[i] = animationScale; // } // setAnimationScales.invoke(windowManagerObj, new Object[] { currentScales }); // } // } // Path: app/src/androidTest/java/com/starter/ui/contributors/ContributorsActivityTest.java import android.support.test.rule.ActivityTestRule; import com.starter.R; import com.starter.util.DeviceAnimationTestRule; import io.appflate.restmock.RESTMockServer; import io.appflate.restmock.RequestsVerifier; import okhttp3.mockwebserver.MockResponse; import org.junit.Before; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static io.appflate.restmock.utils.RequestMatchers.pathContains; import static org.hamcrest.CoreMatchers.not; package com.starter.ui.contributors; public class ContributorsActivityTest { private static final String CONTRIBUTORS_JSON = "contributors.json"; private static final String EMPTY_JSON = "empty_array.json"; private static final String CONTRIBUTORS_ENDPOINT = "contributors";
@ClassRule static public DeviceAnimationTestRule deviceAnimationTestRule =
BartoszJarocki/android-starter
app/src/main/java/com/starter/ui/contributors/ContributorsView.java
// Path: app/src/main/java/com/starter/data/model/Contributor.java // public final class Contributor { // private final String login; // private final int contributions; // private final String avatarUrl; // // public Contributor(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // public Contributor(final ContributorJson contributorJson) { // this.login = contributorJson.getLogin(); // this.contributions = contributorJson.getContributions(); // this.avatarUrl = contributorJson.getAvatarUrl(); // } // // public Contributor(final ContributorEntity contributorEntity) { // this.login = contributorEntity.getLogin(); // this.contributions = contributorEntity.getContributions(); // this.avatarUrl = contributorEntity.getAvatarUrl(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final Contributor that = (Contributor) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // } // // Path: app/src/main/java/com/starter/ui/base/mvp/core/MvpView.java // public interface MvpView { // }
import com.starter.data.model.Contributor; import com.starter.ui.base.mvp.core.MvpView; import java.util.List;
package com.starter.ui.contributors; public interface ContributorsView extends MvpView { void showProgress(boolean pullToRefresh);
// Path: app/src/main/java/com/starter/data/model/Contributor.java // public final class Contributor { // private final String login; // private final int contributions; // private final String avatarUrl; // // public Contributor(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // public Contributor(final ContributorJson contributorJson) { // this.login = contributorJson.getLogin(); // this.contributions = contributorJson.getContributions(); // this.avatarUrl = contributorJson.getAvatarUrl(); // } // // public Contributor(final ContributorEntity contributorEntity) { // this.login = contributorEntity.getLogin(); // this.contributions = contributorEntity.getContributions(); // this.avatarUrl = contributorEntity.getAvatarUrl(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final Contributor that = (Contributor) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // } // // Path: app/src/main/java/com/starter/ui/base/mvp/core/MvpView.java // public interface MvpView { // } // Path: app/src/main/java/com/starter/ui/contributors/ContributorsView.java import com.starter.data.model.Contributor; import com.starter.ui.base.mvp.core.MvpView; import java.util.List; package com.starter.ui.contributors; public interface ContributorsView extends MvpView { void showProgress(boolean pullToRefresh);
void showContributors(List<Contributor> contributors);
BartoszJarocki/android-starter
app/src/main/java/com/starter/data/AppRepository.java
// Path: app/src/main/java/com/starter/data/local/LocalRepository.java // public class LocalRepository implements Repository { // private final Box<ContributorEntity> localContributorBox; // private final ThreadConfiguration threadConfiguration; // private final ContributorsJsonsToContributorEntitiesMapper // contributorsJsonsToContributorEntitiesMapper = // new ContributorsJsonsToContributorEntitiesMapper(); // private final ContributorsEntitiesToContributorsMapper entitiesToContributorsMapper = // new ContributorsEntitiesToContributorsMapper(); // // public LocalRepository(final Box<ContributorEntity> localContributorBox, // final ThreadConfiguration threadConfiguration) { // this.localContributorBox = localContributorBox; // this.threadConfiguration = threadConfiguration; // } // // @Override // public Observable<List<Contributor>> contributors(final String owner, final String repo) { // return Observable.defer(() -> Observable.just(localContributorBox.getAll())) // .flatMap(contributorEntities -> Observable.just( // entitiesToContributorsMapper.map(contributorEntities))) // .compose(threadConfiguration.applySchedulers()); // } // // public void put(final List<ContributorJson> contributorJsons) { // localContributorBox.put(contributorsJsonsToContributorEntitiesMapper.map(contributorJsons)); // } // } // // Path: app/src/main/java/com/starter/data/model/Contributor.java // public final class Contributor { // private final String login; // private final int contributions; // private final String avatarUrl; // // public Contributor(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // public Contributor(final ContributorJson contributorJson) { // this.login = contributorJson.getLogin(); // this.contributions = contributorJson.getContributions(); // this.avatarUrl = contributorJson.getAvatarUrl(); // } // // public Contributor(final ContributorEntity contributorEntity) { // this.login = contributorEntity.getLogin(); // this.contributions = contributorEntity.getContributions(); // this.avatarUrl = contributorEntity.getAvatarUrl(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final Contributor that = (Contributor) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // } // // Path: app/src/main/java/com/starter/data/remote/RemoteRepository.java // public class RemoteRepository implements Repository { // // private final LocalRepository localRepository; // private final ThreadConfiguration threadConfiguration; // private final GithubApi githubApi; // private final ContributorsJsonsToContributorListMapper // contributorsJsonsToContributorListMapper = new ContributorsJsonsToContributorListMapper(); // // @Inject // public RemoteRepository(final LocalRepository localRepository, @NonNull GithubApi githubApi, // @NonNull ThreadConfiguration threadConfiguration) { // this.localRepository = localRepository; // this.githubApi = githubApi; // this.threadConfiguration = threadConfiguration; // } // // public Observable<List<Contributor>> contributors(String owner, String repo) { // return githubApi.contributors(owner, repo) // .flatMap(response -> { // if (response.isSuccessful()) { // return Observable.just(response.body()); // } else { // return Observable.error(new RuntimeException()); // } // }) // .doOnNext(localRepository::put) // .flatMap(contributors -> Observable.just( // contributorsJsonsToContributorListMapper.map(contributors))) // .onErrorResumeNext(throwable -> { // if (throwable instanceof IOException) { // network errors // return Observable.empty(); // show local data! // } // // return Observable.error(throwable); // }) // .compose(threadConfiguration.applySchedulers()); // } // }
import com.starter.data.local.LocalRepository; import com.starter.data.model.Contributor; import com.starter.data.remote.RemoteRepository; import java.util.List; import javax.inject.Inject; import rx.Observable;
package com.starter.data; public class AppRepository implements Repository { private final LocalRepository localRepository;
// Path: app/src/main/java/com/starter/data/local/LocalRepository.java // public class LocalRepository implements Repository { // private final Box<ContributorEntity> localContributorBox; // private final ThreadConfiguration threadConfiguration; // private final ContributorsJsonsToContributorEntitiesMapper // contributorsJsonsToContributorEntitiesMapper = // new ContributorsJsonsToContributorEntitiesMapper(); // private final ContributorsEntitiesToContributorsMapper entitiesToContributorsMapper = // new ContributorsEntitiesToContributorsMapper(); // // public LocalRepository(final Box<ContributorEntity> localContributorBox, // final ThreadConfiguration threadConfiguration) { // this.localContributorBox = localContributorBox; // this.threadConfiguration = threadConfiguration; // } // // @Override // public Observable<List<Contributor>> contributors(final String owner, final String repo) { // return Observable.defer(() -> Observable.just(localContributorBox.getAll())) // .flatMap(contributorEntities -> Observable.just( // entitiesToContributorsMapper.map(contributorEntities))) // .compose(threadConfiguration.applySchedulers()); // } // // public void put(final List<ContributorJson> contributorJsons) { // localContributorBox.put(contributorsJsonsToContributorEntitiesMapper.map(contributorJsons)); // } // } // // Path: app/src/main/java/com/starter/data/model/Contributor.java // public final class Contributor { // private final String login; // private final int contributions; // private final String avatarUrl; // // public Contributor(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // public Contributor(final ContributorJson contributorJson) { // this.login = contributorJson.getLogin(); // this.contributions = contributorJson.getContributions(); // this.avatarUrl = contributorJson.getAvatarUrl(); // } // // public Contributor(final ContributorEntity contributorEntity) { // this.login = contributorEntity.getLogin(); // this.contributions = contributorEntity.getContributions(); // this.avatarUrl = contributorEntity.getAvatarUrl(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final Contributor that = (Contributor) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // } // // Path: app/src/main/java/com/starter/data/remote/RemoteRepository.java // public class RemoteRepository implements Repository { // // private final LocalRepository localRepository; // private final ThreadConfiguration threadConfiguration; // private final GithubApi githubApi; // private final ContributorsJsonsToContributorListMapper // contributorsJsonsToContributorListMapper = new ContributorsJsonsToContributorListMapper(); // // @Inject // public RemoteRepository(final LocalRepository localRepository, @NonNull GithubApi githubApi, // @NonNull ThreadConfiguration threadConfiguration) { // this.localRepository = localRepository; // this.githubApi = githubApi; // this.threadConfiguration = threadConfiguration; // } // // public Observable<List<Contributor>> contributors(String owner, String repo) { // return githubApi.contributors(owner, repo) // .flatMap(response -> { // if (response.isSuccessful()) { // return Observable.just(response.body()); // } else { // return Observable.error(new RuntimeException()); // } // }) // .doOnNext(localRepository::put) // .flatMap(contributors -> Observable.just( // contributorsJsonsToContributorListMapper.map(contributors))) // .onErrorResumeNext(throwable -> { // if (throwable instanceof IOException) { // network errors // return Observable.empty(); // show local data! // } // // return Observable.error(throwable); // }) // .compose(threadConfiguration.applySchedulers()); // } // } // Path: app/src/main/java/com/starter/data/AppRepository.java import com.starter.data.local.LocalRepository; import com.starter.data.model.Contributor; import com.starter.data.remote.RemoteRepository; import java.util.List; import javax.inject.Inject; import rx.Observable; package com.starter.data; public class AppRepository implements Repository { private final LocalRepository localRepository;
private final RemoteRepository remoteRepository;
BartoszJarocki/android-starter
app/src/main/java/com/starter/data/AppRepository.java
// Path: app/src/main/java/com/starter/data/local/LocalRepository.java // public class LocalRepository implements Repository { // private final Box<ContributorEntity> localContributorBox; // private final ThreadConfiguration threadConfiguration; // private final ContributorsJsonsToContributorEntitiesMapper // contributorsJsonsToContributorEntitiesMapper = // new ContributorsJsonsToContributorEntitiesMapper(); // private final ContributorsEntitiesToContributorsMapper entitiesToContributorsMapper = // new ContributorsEntitiesToContributorsMapper(); // // public LocalRepository(final Box<ContributorEntity> localContributorBox, // final ThreadConfiguration threadConfiguration) { // this.localContributorBox = localContributorBox; // this.threadConfiguration = threadConfiguration; // } // // @Override // public Observable<List<Contributor>> contributors(final String owner, final String repo) { // return Observable.defer(() -> Observable.just(localContributorBox.getAll())) // .flatMap(contributorEntities -> Observable.just( // entitiesToContributorsMapper.map(contributorEntities))) // .compose(threadConfiguration.applySchedulers()); // } // // public void put(final List<ContributorJson> contributorJsons) { // localContributorBox.put(contributorsJsonsToContributorEntitiesMapper.map(contributorJsons)); // } // } // // Path: app/src/main/java/com/starter/data/model/Contributor.java // public final class Contributor { // private final String login; // private final int contributions; // private final String avatarUrl; // // public Contributor(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // public Contributor(final ContributorJson contributorJson) { // this.login = contributorJson.getLogin(); // this.contributions = contributorJson.getContributions(); // this.avatarUrl = contributorJson.getAvatarUrl(); // } // // public Contributor(final ContributorEntity contributorEntity) { // this.login = contributorEntity.getLogin(); // this.contributions = contributorEntity.getContributions(); // this.avatarUrl = contributorEntity.getAvatarUrl(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final Contributor that = (Contributor) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // } // // Path: app/src/main/java/com/starter/data/remote/RemoteRepository.java // public class RemoteRepository implements Repository { // // private final LocalRepository localRepository; // private final ThreadConfiguration threadConfiguration; // private final GithubApi githubApi; // private final ContributorsJsonsToContributorListMapper // contributorsJsonsToContributorListMapper = new ContributorsJsonsToContributorListMapper(); // // @Inject // public RemoteRepository(final LocalRepository localRepository, @NonNull GithubApi githubApi, // @NonNull ThreadConfiguration threadConfiguration) { // this.localRepository = localRepository; // this.githubApi = githubApi; // this.threadConfiguration = threadConfiguration; // } // // public Observable<List<Contributor>> contributors(String owner, String repo) { // return githubApi.contributors(owner, repo) // .flatMap(response -> { // if (response.isSuccessful()) { // return Observable.just(response.body()); // } else { // return Observable.error(new RuntimeException()); // } // }) // .doOnNext(localRepository::put) // .flatMap(contributors -> Observable.just( // contributorsJsonsToContributorListMapper.map(contributors))) // .onErrorResumeNext(throwable -> { // if (throwable instanceof IOException) { // network errors // return Observable.empty(); // show local data! // } // // return Observable.error(throwable); // }) // .compose(threadConfiguration.applySchedulers()); // } // }
import com.starter.data.local.LocalRepository; import com.starter.data.model.Contributor; import com.starter.data.remote.RemoteRepository; import java.util.List; import javax.inject.Inject; import rx.Observable;
package com.starter.data; public class AppRepository implements Repository { private final LocalRepository localRepository; private final RemoteRepository remoteRepository; @Inject public AppRepository(final LocalRepository localRepository, final RemoteRepository remoteRepository) { this.localRepository = localRepository; this.remoteRepository = remoteRepository; } @Override
// Path: app/src/main/java/com/starter/data/local/LocalRepository.java // public class LocalRepository implements Repository { // private final Box<ContributorEntity> localContributorBox; // private final ThreadConfiguration threadConfiguration; // private final ContributorsJsonsToContributorEntitiesMapper // contributorsJsonsToContributorEntitiesMapper = // new ContributorsJsonsToContributorEntitiesMapper(); // private final ContributorsEntitiesToContributorsMapper entitiesToContributorsMapper = // new ContributorsEntitiesToContributorsMapper(); // // public LocalRepository(final Box<ContributorEntity> localContributorBox, // final ThreadConfiguration threadConfiguration) { // this.localContributorBox = localContributorBox; // this.threadConfiguration = threadConfiguration; // } // // @Override // public Observable<List<Contributor>> contributors(final String owner, final String repo) { // return Observable.defer(() -> Observable.just(localContributorBox.getAll())) // .flatMap(contributorEntities -> Observable.just( // entitiesToContributorsMapper.map(contributorEntities))) // .compose(threadConfiguration.applySchedulers()); // } // // public void put(final List<ContributorJson> contributorJsons) { // localContributorBox.put(contributorsJsonsToContributorEntitiesMapper.map(contributorJsons)); // } // } // // Path: app/src/main/java/com/starter/data/model/Contributor.java // public final class Contributor { // private final String login; // private final int contributions; // private final String avatarUrl; // // public Contributor(final String login, final int contributions, final String avatarUrl) { // this.login = login; // this.contributions = contributions; // this.avatarUrl = avatarUrl; // } // // public Contributor(final ContributorJson contributorJson) { // this.login = contributorJson.getLogin(); // this.contributions = contributorJson.getContributions(); // this.avatarUrl = contributorJson.getAvatarUrl(); // } // // public Contributor(final ContributorEntity contributorEntity) { // this.login = contributorEntity.getLogin(); // this.contributions = contributorEntity.getContributions(); // this.avatarUrl = contributorEntity.getAvatarUrl(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final Contributor that = (Contributor) o; // // if (contributions != that.contributions) return false; // if (login != null ? !login.equals(that.login) : that.login != null) return false; // return avatarUrl != null ? avatarUrl.equals(that.avatarUrl) : that.avatarUrl == null; // } // // @Override // public int hashCode() { // int result = login != null ? login.hashCode() : 0; // result = 31 * result + contributions; // result = 31 * result + (avatarUrl != null ? avatarUrl.hashCode() : 0); // return result; // } // // public String getLogin() { // return login; // } // // public int getContributions() { // return contributions; // } // // public String getAvatarUrl() { // return avatarUrl; // } // } // // Path: app/src/main/java/com/starter/data/remote/RemoteRepository.java // public class RemoteRepository implements Repository { // // private final LocalRepository localRepository; // private final ThreadConfiguration threadConfiguration; // private final GithubApi githubApi; // private final ContributorsJsonsToContributorListMapper // contributorsJsonsToContributorListMapper = new ContributorsJsonsToContributorListMapper(); // // @Inject // public RemoteRepository(final LocalRepository localRepository, @NonNull GithubApi githubApi, // @NonNull ThreadConfiguration threadConfiguration) { // this.localRepository = localRepository; // this.githubApi = githubApi; // this.threadConfiguration = threadConfiguration; // } // // public Observable<List<Contributor>> contributors(String owner, String repo) { // return githubApi.contributors(owner, repo) // .flatMap(response -> { // if (response.isSuccessful()) { // return Observable.just(response.body()); // } else { // return Observable.error(new RuntimeException()); // } // }) // .doOnNext(localRepository::put) // .flatMap(contributors -> Observable.just( // contributorsJsonsToContributorListMapper.map(contributors))) // .onErrorResumeNext(throwable -> { // if (throwable instanceof IOException) { // network errors // return Observable.empty(); // show local data! // } // // return Observable.error(throwable); // }) // .compose(threadConfiguration.applySchedulers()); // } // } // Path: app/src/main/java/com/starter/data/AppRepository.java import com.starter.data.local.LocalRepository; import com.starter.data.model.Contributor; import com.starter.data.remote.RemoteRepository; import java.util.List; import javax.inject.Inject; import rx.Observable; package com.starter.data; public class AppRepository implements Repository { private final LocalRepository localRepository; private final RemoteRepository remoteRepository; @Inject public AppRepository(final LocalRepository localRepository, final RemoteRepository remoteRepository) { this.localRepository = localRepository; this.remoteRepository = remoteRepository; } @Override
public Observable<List<Contributor>> contributors(final String owner, final String repo) {
BartoszJarocki/android-starter
app/src/androidTest/java/com/starter/TestApplication.java
// Path: app/src/main/java/com/starter/data/di/DataModule.java // @Module // public class DataModule { // private static final int HTTP_DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB // private static final String HTTP_CACHE_DIR = "cache_http"; // private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm"; // // private final String apiBaseUrl; // // public DataModule(final String apiBaseUrl) { // this.apiBaseUrl = apiBaseUrl; // } // // @Provides // @Singleton // public Gson provideGson() { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.setDateFormat(DATE_FORMAT); // // return gsonBuilder.create(); // } // // @Provides // @Singleton // public OkHttpClient provideOkHttpClient(Application application) { // final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); // // // Install an HTTP cache in the application cache directory. // File cacheDir = new File(application.getCacheDir(), HTTP_CACHE_DIR); // Cache cache = new Cache(cacheDir, HTTP_DISK_CACHE_SIZE); // // final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS); // // httpBuilder.addInterceptor(interceptor); // httpBuilder.cache(cache); // // if (BuildConfig.DEBUG) { // httpBuilder.addNetworkInterceptor(new StethoInterceptor()); // } // // return httpBuilder.build(); // } // // @Provides // @Singleton // public Retrofit provideRetrofit(OkHttpClient client, Gson gson) { // return new Retrofit.Builder().baseUrl(apiBaseUrl) // .client(client) // .addConverterFactory(new ToStringConverterFactory()) // .addConverterFactory(GsonConverterFactory.create(gson)) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // } // // @Provides // @Singleton // public BoxStore providesObjectBox(Application application) { // return MyObjectBox.builder().androidContext(application).build(); // } // // @Provides // @Singleton // public Box<ContributorEntity> providesContributorsObjectBox(BoxStore boxStore) { // return boxStore.boxFor(ContributorEntity.class); // } // // @Provides // @Singleton // public GithubApi providesGithubApi(Retrofit retrofit) { // return retrofit.create(GithubApi.class); // } // // @Provides // @NonNull // @Singleton // public LocalRepository providesLocalRepository(Box<ContributorEntity> localContributorBox, // ThreadConfiguration threadConfiguration) { // return new LocalRepository(localContributorBox, threadConfiguration); // } // // @Provides // @Singleton // public RemoteRepository providesRemoteRepository(LocalRepository localRepository, // GithubApi githubApi, ThreadConfiguration threadConfiguration) { // return new RemoteRepository(localRepository, githubApi, threadConfiguration); // } // // @Provides // @Singleton // public AppRepository provideAppRepository(RemoteRepository remoteRepository, // LocalRepository localRepository) { // return new AppRepository(localRepository, remoteRepository); // } // } // // Path: app/src/main/java/com/starter/di/AppModule.java // @Module // public class AppModule { // private static final String IMAGE_CACHE_DIR = "cache_images"; // private static final int IMAGE_DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB // private final Application application; // // public AppModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // Application provideApplication() { // return application; // } // // @Provides // @Singleton // Picasso providePicasso(final Application app) { // final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); // // File cacheDir = new File(app.getCacheDir(), IMAGE_CACHE_DIR); // httpBuilder.cache(new Cache(cacheDir, IMAGE_DISK_CACHE_SIZE)); // final OkHttp3Downloader okHttpDownloader = new OkHttp3Downloader(httpBuilder.build()); // // return new Picasso.Builder(app).downloader(okHttpDownloader).indicatorsEnabled(true).build(); // } // // @Provides // @Singleton // SharedPreferences provideSharedPreferences(Application app) { // return PreferenceManager.getDefaultSharedPreferences(app); // } // // @Provides // @Singleton // ThreadConfiguration provideThreadConfiguration() { // return new ThreadConfiguration(Schedulers.io(), AndroidSchedulers.mainThread()); // } // // @Provides // @Singleton // ApplicationPreferences provideApplicationPreferences(SharedPreferences sharedPreferences) { // return new ApplicationPreferences(sharedPreferences); // } // }
import com.starter.data.di.DataModule; import com.starter.di.AppModule; import com.starter.di.DaggerAppComponent; import io.appflate.restmock.RESTMockServer;
package com.starter; public class TestApplication extends StarterApplication { /** * Replaces API url with local mock server url. */ @Override public void initGraph() {
// Path: app/src/main/java/com/starter/data/di/DataModule.java // @Module // public class DataModule { // private static final int HTTP_DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB // private static final String HTTP_CACHE_DIR = "cache_http"; // private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm"; // // private final String apiBaseUrl; // // public DataModule(final String apiBaseUrl) { // this.apiBaseUrl = apiBaseUrl; // } // // @Provides // @Singleton // public Gson provideGson() { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.setDateFormat(DATE_FORMAT); // // return gsonBuilder.create(); // } // // @Provides // @Singleton // public OkHttpClient provideOkHttpClient(Application application) { // final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); // // // Install an HTTP cache in the application cache directory. // File cacheDir = new File(application.getCacheDir(), HTTP_CACHE_DIR); // Cache cache = new Cache(cacheDir, HTTP_DISK_CACHE_SIZE); // // final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS); // // httpBuilder.addInterceptor(interceptor); // httpBuilder.cache(cache); // // if (BuildConfig.DEBUG) { // httpBuilder.addNetworkInterceptor(new StethoInterceptor()); // } // // return httpBuilder.build(); // } // // @Provides // @Singleton // public Retrofit provideRetrofit(OkHttpClient client, Gson gson) { // return new Retrofit.Builder().baseUrl(apiBaseUrl) // .client(client) // .addConverterFactory(new ToStringConverterFactory()) // .addConverterFactory(GsonConverterFactory.create(gson)) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // } // // @Provides // @Singleton // public BoxStore providesObjectBox(Application application) { // return MyObjectBox.builder().androidContext(application).build(); // } // // @Provides // @Singleton // public Box<ContributorEntity> providesContributorsObjectBox(BoxStore boxStore) { // return boxStore.boxFor(ContributorEntity.class); // } // // @Provides // @Singleton // public GithubApi providesGithubApi(Retrofit retrofit) { // return retrofit.create(GithubApi.class); // } // // @Provides // @NonNull // @Singleton // public LocalRepository providesLocalRepository(Box<ContributorEntity> localContributorBox, // ThreadConfiguration threadConfiguration) { // return new LocalRepository(localContributorBox, threadConfiguration); // } // // @Provides // @Singleton // public RemoteRepository providesRemoteRepository(LocalRepository localRepository, // GithubApi githubApi, ThreadConfiguration threadConfiguration) { // return new RemoteRepository(localRepository, githubApi, threadConfiguration); // } // // @Provides // @Singleton // public AppRepository provideAppRepository(RemoteRepository remoteRepository, // LocalRepository localRepository) { // return new AppRepository(localRepository, remoteRepository); // } // } // // Path: app/src/main/java/com/starter/di/AppModule.java // @Module // public class AppModule { // private static final String IMAGE_CACHE_DIR = "cache_images"; // private static final int IMAGE_DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB // private final Application application; // // public AppModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // Application provideApplication() { // return application; // } // // @Provides // @Singleton // Picasso providePicasso(final Application app) { // final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); // // File cacheDir = new File(app.getCacheDir(), IMAGE_CACHE_DIR); // httpBuilder.cache(new Cache(cacheDir, IMAGE_DISK_CACHE_SIZE)); // final OkHttp3Downloader okHttpDownloader = new OkHttp3Downloader(httpBuilder.build()); // // return new Picasso.Builder(app).downloader(okHttpDownloader).indicatorsEnabled(true).build(); // } // // @Provides // @Singleton // SharedPreferences provideSharedPreferences(Application app) { // return PreferenceManager.getDefaultSharedPreferences(app); // } // // @Provides // @Singleton // ThreadConfiguration provideThreadConfiguration() { // return new ThreadConfiguration(Schedulers.io(), AndroidSchedulers.mainThread()); // } // // @Provides // @Singleton // ApplicationPreferences provideApplicationPreferences(SharedPreferences sharedPreferences) { // return new ApplicationPreferences(sharedPreferences); // } // } // Path: app/src/androidTest/java/com/starter/TestApplication.java import com.starter.data.di.DataModule; import com.starter.di.AppModule; import com.starter.di.DaggerAppComponent; import io.appflate.restmock.RESTMockServer; package com.starter; public class TestApplication extends StarterApplication { /** * Replaces API url with local mock server url. */ @Override public void initGraph() {
appModule = new AppModule(this);
BartoszJarocki/android-starter
app/src/androidTest/java/com/starter/TestApplication.java
// Path: app/src/main/java/com/starter/data/di/DataModule.java // @Module // public class DataModule { // private static final int HTTP_DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB // private static final String HTTP_CACHE_DIR = "cache_http"; // private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm"; // // private final String apiBaseUrl; // // public DataModule(final String apiBaseUrl) { // this.apiBaseUrl = apiBaseUrl; // } // // @Provides // @Singleton // public Gson provideGson() { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.setDateFormat(DATE_FORMAT); // // return gsonBuilder.create(); // } // // @Provides // @Singleton // public OkHttpClient provideOkHttpClient(Application application) { // final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); // // // Install an HTTP cache in the application cache directory. // File cacheDir = new File(application.getCacheDir(), HTTP_CACHE_DIR); // Cache cache = new Cache(cacheDir, HTTP_DISK_CACHE_SIZE); // // final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS); // // httpBuilder.addInterceptor(interceptor); // httpBuilder.cache(cache); // // if (BuildConfig.DEBUG) { // httpBuilder.addNetworkInterceptor(new StethoInterceptor()); // } // // return httpBuilder.build(); // } // // @Provides // @Singleton // public Retrofit provideRetrofit(OkHttpClient client, Gson gson) { // return new Retrofit.Builder().baseUrl(apiBaseUrl) // .client(client) // .addConverterFactory(new ToStringConverterFactory()) // .addConverterFactory(GsonConverterFactory.create(gson)) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // } // // @Provides // @Singleton // public BoxStore providesObjectBox(Application application) { // return MyObjectBox.builder().androidContext(application).build(); // } // // @Provides // @Singleton // public Box<ContributorEntity> providesContributorsObjectBox(BoxStore boxStore) { // return boxStore.boxFor(ContributorEntity.class); // } // // @Provides // @Singleton // public GithubApi providesGithubApi(Retrofit retrofit) { // return retrofit.create(GithubApi.class); // } // // @Provides // @NonNull // @Singleton // public LocalRepository providesLocalRepository(Box<ContributorEntity> localContributorBox, // ThreadConfiguration threadConfiguration) { // return new LocalRepository(localContributorBox, threadConfiguration); // } // // @Provides // @Singleton // public RemoteRepository providesRemoteRepository(LocalRepository localRepository, // GithubApi githubApi, ThreadConfiguration threadConfiguration) { // return new RemoteRepository(localRepository, githubApi, threadConfiguration); // } // // @Provides // @Singleton // public AppRepository provideAppRepository(RemoteRepository remoteRepository, // LocalRepository localRepository) { // return new AppRepository(localRepository, remoteRepository); // } // } // // Path: app/src/main/java/com/starter/di/AppModule.java // @Module // public class AppModule { // private static final String IMAGE_CACHE_DIR = "cache_images"; // private static final int IMAGE_DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB // private final Application application; // // public AppModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // Application provideApplication() { // return application; // } // // @Provides // @Singleton // Picasso providePicasso(final Application app) { // final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); // // File cacheDir = new File(app.getCacheDir(), IMAGE_CACHE_DIR); // httpBuilder.cache(new Cache(cacheDir, IMAGE_DISK_CACHE_SIZE)); // final OkHttp3Downloader okHttpDownloader = new OkHttp3Downloader(httpBuilder.build()); // // return new Picasso.Builder(app).downloader(okHttpDownloader).indicatorsEnabled(true).build(); // } // // @Provides // @Singleton // SharedPreferences provideSharedPreferences(Application app) { // return PreferenceManager.getDefaultSharedPreferences(app); // } // // @Provides // @Singleton // ThreadConfiguration provideThreadConfiguration() { // return new ThreadConfiguration(Schedulers.io(), AndroidSchedulers.mainThread()); // } // // @Provides // @Singleton // ApplicationPreferences provideApplicationPreferences(SharedPreferences sharedPreferences) { // return new ApplicationPreferences(sharedPreferences); // } // }
import com.starter.data.di.DataModule; import com.starter.di.AppModule; import com.starter.di.DaggerAppComponent; import io.appflate.restmock.RESTMockServer;
package com.starter; public class TestApplication extends StarterApplication { /** * Replaces API url with local mock server url. */ @Override public void initGraph() { appModule = new AppModule(this); appComponent = DaggerAppComponent.builder() .appModule(appModule)
// Path: app/src/main/java/com/starter/data/di/DataModule.java // @Module // public class DataModule { // private static final int HTTP_DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB // private static final String HTTP_CACHE_DIR = "cache_http"; // private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm"; // // private final String apiBaseUrl; // // public DataModule(final String apiBaseUrl) { // this.apiBaseUrl = apiBaseUrl; // } // // @Provides // @Singleton // public Gson provideGson() { // GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.setDateFormat(DATE_FORMAT); // // return gsonBuilder.create(); // } // // @Provides // @Singleton // public OkHttpClient provideOkHttpClient(Application application) { // final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); // // // Install an HTTP cache in the application cache directory. // File cacheDir = new File(application.getCacheDir(), HTTP_CACHE_DIR); // Cache cache = new Cache(cacheDir, HTTP_DISK_CACHE_SIZE); // // final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS); // // httpBuilder.addInterceptor(interceptor); // httpBuilder.cache(cache); // // if (BuildConfig.DEBUG) { // httpBuilder.addNetworkInterceptor(new StethoInterceptor()); // } // // return httpBuilder.build(); // } // // @Provides // @Singleton // public Retrofit provideRetrofit(OkHttpClient client, Gson gson) { // return new Retrofit.Builder().baseUrl(apiBaseUrl) // .client(client) // .addConverterFactory(new ToStringConverterFactory()) // .addConverterFactory(GsonConverterFactory.create(gson)) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // } // // @Provides // @Singleton // public BoxStore providesObjectBox(Application application) { // return MyObjectBox.builder().androidContext(application).build(); // } // // @Provides // @Singleton // public Box<ContributorEntity> providesContributorsObjectBox(BoxStore boxStore) { // return boxStore.boxFor(ContributorEntity.class); // } // // @Provides // @Singleton // public GithubApi providesGithubApi(Retrofit retrofit) { // return retrofit.create(GithubApi.class); // } // // @Provides // @NonNull // @Singleton // public LocalRepository providesLocalRepository(Box<ContributorEntity> localContributorBox, // ThreadConfiguration threadConfiguration) { // return new LocalRepository(localContributorBox, threadConfiguration); // } // // @Provides // @Singleton // public RemoteRepository providesRemoteRepository(LocalRepository localRepository, // GithubApi githubApi, ThreadConfiguration threadConfiguration) { // return new RemoteRepository(localRepository, githubApi, threadConfiguration); // } // // @Provides // @Singleton // public AppRepository provideAppRepository(RemoteRepository remoteRepository, // LocalRepository localRepository) { // return new AppRepository(localRepository, remoteRepository); // } // } // // Path: app/src/main/java/com/starter/di/AppModule.java // @Module // public class AppModule { // private static final String IMAGE_CACHE_DIR = "cache_images"; // private static final int IMAGE_DISK_CACHE_SIZE = 100 * 1024 * 1024; // 100MB // private final Application application; // // public AppModule(Application application) { // this.application = application; // } // // @Provides // @Singleton // Application provideApplication() { // return application; // } // // @Provides // @Singleton // Picasso providePicasso(final Application app) { // final OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder(); // // File cacheDir = new File(app.getCacheDir(), IMAGE_CACHE_DIR); // httpBuilder.cache(new Cache(cacheDir, IMAGE_DISK_CACHE_SIZE)); // final OkHttp3Downloader okHttpDownloader = new OkHttp3Downloader(httpBuilder.build()); // // return new Picasso.Builder(app).downloader(okHttpDownloader).indicatorsEnabled(true).build(); // } // // @Provides // @Singleton // SharedPreferences provideSharedPreferences(Application app) { // return PreferenceManager.getDefaultSharedPreferences(app); // } // // @Provides // @Singleton // ThreadConfiguration provideThreadConfiguration() { // return new ThreadConfiguration(Schedulers.io(), AndroidSchedulers.mainThread()); // } // // @Provides // @Singleton // ApplicationPreferences provideApplicationPreferences(SharedPreferences sharedPreferences) { // return new ApplicationPreferences(sharedPreferences); // } // } // Path: app/src/androidTest/java/com/starter/TestApplication.java import com.starter.data.di.DataModule; import com.starter.di.AppModule; import com.starter.di.DaggerAppComponent; import io.appflate.restmock.RESTMockServer; package com.starter; public class TestApplication extends StarterApplication { /** * Replaces API url with local mock server url. */ @Override public void initGraph() { appModule = new AppModule(this); appComponent = DaggerAppComponent.builder() .appModule(appModule)
.dataModule(new DataModule(RESTMockServer.getUrl()))
dbasedow/prospecter
src/main/java/de/danielbasedow/prospecter/core/query/build/PropositionalSentenceMapper.java
// Path: src/main/java/de/danielbasedow/prospecter/core/query/Condition.java // public class Condition implements ClauseNode { // private final String fieldName; // private final Token token; // // /** // * if "not" is set the condition will result in a posting in a "NOT-index" // */ // private boolean not; // // public Condition(String fieldName, Token token) { // this.fieldName = fieldName; // this.token = token; // this.not = false; // } // // public Condition(String fieldName, Token token, boolean not) { // this.fieldName = fieldName; // this.token = token; // this.not = not; // } // // public String getFieldName() { // return fieldName; // } // // public Token getToken() { // return token; // } // // public boolean isNot() { // return not; // } // // public void setNot(boolean not) { // this.not = not; // } // // @Override // public boolean isLeaf() { // return true; // } // // /** // * AIMA symbols need a unique, java conform name // * // * @return symbol name for use in AIMA // */ // public String getSymbolName() { // return fieldName + token.getCondition().name() + token.getToken().toString(); // } // }
import aima.core.logic.propositional.parsing.ast.ComplexSentence; import aima.core.logic.propositional.parsing.ast.Connective; import aima.core.logic.propositional.parsing.ast.Sentence; import de.danielbasedow.prospecter.core.query.Condition; import java.util.ArrayList; import java.util.List;
package de.danielbasedow.prospecter.core.query.build; public class PropositionalSentenceMapper { public static Sentence map(ClauseNode clause) { if (!clause.isLeaf()) { return mapAsComplexSentence((Clause) clause); } else {
// Path: src/main/java/de/danielbasedow/prospecter/core/query/Condition.java // public class Condition implements ClauseNode { // private final String fieldName; // private final Token token; // // /** // * if "not" is set the condition will result in a posting in a "NOT-index" // */ // private boolean not; // // public Condition(String fieldName, Token token) { // this.fieldName = fieldName; // this.token = token; // this.not = false; // } // // public Condition(String fieldName, Token token, boolean not) { // this.fieldName = fieldName; // this.token = token; // this.not = not; // } // // public String getFieldName() { // return fieldName; // } // // public Token getToken() { // return token; // } // // public boolean isNot() { // return not; // } // // public void setNot(boolean not) { // this.not = not; // } // // @Override // public boolean isLeaf() { // return true; // } // // /** // * AIMA symbols need a unique, java conform name // * // * @return symbol name for use in AIMA // */ // public String getSymbolName() { // return fieldName + token.getCondition().name() + token.getToken().toString(); // } // } // Path: src/main/java/de/danielbasedow/prospecter/core/query/build/PropositionalSentenceMapper.java import aima.core.logic.propositional.parsing.ast.ComplexSentence; import aima.core.logic.propositional.parsing.ast.Connective; import aima.core.logic.propositional.parsing.ast.Sentence; import de.danielbasedow.prospecter.core.query.Condition; import java.util.ArrayList; import java.util.List; package de.danielbasedow.prospecter.core.query.build; public class PropositionalSentenceMapper { public static Sentence map(ClauseNode clause) { if (!clause.isLeaf()) { return mapAsComplexSentence((Clause) clause); } else {
return mapAsAtomicSentence((Condition) clause);
dbasedow/prospecter
src/main/java/de/danielbasedow/prospecter/core/index/FullTextIndex.java
// Path: src/main/java/de/danielbasedow/prospecter/core/Matcher.java // public class Matcher { // protected final TIntObjectHashMap<BitSet> hits = new TIntObjectHashMap<BitSet>(); // protected final TIntObjectHashMap<QueryNegativeCounter> negativeHits = new TIntObjectHashMap<QueryNegativeCounter>(); // // protected final QueryManager queryManager; // // public Matcher(QueryManager qm) { // queryManager = qm; // } // // public void addHits(TLongList postings) { // postings.forEach(new TLongProcedure() { // @Override // public boolean execute(long posting) { // addHit(posting); // return true; // } // }); // } // // public void addHit(long posting) { // int[] unpacked = QueryPosting.unpack(posting); // int queryId = unpacked[QueryPosting.QUERY_ID_INDEX]; // // if (unpacked[QueryPosting.QUERY_NOT_INDEX] == 1) { // QueryNegativeCounter counter = negativeHits.get(queryId); // if (counter == null) { // counter = new QueryNegativeCounter(); // negativeHits.put(queryId, counter); // } // counter.add(unpacked[QueryPosting.QUERY_BIT_INDEX]); // } else { // BitSet bits = hits.get(queryId); // if (bits == null) { // bits = new BitSet(); // hits.put(queryId, bits); // } // bits.set(unpacked[QueryPosting.QUERY_BIT_INDEX]); // } // } // // public int getPositiveMatchCount() { // return hits.size(); // } // // public int getNegativeMatchCount() { // return negativeHits.size(); // } // // public List<Integer> getMatchedQueries() { // final List<Integer> results = new ArrayList<Integer>(); // // hits.forEachEntry(new TIntObjectProcedure<BitSet>() { // @Override // public boolean execute(int queryId, BitSet bitSet) { // BitSet mask = queryManager.getMask(queryId); // if (mask != null) { // if (mask.equals(bitSet)) { // results.add(queryId); // } else { // QueryNegativeCounter countMask = queryManager.getQueryNegativeCounter(queryId); // if (countMask != null) { // QueryNegativeCounter actualCount = negativeHits.get(queryId); // if (actualCount == null) { // actualCount = new QueryNegativeCounter(); // } // int[] bitPositions = countMask.getBitPositionsToSet(actualCount); // if (bitPositions.length > 0) { // for (int position : bitPositions) { // bitSet.set(position, true); // } // } // if (mask.equals(bitSet)) { // results.add(queryId); // } // } // } // } // return true; // } // }); // return results; // } // } // // Path: src/main/java/de/danielbasedow/prospecter/core/Token.java // public class Token<T> { // private final T token; // private final MatchCondition condition; // // public Token(T token) { // this(token, MatchCondition.NONE); // } // // public Token(T token, MatchCondition condition) { // this.token = token; // this.condition = condition; // } // // public T getToken() { // return token; // } // // public int hashCode() { // return token.hashCode(); // } // // public boolean equals(Object compare) { // if (compare instanceof Token) { // return token.equals(((Token) compare).getToken()); // } // return false; // } // // public MatchCondition getCondition() { // return condition; // } // } // // Path: src/main/java/de/danielbasedow/prospecter/core/analysis/Analyzer.java // public interface Analyzer { // /** // * Tokenizes raw input // * // * @param input raw String that should be turned into tokens // * @return list of tokens // * @throws TokenizerException // */ // public List<Token> tokenize(String input) throws TokenizerException; // // /** // * Tokenizes raw input. It is possible to turn off generating formerly unknown tokens. This makes sense when // * tokenizing documents, as any token in a document has to have been already seen in a query to have any chance // * of matching. // * // * @param input raw String that should be turned into tokens // * @param dontGenerateNewIds if set to true no new tokens will be generated. // * @return list of tokens // * @throws TokenizerException // */ // public List<Token> tokenize(String input, boolean dontGenerateNewIds) throws TokenizerException; // } // // Path: src/main/java/de/danielbasedow/prospecter/core/document/Field.java // public class Field { // protected final String name; // protected final List<Token> tokens; // // /** // * @param name name of the field // * @param tokens List of tokens in the field // */ // public Field(String name, List<Token> tokens) { // this.name = name; // this.tokens = tokens; // } // // public List<Token> getTokens() { // return tokens; // } // // public String getName() { // return name; // } // // }
import de.danielbasedow.prospecter.core.Matcher; import de.danielbasedow.prospecter.core.Token; import de.danielbasedow.prospecter.core.analysis.Analyzer; import de.danielbasedow.prospecter.core.document.Field; import gnu.trove.list.TLongList; import gnu.trove.list.array.TLongArrayList; import gnu.trove.map.hash.TIntObjectHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList;
package de.danielbasedow.prospecter.core.index; /** * Index enabling full text search */ public class FullTextIndex extends AbstractFieldIndex { private static final Logger LOGGER = LoggerFactory.getLogger(FullTextIndex.class); protected final TIntObjectHashMap<TLongList> index = new TIntObjectHashMap<TLongList>();
// Path: src/main/java/de/danielbasedow/prospecter/core/Matcher.java // public class Matcher { // protected final TIntObjectHashMap<BitSet> hits = new TIntObjectHashMap<BitSet>(); // protected final TIntObjectHashMap<QueryNegativeCounter> negativeHits = new TIntObjectHashMap<QueryNegativeCounter>(); // // protected final QueryManager queryManager; // // public Matcher(QueryManager qm) { // queryManager = qm; // } // // public void addHits(TLongList postings) { // postings.forEach(new TLongProcedure() { // @Override // public boolean execute(long posting) { // addHit(posting); // return true; // } // }); // } // // public void addHit(long posting) { // int[] unpacked = QueryPosting.unpack(posting); // int queryId = unpacked[QueryPosting.QUERY_ID_INDEX]; // // if (unpacked[QueryPosting.QUERY_NOT_INDEX] == 1) { // QueryNegativeCounter counter = negativeHits.get(queryId); // if (counter == null) { // counter = new QueryNegativeCounter(); // negativeHits.put(queryId, counter); // } // counter.add(unpacked[QueryPosting.QUERY_BIT_INDEX]); // } else { // BitSet bits = hits.get(queryId); // if (bits == null) { // bits = new BitSet(); // hits.put(queryId, bits); // } // bits.set(unpacked[QueryPosting.QUERY_BIT_INDEX]); // } // } // // public int getPositiveMatchCount() { // return hits.size(); // } // // public int getNegativeMatchCount() { // return negativeHits.size(); // } // // public List<Integer> getMatchedQueries() { // final List<Integer> results = new ArrayList<Integer>(); // // hits.forEachEntry(new TIntObjectProcedure<BitSet>() { // @Override // public boolean execute(int queryId, BitSet bitSet) { // BitSet mask = queryManager.getMask(queryId); // if (mask != null) { // if (mask.equals(bitSet)) { // results.add(queryId); // } else { // QueryNegativeCounter countMask = queryManager.getQueryNegativeCounter(queryId); // if (countMask != null) { // QueryNegativeCounter actualCount = negativeHits.get(queryId); // if (actualCount == null) { // actualCount = new QueryNegativeCounter(); // } // int[] bitPositions = countMask.getBitPositionsToSet(actualCount); // if (bitPositions.length > 0) { // for (int position : bitPositions) { // bitSet.set(position, true); // } // } // if (mask.equals(bitSet)) { // results.add(queryId); // } // } // } // } // return true; // } // }); // return results; // } // } // // Path: src/main/java/de/danielbasedow/prospecter/core/Token.java // public class Token<T> { // private final T token; // private final MatchCondition condition; // // public Token(T token) { // this(token, MatchCondition.NONE); // } // // public Token(T token, MatchCondition condition) { // this.token = token; // this.condition = condition; // } // // public T getToken() { // return token; // } // // public int hashCode() { // return token.hashCode(); // } // // public boolean equals(Object compare) { // if (compare instanceof Token) { // return token.equals(((Token) compare).getToken()); // } // return false; // } // // public MatchCondition getCondition() { // return condition; // } // } // // Path: src/main/java/de/danielbasedow/prospecter/core/analysis/Analyzer.java // public interface Analyzer { // /** // * Tokenizes raw input // * // * @param input raw String that should be turned into tokens // * @return list of tokens // * @throws TokenizerException // */ // public List<Token> tokenize(String input) throws TokenizerException; // // /** // * Tokenizes raw input. It is possible to turn off generating formerly unknown tokens. This makes sense when // * tokenizing documents, as any token in a document has to have been already seen in a query to have any chance // * of matching. // * // * @param input raw String that should be turned into tokens // * @param dontGenerateNewIds if set to true no new tokens will be generated. // * @return list of tokens // * @throws TokenizerException // */ // public List<Token> tokenize(String input, boolean dontGenerateNewIds) throws TokenizerException; // } // // Path: src/main/java/de/danielbasedow/prospecter/core/document/Field.java // public class Field { // protected final String name; // protected final List<Token> tokens; // // /** // * @param name name of the field // * @param tokens List of tokens in the field // */ // public Field(String name, List<Token> tokens) { // this.name = name; // this.tokens = tokens; // } // // public List<Token> getTokens() { // return tokens; // } // // public String getName() { // return name; // } // // } // Path: src/main/java/de/danielbasedow/prospecter/core/index/FullTextIndex.java import de.danielbasedow.prospecter.core.Matcher; import de.danielbasedow.prospecter.core.Token; import de.danielbasedow.prospecter.core.analysis.Analyzer; import de.danielbasedow.prospecter.core.document.Field; import gnu.trove.list.TLongList; import gnu.trove.list.array.TLongArrayList; import gnu.trove.map.hash.TIntObjectHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; package de.danielbasedow.prospecter.core.index; /** * Index enabling full text search */ public class FullTextIndex extends AbstractFieldIndex { private static final Logger LOGGER = LoggerFactory.getLogger(FullTextIndex.class); protected final TIntObjectHashMap<TLongList> index = new TIntObjectHashMap<TLongList>();
private final Analyzer analyzer;
dbasedow/prospecter
src/main/java/de/danielbasedow/prospecter/core/index/FullTextIndex.java
// Path: src/main/java/de/danielbasedow/prospecter/core/Matcher.java // public class Matcher { // protected final TIntObjectHashMap<BitSet> hits = new TIntObjectHashMap<BitSet>(); // protected final TIntObjectHashMap<QueryNegativeCounter> negativeHits = new TIntObjectHashMap<QueryNegativeCounter>(); // // protected final QueryManager queryManager; // // public Matcher(QueryManager qm) { // queryManager = qm; // } // // public void addHits(TLongList postings) { // postings.forEach(new TLongProcedure() { // @Override // public boolean execute(long posting) { // addHit(posting); // return true; // } // }); // } // // public void addHit(long posting) { // int[] unpacked = QueryPosting.unpack(posting); // int queryId = unpacked[QueryPosting.QUERY_ID_INDEX]; // // if (unpacked[QueryPosting.QUERY_NOT_INDEX] == 1) { // QueryNegativeCounter counter = negativeHits.get(queryId); // if (counter == null) { // counter = new QueryNegativeCounter(); // negativeHits.put(queryId, counter); // } // counter.add(unpacked[QueryPosting.QUERY_BIT_INDEX]); // } else { // BitSet bits = hits.get(queryId); // if (bits == null) { // bits = new BitSet(); // hits.put(queryId, bits); // } // bits.set(unpacked[QueryPosting.QUERY_BIT_INDEX]); // } // } // // public int getPositiveMatchCount() { // return hits.size(); // } // // public int getNegativeMatchCount() { // return negativeHits.size(); // } // // public List<Integer> getMatchedQueries() { // final List<Integer> results = new ArrayList<Integer>(); // // hits.forEachEntry(new TIntObjectProcedure<BitSet>() { // @Override // public boolean execute(int queryId, BitSet bitSet) { // BitSet mask = queryManager.getMask(queryId); // if (mask != null) { // if (mask.equals(bitSet)) { // results.add(queryId); // } else { // QueryNegativeCounter countMask = queryManager.getQueryNegativeCounter(queryId); // if (countMask != null) { // QueryNegativeCounter actualCount = negativeHits.get(queryId); // if (actualCount == null) { // actualCount = new QueryNegativeCounter(); // } // int[] bitPositions = countMask.getBitPositionsToSet(actualCount); // if (bitPositions.length > 0) { // for (int position : bitPositions) { // bitSet.set(position, true); // } // } // if (mask.equals(bitSet)) { // results.add(queryId); // } // } // } // } // return true; // } // }); // return results; // } // } // // Path: src/main/java/de/danielbasedow/prospecter/core/Token.java // public class Token<T> { // private final T token; // private final MatchCondition condition; // // public Token(T token) { // this(token, MatchCondition.NONE); // } // // public Token(T token, MatchCondition condition) { // this.token = token; // this.condition = condition; // } // // public T getToken() { // return token; // } // // public int hashCode() { // return token.hashCode(); // } // // public boolean equals(Object compare) { // if (compare instanceof Token) { // return token.equals(((Token) compare).getToken()); // } // return false; // } // // public MatchCondition getCondition() { // return condition; // } // } // // Path: src/main/java/de/danielbasedow/prospecter/core/analysis/Analyzer.java // public interface Analyzer { // /** // * Tokenizes raw input // * // * @param input raw String that should be turned into tokens // * @return list of tokens // * @throws TokenizerException // */ // public List<Token> tokenize(String input) throws TokenizerException; // // /** // * Tokenizes raw input. It is possible to turn off generating formerly unknown tokens. This makes sense when // * tokenizing documents, as any token in a document has to have been already seen in a query to have any chance // * of matching. // * // * @param input raw String that should be turned into tokens // * @param dontGenerateNewIds if set to true no new tokens will be generated. // * @return list of tokens // * @throws TokenizerException // */ // public List<Token> tokenize(String input, boolean dontGenerateNewIds) throws TokenizerException; // } // // Path: src/main/java/de/danielbasedow/prospecter/core/document/Field.java // public class Field { // protected final String name; // protected final List<Token> tokens; // // /** // * @param name name of the field // * @param tokens List of tokens in the field // */ // public Field(String name, List<Token> tokens) { // this.name = name; // this.tokens = tokens; // } // // public List<Token> getTokens() { // return tokens; // } // // public String getName() { // return name; // } // // }
import de.danielbasedow.prospecter.core.Matcher; import de.danielbasedow.prospecter.core.Token; import de.danielbasedow.prospecter.core.analysis.Analyzer; import de.danielbasedow.prospecter.core.document.Field; import gnu.trove.list.TLongList; import gnu.trove.list.array.TLongArrayList; import gnu.trove.map.hash.TIntObjectHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList;
package de.danielbasedow.prospecter.core.index; /** * Index enabling full text search */ public class FullTextIndex extends AbstractFieldIndex { private static final Logger LOGGER = LoggerFactory.getLogger(FullTextIndex.class); protected final TIntObjectHashMap<TLongList> index = new TIntObjectHashMap<TLongList>(); private final Analyzer analyzer; public FullTextIndex(String name, Analyzer analyzer) { super(name); this.analyzer = analyzer; } @Override
// Path: src/main/java/de/danielbasedow/prospecter/core/Matcher.java // public class Matcher { // protected final TIntObjectHashMap<BitSet> hits = new TIntObjectHashMap<BitSet>(); // protected final TIntObjectHashMap<QueryNegativeCounter> negativeHits = new TIntObjectHashMap<QueryNegativeCounter>(); // // protected final QueryManager queryManager; // // public Matcher(QueryManager qm) { // queryManager = qm; // } // // public void addHits(TLongList postings) { // postings.forEach(new TLongProcedure() { // @Override // public boolean execute(long posting) { // addHit(posting); // return true; // } // }); // } // // public void addHit(long posting) { // int[] unpacked = QueryPosting.unpack(posting); // int queryId = unpacked[QueryPosting.QUERY_ID_INDEX]; // // if (unpacked[QueryPosting.QUERY_NOT_INDEX] == 1) { // QueryNegativeCounter counter = negativeHits.get(queryId); // if (counter == null) { // counter = new QueryNegativeCounter(); // negativeHits.put(queryId, counter); // } // counter.add(unpacked[QueryPosting.QUERY_BIT_INDEX]); // } else { // BitSet bits = hits.get(queryId); // if (bits == null) { // bits = new BitSet(); // hits.put(queryId, bits); // } // bits.set(unpacked[QueryPosting.QUERY_BIT_INDEX]); // } // } // // public int getPositiveMatchCount() { // return hits.size(); // } // // public int getNegativeMatchCount() { // return negativeHits.size(); // } // // public List<Integer> getMatchedQueries() { // final List<Integer> results = new ArrayList<Integer>(); // // hits.forEachEntry(new TIntObjectProcedure<BitSet>() { // @Override // public boolean execute(int queryId, BitSet bitSet) { // BitSet mask = queryManager.getMask(queryId); // if (mask != null) { // if (mask.equals(bitSet)) { // results.add(queryId); // } else { // QueryNegativeCounter countMask = queryManager.getQueryNegativeCounter(queryId); // if (countMask != null) { // QueryNegativeCounter actualCount = negativeHits.get(queryId); // if (actualCount == null) { // actualCount = new QueryNegativeCounter(); // } // int[] bitPositions = countMask.getBitPositionsToSet(actualCount); // if (bitPositions.length > 0) { // for (int position : bitPositions) { // bitSet.set(position, true); // } // } // if (mask.equals(bitSet)) { // results.add(queryId); // } // } // } // } // return true; // } // }); // return results; // } // } // // Path: src/main/java/de/danielbasedow/prospecter/core/Token.java // public class Token<T> { // private final T token; // private final MatchCondition condition; // // public Token(T token) { // this(token, MatchCondition.NONE); // } // // public Token(T token, MatchCondition condition) { // this.token = token; // this.condition = condition; // } // // public T getToken() { // return token; // } // // public int hashCode() { // return token.hashCode(); // } // // public boolean equals(Object compare) { // if (compare instanceof Token) { // return token.equals(((Token) compare).getToken()); // } // return false; // } // // public MatchCondition getCondition() { // return condition; // } // } // // Path: src/main/java/de/danielbasedow/prospecter/core/analysis/Analyzer.java // public interface Analyzer { // /** // * Tokenizes raw input // * // * @param input raw String that should be turned into tokens // * @return list of tokens // * @throws TokenizerException // */ // public List<Token> tokenize(String input) throws TokenizerException; // // /** // * Tokenizes raw input. It is possible to turn off generating formerly unknown tokens. This makes sense when // * tokenizing documents, as any token in a document has to have been already seen in a query to have any chance // * of matching. // * // * @param input raw String that should be turned into tokens // * @param dontGenerateNewIds if set to true no new tokens will be generated. // * @return list of tokens // * @throws TokenizerException // */ // public List<Token> tokenize(String input, boolean dontGenerateNewIds) throws TokenizerException; // } // // Path: src/main/java/de/danielbasedow/prospecter/core/document/Field.java // public class Field { // protected final String name; // protected final List<Token> tokens; // // /** // * @param name name of the field // * @param tokens List of tokens in the field // */ // public Field(String name, List<Token> tokens) { // this.name = name; // this.tokens = tokens; // } // // public List<Token> getTokens() { // return tokens; // } // // public String getName() { // return name; // } // // } // Path: src/main/java/de/danielbasedow/prospecter/core/index/FullTextIndex.java import de.danielbasedow.prospecter.core.Matcher; import de.danielbasedow.prospecter.core.Token; import de.danielbasedow.prospecter.core.analysis.Analyzer; import de.danielbasedow.prospecter.core.document.Field; import gnu.trove.list.TLongList; import gnu.trove.list.array.TLongArrayList; import gnu.trove.map.hash.TIntObjectHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; package de.danielbasedow.prospecter.core.index; /** * Index enabling full text search */ public class FullTextIndex extends AbstractFieldIndex { private static final Logger LOGGER = LoggerFactory.getLogger(FullTextIndex.class); protected final TIntObjectHashMap<TLongList> index = new TIntObjectHashMap<TLongList>(); private final Analyzer analyzer; public FullTextIndex(String name, Analyzer analyzer) { super(name); this.analyzer = analyzer; } @Override
public void addPosting(Token token, Long posting) {
dbasedow/prospecter
src/main/java/de/danielbasedow/prospecter/server/HttpApiRequestHandler.java
// Path: src/main/java/de/danielbasedow/prospecter/core/document/Document.java // public class Document { // protected final HashMap<String, Field> fields; // // public Document() { // fields = new HashMap<String, Field>(); // } // // /** // * Add a Field to the Document // * // * @param name name of the field // * @param field Field instance // */ // public void addField(String name, Field field) { // fields.put(name, field); // } // // /** // * Gets a Field instance by it's field name // * // * @param name name of the field // * @return Field instance // */ // public Field getField(String name) { // return fields.get(name); // } // // /** // * Get Iterator over all fields in this Document // * // * @return iterator over all available fields // */ // public FieldIterator getFields() { // return new FieldIterator(fields); // } // // } // // Path: src/main/java/de/danielbasedow/prospecter/core/document/MalformedDocumentException.java // public class MalformedDocumentException extends RuntimeException { // public MalformedDocumentException(String msg) { // super(msg); // } // // public MalformedDocumentException(String msg, Throwable cause) { // super(msg, cause); // } // } // // Path: src/main/java/de/danielbasedow/prospecter/core/schema/Schema.java // public interface Schema { // /** // * Add a new FieldIndex to the schema // * // * @param fieldName name of the field // * @param index index instance used to back this field // */ // public void addFieldIndex(String fieldName, FieldIndex index) throws SchemaConfigurationError; // // /** // * Get matches for a specific field. Useful for debugging index implementations. // * // * @param fieldIndexName name of the field // * @param field field instance from a Document // * @throws UndefinedIndexFieldException // */ // public void matchField(String fieldIndexName, Field field, Matcher matcher) throws UndefinedIndexFieldException; // // /** // * Add query to index. The postings will be added to the corresponding field indices. // * // * @param query the parsed query // * @throws UndefinedIndexFieldException // */ // public void addQuery(Query query) throws UndefinedIndexFieldException; // // /** // * Add query to index. The supplied String will be parsed as JSON and the resulting Query object is passed to // * addQuery(Query query) // * // * @param json raw JSON string // * @throws UndefinedIndexFieldException // */ // public void addQuery(String json) throws UndefinedIndexFieldException, MalformedQueryException; // // /** // * Collect all matches for a document // * // * @param doc document instance // * @param matcher an unused matcher // * @return matcher // */ // public Matcher matchDocument(Document doc, Matcher matcher); // // /** // * Collect all matches from a document. A new Matcher instance is automatically created // * // * @param doc document instance // * @return matcher // */ // public Matcher matchDocument(Document doc); // // public int getFieldCount(); // // public FieldIndex getFieldIndex(String name); // // public AdvancedQueryBuilder getQueryBuilder(); // // public DocumentBuilder getDocumentBuilder(); // // public Matcher getMatcher(); // // public QueryManager getQueryManager(); // // public void setQueryStorage(QueryStorage queryStorage); // // /** // * Tidy up before shutting down, close files and network connections // */ // public void close(); // // /** // * execute any code that should run after the SchemaBuilder is finished. For example loading queries from disk // */ // public void init(); // // public void deleteQuery(Integer queryId); // // /** // * optimize storage requirements // */ // public void trim(); // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import de.danielbasedow.prospecter.core.*; import de.danielbasedow.prospecter.core.document.Document; import de.danielbasedow.prospecter.core.document.MalformedDocumentException; import de.danielbasedow.prospecter.core.schema.Schema; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.*; import io.netty.util.CharsetUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package de.danielbasedow.prospecter.server; public class HttpApiRequestHandler extends SimpleChannelInboundHandler<Object> { private static final ObjectMapper mapper = new ObjectMapper(); private final Instance instance; private FullHttpRequest request; private static final Logger LOGGER = LoggerFactory.getLogger(HttpApiRequestHandler.class); public HttpApiRequestHandler(Instance instance) { this.instance = instance; } private final StringBuilder responseBuffer = new StringBuilder(); @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { this.request = (FullHttpRequest) msg; } else { throw new Exception(); } FullHttpResponse response; try { response = dispatch(); } catch (Exception e) { LOGGER.warn(e.getLocalizedMessage(), e); response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.copiedBuffer(e.getLocalizedMessage(), CharsetUtil.UTF_8) ); } ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
// Path: src/main/java/de/danielbasedow/prospecter/core/document/Document.java // public class Document { // protected final HashMap<String, Field> fields; // // public Document() { // fields = new HashMap<String, Field>(); // } // // /** // * Add a Field to the Document // * // * @param name name of the field // * @param field Field instance // */ // public void addField(String name, Field field) { // fields.put(name, field); // } // // /** // * Gets a Field instance by it's field name // * // * @param name name of the field // * @return Field instance // */ // public Field getField(String name) { // return fields.get(name); // } // // /** // * Get Iterator over all fields in this Document // * // * @return iterator over all available fields // */ // public FieldIterator getFields() { // return new FieldIterator(fields); // } // // } // // Path: src/main/java/de/danielbasedow/prospecter/core/document/MalformedDocumentException.java // public class MalformedDocumentException extends RuntimeException { // public MalformedDocumentException(String msg) { // super(msg); // } // // public MalformedDocumentException(String msg, Throwable cause) { // super(msg, cause); // } // } // // Path: src/main/java/de/danielbasedow/prospecter/core/schema/Schema.java // public interface Schema { // /** // * Add a new FieldIndex to the schema // * // * @param fieldName name of the field // * @param index index instance used to back this field // */ // public void addFieldIndex(String fieldName, FieldIndex index) throws SchemaConfigurationError; // // /** // * Get matches for a specific field. Useful for debugging index implementations. // * // * @param fieldIndexName name of the field // * @param field field instance from a Document // * @throws UndefinedIndexFieldException // */ // public void matchField(String fieldIndexName, Field field, Matcher matcher) throws UndefinedIndexFieldException; // // /** // * Add query to index. The postings will be added to the corresponding field indices. // * // * @param query the parsed query // * @throws UndefinedIndexFieldException // */ // public void addQuery(Query query) throws UndefinedIndexFieldException; // // /** // * Add query to index. The supplied String will be parsed as JSON and the resulting Query object is passed to // * addQuery(Query query) // * // * @param json raw JSON string // * @throws UndefinedIndexFieldException // */ // public void addQuery(String json) throws UndefinedIndexFieldException, MalformedQueryException; // // /** // * Collect all matches for a document // * // * @param doc document instance // * @param matcher an unused matcher // * @return matcher // */ // public Matcher matchDocument(Document doc, Matcher matcher); // // /** // * Collect all matches from a document. A new Matcher instance is automatically created // * // * @param doc document instance // * @return matcher // */ // public Matcher matchDocument(Document doc); // // public int getFieldCount(); // // public FieldIndex getFieldIndex(String name); // // public AdvancedQueryBuilder getQueryBuilder(); // // public DocumentBuilder getDocumentBuilder(); // // public Matcher getMatcher(); // // public QueryManager getQueryManager(); // // public void setQueryStorage(QueryStorage queryStorage); // // /** // * Tidy up before shutting down, close files and network connections // */ // public void close(); // // /** // * execute any code that should run after the SchemaBuilder is finished. For example loading queries from disk // */ // public void init(); // // public void deleteQuery(Integer queryId); // // /** // * optimize storage requirements // */ // public void trim(); // } // Path: src/main/java/de/danielbasedow/prospecter/server/HttpApiRequestHandler.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import de.danielbasedow.prospecter.core.*; import de.danielbasedow.prospecter.core.document.Document; import de.danielbasedow.prospecter.core.document.MalformedDocumentException; import de.danielbasedow.prospecter.core.schema.Schema; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.*; import io.netty.util.CharsetUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package de.danielbasedow.prospecter.server; public class HttpApiRequestHandler extends SimpleChannelInboundHandler<Object> { private static final ObjectMapper mapper = new ObjectMapper(); private final Instance instance; private FullHttpRequest request; private static final Logger LOGGER = LoggerFactory.getLogger(HttpApiRequestHandler.class); public HttpApiRequestHandler(Instance instance) { this.instance = instance; } private final StringBuilder responseBuffer = new StringBuilder(); @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { this.request = (FullHttpRequest) msg; } else { throw new Exception(); } FullHttpResponse response; try { response = dispatch(); } catch (Exception e) { LOGGER.warn(e.getLocalizedMessage(), e); response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.copiedBuffer(e.getLocalizedMessage(), CharsetUtil.UTF_8) ); } ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
protected FullHttpResponse dispatch() throws UndefinedIndexFieldException, MalformedQueryException, MalformedDocumentException, JsonProcessingException {
dbasedow/prospecter
src/main/java/de/danielbasedow/prospecter/server/HttpApiRequestHandler.java
// Path: src/main/java/de/danielbasedow/prospecter/core/document/Document.java // public class Document { // protected final HashMap<String, Field> fields; // // public Document() { // fields = new HashMap<String, Field>(); // } // // /** // * Add a Field to the Document // * // * @param name name of the field // * @param field Field instance // */ // public void addField(String name, Field field) { // fields.put(name, field); // } // // /** // * Gets a Field instance by it's field name // * // * @param name name of the field // * @return Field instance // */ // public Field getField(String name) { // return fields.get(name); // } // // /** // * Get Iterator over all fields in this Document // * // * @return iterator over all available fields // */ // public FieldIterator getFields() { // return new FieldIterator(fields); // } // // } // // Path: src/main/java/de/danielbasedow/prospecter/core/document/MalformedDocumentException.java // public class MalformedDocumentException extends RuntimeException { // public MalformedDocumentException(String msg) { // super(msg); // } // // public MalformedDocumentException(String msg, Throwable cause) { // super(msg, cause); // } // } // // Path: src/main/java/de/danielbasedow/prospecter/core/schema/Schema.java // public interface Schema { // /** // * Add a new FieldIndex to the schema // * // * @param fieldName name of the field // * @param index index instance used to back this field // */ // public void addFieldIndex(String fieldName, FieldIndex index) throws SchemaConfigurationError; // // /** // * Get matches for a specific field. Useful for debugging index implementations. // * // * @param fieldIndexName name of the field // * @param field field instance from a Document // * @throws UndefinedIndexFieldException // */ // public void matchField(String fieldIndexName, Field field, Matcher matcher) throws UndefinedIndexFieldException; // // /** // * Add query to index. The postings will be added to the corresponding field indices. // * // * @param query the parsed query // * @throws UndefinedIndexFieldException // */ // public void addQuery(Query query) throws UndefinedIndexFieldException; // // /** // * Add query to index. The supplied String will be parsed as JSON and the resulting Query object is passed to // * addQuery(Query query) // * // * @param json raw JSON string // * @throws UndefinedIndexFieldException // */ // public void addQuery(String json) throws UndefinedIndexFieldException, MalformedQueryException; // // /** // * Collect all matches for a document // * // * @param doc document instance // * @param matcher an unused matcher // * @return matcher // */ // public Matcher matchDocument(Document doc, Matcher matcher); // // /** // * Collect all matches from a document. A new Matcher instance is automatically created // * // * @param doc document instance // * @return matcher // */ // public Matcher matchDocument(Document doc); // // public int getFieldCount(); // // public FieldIndex getFieldIndex(String name); // // public AdvancedQueryBuilder getQueryBuilder(); // // public DocumentBuilder getDocumentBuilder(); // // public Matcher getMatcher(); // // public QueryManager getQueryManager(); // // public void setQueryStorage(QueryStorage queryStorage); // // /** // * Tidy up before shutting down, close files and network connections // */ // public void close(); // // /** // * execute any code that should run after the SchemaBuilder is finished. For example loading queries from disk // */ // public void init(); // // public void deleteQuery(Integer queryId); // // /** // * optimize storage requirements // */ // public void trim(); // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import de.danielbasedow.prospecter.core.*; import de.danielbasedow.prospecter.core.document.Document; import de.danielbasedow.prospecter.core.document.MalformedDocumentException; import de.danielbasedow.prospecter.core.schema.Schema; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.*; import io.netty.util.CharsetUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
); } ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } protected FullHttpResponse dispatch() throws UndefinedIndexFieldException, MalformedQueryException, MalformedDocumentException, JsonProcessingException { String uri = request.getUri(); String[] uriParts = uri.split("/"); if (uriParts.length == 0) { LOGGER.warn("root uri specified, please supply a valid uri! Doing nothing!"); return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR); } String schemaName = uriParts[1]; LOGGER.debug("method: " + request.getMethod() + ", schema: '" + schemaName + "'"); if (request.getMethod() == HttpMethod.POST && schemaName != null) { return matchDocument(instance.getSchema(schemaName)); } if (request.getMethod() == HttpMethod.PUT && schemaName != null) { return addQuery(instance.getSchema(schemaName)); } if (request.getMethod() == HttpMethod.DELETE && schemaName != null) { String queryId = uriParts[1]; return deleteQuery(instance.getSchema(schemaName), queryId); } return null; }
// Path: src/main/java/de/danielbasedow/prospecter/core/document/Document.java // public class Document { // protected final HashMap<String, Field> fields; // // public Document() { // fields = new HashMap<String, Field>(); // } // // /** // * Add a Field to the Document // * // * @param name name of the field // * @param field Field instance // */ // public void addField(String name, Field field) { // fields.put(name, field); // } // // /** // * Gets a Field instance by it's field name // * // * @param name name of the field // * @return Field instance // */ // public Field getField(String name) { // return fields.get(name); // } // // /** // * Get Iterator over all fields in this Document // * // * @return iterator over all available fields // */ // public FieldIterator getFields() { // return new FieldIterator(fields); // } // // } // // Path: src/main/java/de/danielbasedow/prospecter/core/document/MalformedDocumentException.java // public class MalformedDocumentException extends RuntimeException { // public MalformedDocumentException(String msg) { // super(msg); // } // // public MalformedDocumentException(String msg, Throwable cause) { // super(msg, cause); // } // } // // Path: src/main/java/de/danielbasedow/prospecter/core/schema/Schema.java // public interface Schema { // /** // * Add a new FieldIndex to the schema // * // * @param fieldName name of the field // * @param index index instance used to back this field // */ // public void addFieldIndex(String fieldName, FieldIndex index) throws SchemaConfigurationError; // // /** // * Get matches for a specific field. Useful for debugging index implementations. // * // * @param fieldIndexName name of the field // * @param field field instance from a Document // * @throws UndefinedIndexFieldException // */ // public void matchField(String fieldIndexName, Field field, Matcher matcher) throws UndefinedIndexFieldException; // // /** // * Add query to index. The postings will be added to the corresponding field indices. // * // * @param query the parsed query // * @throws UndefinedIndexFieldException // */ // public void addQuery(Query query) throws UndefinedIndexFieldException; // // /** // * Add query to index. The supplied String will be parsed as JSON and the resulting Query object is passed to // * addQuery(Query query) // * // * @param json raw JSON string // * @throws UndefinedIndexFieldException // */ // public void addQuery(String json) throws UndefinedIndexFieldException, MalformedQueryException; // // /** // * Collect all matches for a document // * // * @param doc document instance // * @param matcher an unused matcher // * @return matcher // */ // public Matcher matchDocument(Document doc, Matcher matcher); // // /** // * Collect all matches from a document. A new Matcher instance is automatically created // * // * @param doc document instance // * @return matcher // */ // public Matcher matchDocument(Document doc); // // public int getFieldCount(); // // public FieldIndex getFieldIndex(String name); // // public AdvancedQueryBuilder getQueryBuilder(); // // public DocumentBuilder getDocumentBuilder(); // // public Matcher getMatcher(); // // public QueryManager getQueryManager(); // // public void setQueryStorage(QueryStorage queryStorage); // // /** // * Tidy up before shutting down, close files and network connections // */ // public void close(); // // /** // * execute any code that should run after the SchemaBuilder is finished. For example loading queries from disk // */ // public void init(); // // public void deleteQuery(Integer queryId); // // /** // * optimize storage requirements // */ // public void trim(); // } // Path: src/main/java/de/danielbasedow/prospecter/server/HttpApiRequestHandler.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import de.danielbasedow.prospecter.core.*; import de.danielbasedow.prospecter.core.document.Document; import de.danielbasedow.prospecter.core.document.MalformedDocumentException; import de.danielbasedow.prospecter.core.schema.Schema; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.*; import io.netty.util.CharsetUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; ); } ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } protected FullHttpResponse dispatch() throws UndefinedIndexFieldException, MalformedQueryException, MalformedDocumentException, JsonProcessingException { String uri = request.getUri(); String[] uriParts = uri.split("/"); if (uriParts.length == 0) { LOGGER.warn("root uri specified, please supply a valid uri! Doing nothing!"); return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR); } String schemaName = uriParts[1]; LOGGER.debug("method: " + request.getMethod() + ", schema: '" + schemaName + "'"); if (request.getMethod() == HttpMethod.POST && schemaName != null) { return matchDocument(instance.getSchema(schemaName)); } if (request.getMethod() == HttpMethod.PUT && schemaName != null) { return addQuery(instance.getSchema(schemaName)); } if (request.getMethod() == HttpMethod.DELETE && schemaName != null) { String queryId = uriParts[1]; return deleteQuery(instance.getSchema(schemaName), queryId); } return null; }
protected DefaultFullHttpResponse addQuery(Schema schema) throws MalformedQueryException, UndefinedIndexFieldException {
dbasedow/prospecter
src/main/java/de/danielbasedow/prospecter/server/HttpApiRequestHandler.java
// Path: src/main/java/de/danielbasedow/prospecter/core/document/Document.java // public class Document { // protected final HashMap<String, Field> fields; // // public Document() { // fields = new HashMap<String, Field>(); // } // // /** // * Add a Field to the Document // * // * @param name name of the field // * @param field Field instance // */ // public void addField(String name, Field field) { // fields.put(name, field); // } // // /** // * Gets a Field instance by it's field name // * // * @param name name of the field // * @return Field instance // */ // public Field getField(String name) { // return fields.get(name); // } // // /** // * Get Iterator over all fields in this Document // * // * @return iterator over all available fields // */ // public FieldIterator getFields() { // return new FieldIterator(fields); // } // // } // // Path: src/main/java/de/danielbasedow/prospecter/core/document/MalformedDocumentException.java // public class MalformedDocumentException extends RuntimeException { // public MalformedDocumentException(String msg) { // super(msg); // } // // public MalformedDocumentException(String msg, Throwable cause) { // super(msg, cause); // } // } // // Path: src/main/java/de/danielbasedow/prospecter/core/schema/Schema.java // public interface Schema { // /** // * Add a new FieldIndex to the schema // * // * @param fieldName name of the field // * @param index index instance used to back this field // */ // public void addFieldIndex(String fieldName, FieldIndex index) throws SchemaConfigurationError; // // /** // * Get matches for a specific field. Useful for debugging index implementations. // * // * @param fieldIndexName name of the field // * @param field field instance from a Document // * @throws UndefinedIndexFieldException // */ // public void matchField(String fieldIndexName, Field field, Matcher matcher) throws UndefinedIndexFieldException; // // /** // * Add query to index. The postings will be added to the corresponding field indices. // * // * @param query the parsed query // * @throws UndefinedIndexFieldException // */ // public void addQuery(Query query) throws UndefinedIndexFieldException; // // /** // * Add query to index. The supplied String will be parsed as JSON and the resulting Query object is passed to // * addQuery(Query query) // * // * @param json raw JSON string // * @throws UndefinedIndexFieldException // */ // public void addQuery(String json) throws UndefinedIndexFieldException, MalformedQueryException; // // /** // * Collect all matches for a document // * // * @param doc document instance // * @param matcher an unused matcher // * @return matcher // */ // public Matcher matchDocument(Document doc, Matcher matcher); // // /** // * Collect all matches from a document. A new Matcher instance is automatically created // * // * @param doc document instance // * @return matcher // */ // public Matcher matchDocument(Document doc); // // public int getFieldCount(); // // public FieldIndex getFieldIndex(String name); // // public AdvancedQueryBuilder getQueryBuilder(); // // public DocumentBuilder getDocumentBuilder(); // // public Matcher getMatcher(); // // public QueryManager getQueryManager(); // // public void setQueryStorage(QueryStorage queryStorage); // // /** // * Tidy up before shutting down, close files and network connections // */ // public void close(); // // /** // * execute any code that should run after the SchemaBuilder is finished. For example loading queries from disk // */ // public void init(); // // public void deleteQuery(Integer queryId); // // /** // * optimize storage requirements // */ // public void trim(); // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import de.danielbasedow.prospecter.core.*; import de.danielbasedow.prospecter.core.document.Document; import de.danielbasedow.prospecter.core.document.MalformedDocumentException; import de.danielbasedow.prospecter.core.schema.Schema; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.*; import io.netty.util.CharsetUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
if (request.getMethod() == HttpMethod.PUT && schemaName != null) { return addQuery(instance.getSchema(schemaName)); } if (request.getMethod() == HttpMethod.DELETE && schemaName != null) { String queryId = uriParts[1]; return deleteQuery(instance.getSchema(schemaName), queryId); } return null; } protected DefaultFullHttpResponse addQuery(Schema schema) throws MalformedQueryException, UndefinedIndexFieldException { ByteBuf content = request.content(); if (content.isReadable()) { schema.addQuery(content.toString(CharsetUtil.UTF_8)); } return new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer("", CharsetUtil.UTF_8) ); } protected FullHttpResponse matchDocument(Schema schema) throws MalformedDocumentException, JsonProcessingException { ByteBuf content = request.content(); int matchCount = 0; ObjectNode node = mapper.getNodeFactory().objectNode(); if (content.isReadable()) { LOGGER.debug("start matching");
// Path: src/main/java/de/danielbasedow/prospecter/core/document/Document.java // public class Document { // protected final HashMap<String, Field> fields; // // public Document() { // fields = new HashMap<String, Field>(); // } // // /** // * Add a Field to the Document // * // * @param name name of the field // * @param field Field instance // */ // public void addField(String name, Field field) { // fields.put(name, field); // } // // /** // * Gets a Field instance by it's field name // * // * @param name name of the field // * @return Field instance // */ // public Field getField(String name) { // return fields.get(name); // } // // /** // * Get Iterator over all fields in this Document // * // * @return iterator over all available fields // */ // public FieldIterator getFields() { // return new FieldIterator(fields); // } // // } // // Path: src/main/java/de/danielbasedow/prospecter/core/document/MalformedDocumentException.java // public class MalformedDocumentException extends RuntimeException { // public MalformedDocumentException(String msg) { // super(msg); // } // // public MalformedDocumentException(String msg, Throwable cause) { // super(msg, cause); // } // } // // Path: src/main/java/de/danielbasedow/prospecter/core/schema/Schema.java // public interface Schema { // /** // * Add a new FieldIndex to the schema // * // * @param fieldName name of the field // * @param index index instance used to back this field // */ // public void addFieldIndex(String fieldName, FieldIndex index) throws SchemaConfigurationError; // // /** // * Get matches for a specific field. Useful for debugging index implementations. // * // * @param fieldIndexName name of the field // * @param field field instance from a Document // * @throws UndefinedIndexFieldException // */ // public void matchField(String fieldIndexName, Field field, Matcher matcher) throws UndefinedIndexFieldException; // // /** // * Add query to index. The postings will be added to the corresponding field indices. // * // * @param query the parsed query // * @throws UndefinedIndexFieldException // */ // public void addQuery(Query query) throws UndefinedIndexFieldException; // // /** // * Add query to index. The supplied String will be parsed as JSON and the resulting Query object is passed to // * addQuery(Query query) // * // * @param json raw JSON string // * @throws UndefinedIndexFieldException // */ // public void addQuery(String json) throws UndefinedIndexFieldException, MalformedQueryException; // // /** // * Collect all matches for a document // * // * @param doc document instance // * @param matcher an unused matcher // * @return matcher // */ // public Matcher matchDocument(Document doc, Matcher matcher); // // /** // * Collect all matches from a document. A new Matcher instance is automatically created // * // * @param doc document instance // * @return matcher // */ // public Matcher matchDocument(Document doc); // // public int getFieldCount(); // // public FieldIndex getFieldIndex(String name); // // public AdvancedQueryBuilder getQueryBuilder(); // // public DocumentBuilder getDocumentBuilder(); // // public Matcher getMatcher(); // // public QueryManager getQueryManager(); // // public void setQueryStorage(QueryStorage queryStorage); // // /** // * Tidy up before shutting down, close files and network connections // */ // public void close(); // // /** // * execute any code that should run after the SchemaBuilder is finished. For example loading queries from disk // */ // public void init(); // // public void deleteQuery(Integer queryId); // // /** // * optimize storage requirements // */ // public void trim(); // } // Path: src/main/java/de/danielbasedow/prospecter/server/HttpApiRequestHandler.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import de.danielbasedow.prospecter.core.*; import de.danielbasedow.prospecter.core.document.Document; import de.danielbasedow.prospecter.core.document.MalformedDocumentException; import de.danielbasedow.prospecter.core.schema.Schema; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.*; import io.netty.util.CharsetUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; if (request.getMethod() == HttpMethod.PUT && schemaName != null) { return addQuery(instance.getSchema(schemaName)); } if (request.getMethod() == HttpMethod.DELETE && schemaName != null) { String queryId = uriParts[1]; return deleteQuery(instance.getSchema(schemaName), queryId); } return null; } protected DefaultFullHttpResponse addQuery(Schema schema) throws MalformedQueryException, UndefinedIndexFieldException { ByteBuf content = request.content(); if (content.isReadable()) { schema.addQuery(content.toString(CharsetUtil.UTF_8)); } return new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer("", CharsetUtil.UTF_8) ); } protected FullHttpResponse matchDocument(Schema schema) throws MalformedDocumentException, JsonProcessingException { ByteBuf content = request.content(); int matchCount = 0; ObjectNode node = mapper.getNodeFactory().objectNode(); if (content.isReadable()) { LOGGER.debug("start matching");
Document doc = schema.getDocumentBuilder().build(content.toString(CharsetUtil.UTF_8));
dbasedow/prospecter
src/main/java/de/danielbasedow/prospecter/core/analysis/AnalyzerModule.java
// Path: src/main/java/de/danielbasedow/prospecter/core/TokenMapper.java // public interface TokenMapper { // public int getTermId(String str, boolean dontGenerateNewIds); // // public void setBloomFilter(BloomFilter<String> bloomFilter); // } // // Path: src/main/java/de/danielbasedow/prospecter/core/TokenMapperImpl.java // public class TokenMapperImpl implements TokenMapper { // protected int termIdSequence; // protected final TObjectIntHashMap<String> termMap = new TObjectIntHashMap<String>(); // protected BloomFilter<String> bloomFilter; // // public TokenMapperImpl() { // termIdSequence = 1; // bloomFilter = new FakeBloomFilter<String>(); // } // // @Override // public int getTermId(String str, boolean dontGenerateNewIds) { // int termId = 0; // if (bloomFilter.contains(str)) { // termId = termMap.get(str); // } // if (termId == 0 && !dontGenerateNewIds) { // synchronized (this) { // termId = getNewTermId(); // termMap.put(str, termId); // bloomFilter.add(str); // } // } // return termId; // } // // @Override // public void setBloomFilter(BloomFilter<String> bloomFilter) { // this.bloomFilter = bloomFilter; // } // // public int getNewTermId() { // return termIdSequence++; // } // }
import com.google.inject.AbstractModule; import com.google.inject.Singleton; import de.danielbasedow.prospecter.core.TokenMapper; import de.danielbasedow.prospecter.core.TokenMapperImpl;
package de.danielbasedow.prospecter.core.analysis; public class AnalyzerModule extends AbstractModule { @Override protected void configure() {
// Path: src/main/java/de/danielbasedow/prospecter/core/TokenMapper.java // public interface TokenMapper { // public int getTermId(String str, boolean dontGenerateNewIds); // // public void setBloomFilter(BloomFilter<String> bloomFilter); // } // // Path: src/main/java/de/danielbasedow/prospecter/core/TokenMapperImpl.java // public class TokenMapperImpl implements TokenMapper { // protected int termIdSequence; // protected final TObjectIntHashMap<String> termMap = new TObjectIntHashMap<String>(); // protected BloomFilter<String> bloomFilter; // // public TokenMapperImpl() { // termIdSequence = 1; // bloomFilter = new FakeBloomFilter<String>(); // } // // @Override // public int getTermId(String str, boolean dontGenerateNewIds) { // int termId = 0; // if (bloomFilter.contains(str)) { // termId = termMap.get(str); // } // if (termId == 0 && !dontGenerateNewIds) { // synchronized (this) { // termId = getNewTermId(); // termMap.put(str, termId); // bloomFilter.add(str); // } // } // return termId; // } // // @Override // public void setBloomFilter(BloomFilter<String> bloomFilter) { // this.bloomFilter = bloomFilter; // } // // public int getNewTermId() { // return termIdSequence++; // } // } // Path: src/main/java/de/danielbasedow/prospecter/core/analysis/AnalyzerModule.java import com.google.inject.AbstractModule; import com.google.inject.Singleton; import de.danielbasedow.prospecter.core.TokenMapper; import de.danielbasedow.prospecter.core.TokenMapperImpl; package de.danielbasedow.prospecter.core.analysis; public class AnalyzerModule extends AbstractModule { @Override protected void configure() {
bind(TokenMapper.class).to(TokenMapperImpl.class).in(Singleton.class);