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
protolambda/blocktopograph
app/src/main/java/com/protolambda/blocktopograph/nbt/tags/ListTag.java
// Path: app/src/main/java/com/protolambda/blocktopograph/nbt/convert/NBTConstants.java // public class NBTConstants { // // public enum NBTType { // // END(0, EndTag.class, "EndTag"), // BYTE(1, ByteTag.class, "ByteTag"), // SHORT(2, ShortTag.class, "ShortTag"), // INT(3, IntTag.class, "IntTag"), // LONG(4, LongTag.class, "LongTag"), // FLOAT(5, FloatTag.class, "FloatTag"), // DOUBLE(6, DoubleTag.class, "DoubleTag"), // BYTE_ARRAY(7, ByteArrayTag.class, "ByteArrayTag"), // STRING(8, StringTag.class, "StringTag"), // LIST(9, ListTag.class, "ListTag"), // COMPOUND(10, CompoundTag.class, "CompoundTag"), // INT_ARRAY(11, IntArrayTag.class, "IntArrayTag"), // // //Is this one even used?!? Maybe used in mods? // SHORT_ARRAY(100, ShortArrayTag.class, "ShortArrayTag"); // // public final int id; // public final Class<? extends Tag> tagClazz; // public final String displayName; // // static public Map<Integer, NBTType> typesByID = new HashMap<>(); // static public Map<Class<? extends Tag>, NBTType> typesByClazz = new HashMap<>(); // // NBTType(int id, Class<? extends Tag> tagClazz, String displayName){ // this.id = id; // this.tagClazz = tagClazz; // this.displayName = displayName; // } // // //not all NBT types are meant to be created in an editor, the END tag for example. // public static String[] editorOptions_asString; // public static NBTType[] editorOptions_asType = new NBTType[]{ // BYTE, // SHORT, // INT, // LONG, // FLOAT, // DOUBLE, // BYTE_ARRAY, // STRING, // LIST, // COMPOUND, // INT_ARRAY, // SHORT_ARRAY // }; // // static { // // // int len = editorOptions_asType.length; // editorOptions_asString = new String[len]; // for(int i = 0; i < len; i++){ // editorOptions_asString[i] = editorOptions_asType[i].displayName; // } // // // //fill maps // for(NBTType type : NBTType.values()){ // typesByID.put(type.id, type); // typesByClazz.put(type.tagClazz, type); // } // } // // public static Tag newInstance(String tagName, NBTType type){ // switch (type){ // case END: return new EndTag(); // case BYTE: return new ByteTag(tagName, (byte) 0); // case SHORT: return new ShortTag(tagName, (short) 0); // case INT: return new IntTag(tagName, 0); // case LONG: return new LongTag(tagName, 0L); // case FLOAT: return new FloatTag(tagName, 0f); // case DOUBLE: return new DoubleTag(tagName, 0.0); // case BYTE_ARRAY: return new ByteArrayTag(tagName, null); // case STRING: return new StringTag(tagName, ""); // case LIST: return new ListTag(tagName, new ArrayList<Tag>()); // case COMPOUND: return new CompoundTag(tagName, new ArrayList<Tag>()); // default: return null; // } // } // // } // // public static final Charset CHARSET = Charset.forName("UTF-8"); // // }
import com.protolambda.blocktopograph.nbt.convert.NBTConstants; import java.util.ArrayList;
package com.protolambda.blocktopograph.nbt.tags; public class ListTag extends Tag<ArrayList<Tag>> { private static final long serialVersionUID = -4765717626522070446L; public ListTag(String name, ArrayList<Tag> value) { super(name, value); } @Override
// Path: app/src/main/java/com/protolambda/blocktopograph/nbt/convert/NBTConstants.java // public class NBTConstants { // // public enum NBTType { // // END(0, EndTag.class, "EndTag"), // BYTE(1, ByteTag.class, "ByteTag"), // SHORT(2, ShortTag.class, "ShortTag"), // INT(3, IntTag.class, "IntTag"), // LONG(4, LongTag.class, "LongTag"), // FLOAT(5, FloatTag.class, "FloatTag"), // DOUBLE(6, DoubleTag.class, "DoubleTag"), // BYTE_ARRAY(7, ByteArrayTag.class, "ByteArrayTag"), // STRING(8, StringTag.class, "StringTag"), // LIST(9, ListTag.class, "ListTag"), // COMPOUND(10, CompoundTag.class, "CompoundTag"), // INT_ARRAY(11, IntArrayTag.class, "IntArrayTag"), // // //Is this one even used?!? Maybe used in mods? // SHORT_ARRAY(100, ShortArrayTag.class, "ShortArrayTag"); // // public final int id; // public final Class<? extends Tag> tagClazz; // public final String displayName; // // static public Map<Integer, NBTType> typesByID = new HashMap<>(); // static public Map<Class<? extends Tag>, NBTType> typesByClazz = new HashMap<>(); // // NBTType(int id, Class<? extends Tag> tagClazz, String displayName){ // this.id = id; // this.tagClazz = tagClazz; // this.displayName = displayName; // } // // //not all NBT types are meant to be created in an editor, the END tag for example. // public static String[] editorOptions_asString; // public static NBTType[] editorOptions_asType = new NBTType[]{ // BYTE, // SHORT, // INT, // LONG, // FLOAT, // DOUBLE, // BYTE_ARRAY, // STRING, // LIST, // COMPOUND, // INT_ARRAY, // SHORT_ARRAY // }; // // static { // // // int len = editorOptions_asType.length; // editorOptions_asString = new String[len]; // for(int i = 0; i < len; i++){ // editorOptions_asString[i] = editorOptions_asType[i].displayName; // } // // // //fill maps // for(NBTType type : NBTType.values()){ // typesByID.put(type.id, type); // typesByClazz.put(type.tagClazz, type); // } // } // // public static Tag newInstance(String tagName, NBTType type){ // switch (type){ // case END: return new EndTag(); // case BYTE: return new ByteTag(tagName, (byte) 0); // case SHORT: return new ShortTag(tagName, (short) 0); // case INT: return new IntTag(tagName, 0); // case LONG: return new LongTag(tagName, 0L); // case FLOAT: return new FloatTag(tagName, 0f); // case DOUBLE: return new DoubleTag(tagName, 0.0); // case BYTE_ARRAY: return new ByteArrayTag(tagName, null); // case STRING: return new StringTag(tagName, ""); // case LIST: return new ListTag(tagName, new ArrayList<Tag>()); // case COMPOUND: return new CompoundTag(tagName, new ArrayList<Tag>()); // default: return null; // } // } // // } // // public static final Charset CHARSET = Charset.forName("UTF-8"); // // } // Path: app/src/main/java/com/protolambda/blocktopograph/nbt/tags/ListTag.java import com.protolambda.blocktopograph.nbt.convert.NBTConstants; import java.util.ArrayList; package com.protolambda.blocktopograph.nbt.tags; public class ListTag extends Tag<ArrayList<Tag>> { private static final long serialVersionUID = -4765717626522070446L; public ListTag(String name, ArrayList<Tag> value) { super(name, value); } @Override
public NBTConstants.NBTType getType() {
protolambda/blocktopograph
app/src/main/java/com/protolambda/blocktopograph/map/marker/AbstractMarker.java
// Path: app/src/main/java/com/protolambda/blocktopograph/map/Dimension.java // public enum Dimension { // // OVERWORLD(0, "overworld", "Overworld", 16, 16, 128, 1, MapType.OVERWORLD_SATELLITE), // NETHER(1, "nether", "Nether", 16, 16, 128, 8, MapType.NETHER), // END(2, "end", "End", 16, 16, 128, 1, MapType.END_SATELLITE);//mcpe: SOON^TM /jk // // public final int id; // public final int chunkW, chunkL, chunkH; // public final int dimensionScale; // public final String dataName, name; // public final MapType defaultMapType; // // Dimension(int id, String dataName, String name, int chunkW, int chunkL, int chunkH, int dimensionScale, MapType defaultMapType){ // this.id = id; // this.dataName = dataName; // this.name = name; // this.chunkW = chunkW; // this.chunkL = chunkL; // this.chunkH = chunkH; // this.dimensionScale = dimensionScale; // this.defaultMapType = defaultMapType; // } // // private static Map<String, Dimension> dimensionMap = new HashMap<>(); // // static { // for(Dimension dimension : Dimension.values()){ // dimensionMap.put(dimension.dataName, dimension); // } // } // // public static Dimension getDimension(String dataName){ // if(dataName == null) return null; // return dimensionMap.get(dataName.toLowerCase()); // } // // public static Dimension getDimension(int id){ // for(Dimension dimension : values()){ // if(dimension.id == id) return dimension; // } // return null; // } // // } // // Path: app/src/main/java/com/protolambda/blocktopograph/util/NamedBitmapProvider.java // public interface NamedBitmapProvider { // // Bitmap getBitmap(); // // @NonNull // String getBitmapDisplayName(); // // @NonNull // String getBitmapDataName(); // // } // // Path: app/src/main/java/com/protolambda/blocktopograph/util/NamedBitmapProviderHandle.java // public interface NamedBitmapProviderHandle { // // @NonNull // NamedBitmapProvider getNamedBitmapProvider(); // // }
import android.content.Context; import android.support.annotation.NonNull; import android.widget.ImageView; import com.protolambda.blocktopograph.map.Dimension; import com.protolambda.blocktopograph.util.NamedBitmapProvider; import com.protolambda.blocktopograph.util.NamedBitmapProviderHandle; import com.protolambda.blocktopograph.util.math.Vector3;
package com.protolambda.blocktopograph.map.marker; public class AbstractMarker implements NamedBitmapProviderHandle { public final int x, y, z;
// Path: app/src/main/java/com/protolambda/blocktopograph/map/Dimension.java // public enum Dimension { // // OVERWORLD(0, "overworld", "Overworld", 16, 16, 128, 1, MapType.OVERWORLD_SATELLITE), // NETHER(1, "nether", "Nether", 16, 16, 128, 8, MapType.NETHER), // END(2, "end", "End", 16, 16, 128, 1, MapType.END_SATELLITE);//mcpe: SOON^TM /jk // // public final int id; // public final int chunkW, chunkL, chunkH; // public final int dimensionScale; // public final String dataName, name; // public final MapType defaultMapType; // // Dimension(int id, String dataName, String name, int chunkW, int chunkL, int chunkH, int dimensionScale, MapType defaultMapType){ // this.id = id; // this.dataName = dataName; // this.name = name; // this.chunkW = chunkW; // this.chunkL = chunkL; // this.chunkH = chunkH; // this.dimensionScale = dimensionScale; // this.defaultMapType = defaultMapType; // } // // private static Map<String, Dimension> dimensionMap = new HashMap<>(); // // static { // for(Dimension dimension : Dimension.values()){ // dimensionMap.put(dimension.dataName, dimension); // } // } // // public static Dimension getDimension(String dataName){ // if(dataName == null) return null; // return dimensionMap.get(dataName.toLowerCase()); // } // // public static Dimension getDimension(int id){ // for(Dimension dimension : values()){ // if(dimension.id == id) return dimension; // } // return null; // } // // } // // Path: app/src/main/java/com/protolambda/blocktopograph/util/NamedBitmapProvider.java // public interface NamedBitmapProvider { // // Bitmap getBitmap(); // // @NonNull // String getBitmapDisplayName(); // // @NonNull // String getBitmapDataName(); // // } // // Path: app/src/main/java/com/protolambda/blocktopograph/util/NamedBitmapProviderHandle.java // public interface NamedBitmapProviderHandle { // // @NonNull // NamedBitmapProvider getNamedBitmapProvider(); // // } // Path: app/src/main/java/com/protolambda/blocktopograph/map/marker/AbstractMarker.java import android.content.Context; import android.support.annotation.NonNull; import android.widget.ImageView; import com.protolambda.blocktopograph.map.Dimension; import com.protolambda.blocktopograph.util.NamedBitmapProvider; import com.protolambda.blocktopograph.util.NamedBitmapProviderHandle; import com.protolambda.blocktopograph.util.math.Vector3; package com.protolambda.blocktopograph.map.marker; public class AbstractMarker implements NamedBitmapProviderHandle { public final int x, y, z;
public final Dimension dimension;
protolambda/blocktopograph
app/src/main/java/com/protolambda/blocktopograph/map/marker/AbstractMarker.java
// Path: app/src/main/java/com/protolambda/blocktopograph/map/Dimension.java // public enum Dimension { // // OVERWORLD(0, "overworld", "Overworld", 16, 16, 128, 1, MapType.OVERWORLD_SATELLITE), // NETHER(1, "nether", "Nether", 16, 16, 128, 8, MapType.NETHER), // END(2, "end", "End", 16, 16, 128, 1, MapType.END_SATELLITE);//mcpe: SOON^TM /jk // // public final int id; // public final int chunkW, chunkL, chunkH; // public final int dimensionScale; // public final String dataName, name; // public final MapType defaultMapType; // // Dimension(int id, String dataName, String name, int chunkW, int chunkL, int chunkH, int dimensionScale, MapType defaultMapType){ // this.id = id; // this.dataName = dataName; // this.name = name; // this.chunkW = chunkW; // this.chunkL = chunkL; // this.chunkH = chunkH; // this.dimensionScale = dimensionScale; // this.defaultMapType = defaultMapType; // } // // private static Map<String, Dimension> dimensionMap = new HashMap<>(); // // static { // for(Dimension dimension : Dimension.values()){ // dimensionMap.put(dimension.dataName, dimension); // } // } // // public static Dimension getDimension(String dataName){ // if(dataName == null) return null; // return dimensionMap.get(dataName.toLowerCase()); // } // // public static Dimension getDimension(int id){ // for(Dimension dimension : values()){ // if(dimension.id == id) return dimension; // } // return null; // } // // } // // Path: app/src/main/java/com/protolambda/blocktopograph/util/NamedBitmapProvider.java // public interface NamedBitmapProvider { // // Bitmap getBitmap(); // // @NonNull // String getBitmapDisplayName(); // // @NonNull // String getBitmapDataName(); // // } // // Path: app/src/main/java/com/protolambda/blocktopograph/util/NamedBitmapProviderHandle.java // public interface NamedBitmapProviderHandle { // // @NonNull // NamedBitmapProvider getNamedBitmapProvider(); // // }
import android.content.Context; import android.support.annotation.NonNull; import android.widget.ImageView; import com.protolambda.blocktopograph.map.Dimension; import com.protolambda.blocktopograph.util.NamedBitmapProvider; import com.protolambda.blocktopograph.util.NamedBitmapProviderHandle; import com.protolambda.blocktopograph.util.math.Vector3;
package com.protolambda.blocktopograph.map.marker; public class AbstractMarker implements NamedBitmapProviderHandle { public final int x, y, z; public final Dimension dimension;
// Path: app/src/main/java/com/protolambda/blocktopograph/map/Dimension.java // public enum Dimension { // // OVERWORLD(0, "overworld", "Overworld", 16, 16, 128, 1, MapType.OVERWORLD_SATELLITE), // NETHER(1, "nether", "Nether", 16, 16, 128, 8, MapType.NETHER), // END(2, "end", "End", 16, 16, 128, 1, MapType.END_SATELLITE);//mcpe: SOON^TM /jk // // public final int id; // public final int chunkW, chunkL, chunkH; // public final int dimensionScale; // public final String dataName, name; // public final MapType defaultMapType; // // Dimension(int id, String dataName, String name, int chunkW, int chunkL, int chunkH, int dimensionScale, MapType defaultMapType){ // this.id = id; // this.dataName = dataName; // this.name = name; // this.chunkW = chunkW; // this.chunkL = chunkL; // this.chunkH = chunkH; // this.dimensionScale = dimensionScale; // this.defaultMapType = defaultMapType; // } // // private static Map<String, Dimension> dimensionMap = new HashMap<>(); // // static { // for(Dimension dimension : Dimension.values()){ // dimensionMap.put(dimension.dataName, dimension); // } // } // // public static Dimension getDimension(String dataName){ // if(dataName == null) return null; // return dimensionMap.get(dataName.toLowerCase()); // } // // public static Dimension getDimension(int id){ // for(Dimension dimension : values()){ // if(dimension.id == id) return dimension; // } // return null; // } // // } // // Path: app/src/main/java/com/protolambda/blocktopograph/util/NamedBitmapProvider.java // public interface NamedBitmapProvider { // // Bitmap getBitmap(); // // @NonNull // String getBitmapDisplayName(); // // @NonNull // String getBitmapDataName(); // // } // // Path: app/src/main/java/com/protolambda/blocktopograph/util/NamedBitmapProviderHandle.java // public interface NamedBitmapProviderHandle { // // @NonNull // NamedBitmapProvider getNamedBitmapProvider(); // // } // Path: app/src/main/java/com/protolambda/blocktopograph/map/marker/AbstractMarker.java import android.content.Context; import android.support.annotation.NonNull; import android.widget.ImageView; import com.protolambda.blocktopograph.map.Dimension; import com.protolambda.blocktopograph.util.NamedBitmapProvider; import com.protolambda.blocktopograph.util.NamedBitmapProviderHandle; import com.protolambda.blocktopograph.util.math.Vector3; package com.protolambda.blocktopograph.map.marker; public class AbstractMarker implements NamedBitmapProviderHandle { public final int x, y, z; public final Dimension dimension;
public final NamedBitmapProvider namedBitmapProvider;
protolambda/blocktopograph
app/src/main/java/com/protolambda/blocktopograph/WorldData.java
// Path: app/src/main/java/com/protolambda/blocktopograph/map/Dimension.java // public enum Dimension { // // OVERWORLD(0, "overworld", "Overworld", 16, 16, 128, 1, MapType.OVERWORLD_SATELLITE), // NETHER(1, "nether", "Nether", 16, 16, 128, 8, MapType.NETHER), // END(2, "end", "End", 16, 16, 128, 1, MapType.END_SATELLITE);//mcpe: SOON^TM /jk // // public final int id; // public final int chunkW, chunkL, chunkH; // public final int dimensionScale; // public final String dataName, name; // public final MapType defaultMapType; // // Dimension(int id, String dataName, String name, int chunkW, int chunkL, int chunkH, int dimensionScale, MapType defaultMapType){ // this.id = id; // this.dataName = dataName; // this.name = name; // this.chunkW = chunkW; // this.chunkL = chunkL; // this.chunkH = chunkH; // this.dimensionScale = dimensionScale; // this.defaultMapType = defaultMapType; // } // // private static Map<String, Dimension> dimensionMap = new HashMap<>(); // // static { // for(Dimension dimension : Dimension.values()){ // dimensionMap.put(dimension.dataName, dimension); // } // } // // public static Dimension getDimension(String dataName){ // if(dataName == null) return null; // return dimensionMap.get(dataName.toLowerCase()); // } // // public static Dimension getDimension(int id){ // for(Dimension dimension : values()){ // if(dimension.id == id) return dimension; // } // return null; // } // // }
import android.annotation.SuppressLint; import com.protolambda.blocktopograph.chunk.ChunkTag; import com.protolambda.blocktopograph.map.Dimension; import com.litl.leveldb.Iterator; import com.litl.leveldb.DB; import java.io.File; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List;
char[] hexChars = new char[(end-start) * 2]; for ( int j = start; j < end; j++ ) { int v = bytes[j] & 0xFF; hexChars[(j-start) * 2] = hexArray[v >>> 4]; hexChars[(j-start) * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } //close db to make it available for other apps (Minecraft itself!) public void closeDB() throws WorldDBException { if(this.db == null) throw new WorldDBException("DB is null!!! (db is not loaded probably)"); try { this.db.close(); } catch (Exception e){ //db was already closed (probably) e.printStackTrace(); } } /** WARNING: DELETES WORLD !!! */ public void destroy() throws WorldDBException { if(this.db == null) throw new WorldDBException("DB is null!!! (db is not loaded probably)"); this.db.close(); this.db.destroy(); this.db = null; }
// Path: app/src/main/java/com/protolambda/blocktopograph/map/Dimension.java // public enum Dimension { // // OVERWORLD(0, "overworld", "Overworld", 16, 16, 128, 1, MapType.OVERWORLD_SATELLITE), // NETHER(1, "nether", "Nether", 16, 16, 128, 8, MapType.NETHER), // END(2, "end", "End", 16, 16, 128, 1, MapType.END_SATELLITE);//mcpe: SOON^TM /jk // // public final int id; // public final int chunkW, chunkL, chunkH; // public final int dimensionScale; // public final String dataName, name; // public final MapType defaultMapType; // // Dimension(int id, String dataName, String name, int chunkW, int chunkL, int chunkH, int dimensionScale, MapType defaultMapType){ // this.id = id; // this.dataName = dataName; // this.name = name; // this.chunkW = chunkW; // this.chunkL = chunkL; // this.chunkH = chunkH; // this.dimensionScale = dimensionScale; // this.defaultMapType = defaultMapType; // } // // private static Map<String, Dimension> dimensionMap = new HashMap<>(); // // static { // for(Dimension dimension : Dimension.values()){ // dimensionMap.put(dimension.dataName, dimension); // } // } // // public static Dimension getDimension(String dataName){ // if(dataName == null) return null; // return dimensionMap.get(dataName.toLowerCase()); // } // // public static Dimension getDimension(int id){ // for(Dimension dimension : values()){ // if(dimension.id == id) return dimension; // } // return null; // } // // } // Path: app/src/main/java/com/protolambda/blocktopograph/WorldData.java import android.annotation.SuppressLint; import com.protolambda.blocktopograph.chunk.ChunkTag; import com.protolambda.blocktopograph.map.Dimension; import com.litl.leveldb.Iterator; import com.litl.leveldb.DB; import java.io.File; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; char[] hexChars = new char[(end-start) * 2]; for ( int j = start; j < end; j++ ) { int v = bytes[j] & 0xFF; hexChars[(j-start) * 2] = hexArray[v >>> 4]; hexChars[(j-start) * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } //close db to make it available for other apps (Minecraft itself!) public void closeDB() throws WorldDBException { if(this.db == null) throw new WorldDBException("DB is null!!! (db is not loaded probably)"); try { this.db.close(); } catch (Exception e){ //db was already closed (probably) e.printStackTrace(); } } /** WARNING: DELETES WORLD !!! */ public void destroy() throws WorldDBException { if(this.db == null) throw new WorldDBException("DB is null!!! (db is not loaded probably)"); this.db.close(); this.db.destroy(); this.db = null; }
public byte[] getChunkData(int x, int z, ChunkTag type, Dimension dimension, byte subChunk, boolean asSubChunk) throws WorldDBException, WorldDBLoadException {
pierre/hfind
src/main/java/com/ning/hfind/primary/Primary.java
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // }
import com.ning.hfind.FileAttributes;
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; interface Primary { public static final Primary ALWAYS_MATCH = new Primary() { @Override
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // } // Path: src/main/java/com/ning/hfind/primary/Primary.java import com.ning.hfind.FileAttributes; /* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; interface Primary { public static final Primary ALWAYS_MATCH = new Primary() { @Override
public boolean passesFilter(FileAttributes attributes)
pierre/hfind
src/main/java/com/ning/hfind/primary/AndOperand.java
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // }
import com.ning.hfind.FileAttributes;
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class AndOperand implements Operand { @Override
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // } // Path: src/main/java/com/ning/hfind/primary/AndOperand.java import com.ning.hfind.FileAttributes; /* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class AndOperand implements Operand { @Override
public boolean evaluateOperand(Primary primaryLeft, Primary primaryRight, FileAttributes fileAttributes)
pierre/hfind
src/main/java/com/ning/hfind/primary/NamePrimary.java
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // }
import com.ning.hfind.FileAttributes; import org.apache.commons.lang.StringUtils; import org.apache.oro.text.GlobCompiler; import org.apache.oro.text.regex.MalformedPatternException; import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.PatternMatcher; import org.apache.oro.text.regex.Perl5Matcher;
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class NamePrimary implements Primary { private Pattern pattern; PatternMatcher matcher = new Perl5Matcher(); public NamePrimary(String namePattern) throws MalformedPatternException { GlobCompiler compiler = new GlobCompiler(); this.pattern = compiler.compile(namePattern); } @Override
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // } // Path: src/main/java/com/ning/hfind/primary/NamePrimary.java import com.ning.hfind.FileAttributes; import org.apache.commons.lang.StringUtils; import org.apache.oro.text.GlobCompiler; import org.apache.oro.text.regex.MalformedPatternException; import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.PatternMatcher; import org.apache.oro.text.regex.Perl5Matcher; /* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class NamePrimary implements Primary { private Pattern pattern; PatternMatcher matcher = new Perl5Matcher(); public NamePrimary(String namePattern) throws MalformedPatternException { GlobCompiler compiler = new GlobCompiler(); this.pattern = compiler.compile(namePattern); } @Override
public boolean passesFilter(FileAttributes attributes)
pierre/hfind
src/main/java/com/ning/hfind/Printer.java
// Path: src/main/java/com/ning/hfind/primary/Expression.java // public class Expression // { // private final Expression expressionLeft; // private final Expression expressionRight; // // private final Primary primaryLeft; // private final Primary primaryRight; // // private final Operand operand; // // public static final Expression TRUE = new Expression(Primary.ALWAYS_MATCH, Primary.ALWAYS_MATCH, new AndOperand()); // // /** // * Base expression // * // * @param primaryLeft primary on the left of the operand (higher precedence) // * @param primaryRight primary on the right of the operand // * @param operand operand evaluating primaryLeft OP primaryRight // */ // public Expression( // Primary primaryLeft, // Primary primaryRight, // Operand operand // ) // { // this.expressionLeft = null; // this.expressionRight = null; // // this.primaryLeft = primaryLeft; // this.operand = operand; // this.primaryRight = primaryRight; // } // // public Expression( // Primary primaryLeft, // Expression expressionRight, // Operand operand // ) // { // this.expressionLeft = null; // this.primaryRight = null; // // this.primaryLeft = primaryLeft; // this.operand = operand; // this.expressionRight = expressionRight; // } // // public Expression(Expression expressionLeft, Expression expressionRight, Operand operand) // { // this.primaryLeft = null; // this.primaryRight = null; // // this.expressionLeft = expressionLeft; // this.operand = operand; // this.expressionRight = expressionRight; // } // // public void run(String path, int depth, PrinterConfig config) throws IOException // { // FsItem listing = new HdfsItem(HdfsAccess.get(), path, depth); // Printer printer = new Printer(listing, this, config); // // printer.run(); // } // // @Override // public String toString() // { // if (expressionLeft != null && expressionRight != null) { // return String.format("(%s) %s (%s)", expressionLeft, operand, expressionRight); // } // else if (primaryLeft != null && primaryRight != null) { // return String.format("%s %s %s", primaryLeft, operand, primaryRight); // } // else if (primaryLeft != null && expressionRight != null) { // return String.format("%s %s (%s)", primaryLeft, operand, expressionRight); // } // else { // throw new IllegalStateException(String.format("Malformatted expression: %s", toString())); // } // } // // public boolean evaluate(FileAttributes fileAttributes) // { // if (expressionLeft != null && expressionRight != null) { // return operand.evaluateOperand(expressionLeft, expressionRight, fileAttributes); // } // else if (primaryLeft != null && primaryRight != null) { // return operand.evaluateOperand(primaryLeft, primaryRight, fileAttributes); // } // else if (primaryLeft != null && expressionRight != null) { // return operand.evaluateOperand(primaryLeft, expressionRight, fileAttributes); // } // else { // throw new IllegalStateException(String.format("Malformatted expression: %s", toString())); // } // } // }
import com.ning.hfind.primary.Expression;
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind; public class Printer { private final FsItem topLevelItem;
// Path: src/main/java/com/ning/hfind/primary/Expression.java // public class Expression // { // private final Expression expressionLeft; // private final Expression expressionRight; // // private final Primary primaryLeft; // private final Primary primaryRight; // // private final Operand operand; // // public static final Expression TRUE = new Expression(Primary.ALWAYS_MATCH, Primary.ALWAYS_MATCH, new AndOperand()); // // /** // * Base expression // * // * @param primaryLeft primary on the left of the operand (higher precedence) // * @param primaryRight primary on the right of the operand // * @param operand operand evaluating primaryLeft OP primaryRight // */ // public Expression( // Primary primaryLeft, // Primary primaryRight, // Operand operand // ) // { // this.expressionLeft = null; // this.expressionRight = null; // // this.primaryLeft = primaryLeft; // this.operand = operand; // this.primaryRight = primaryRight; // } // // public Expression( // Primary primaryLeft, // Expression expressionRight, // Operand operand // ) // { // this.expressionLeft = null; // this.primaryRight = null; // // this.primaryLeft = primaryLeft; // this.operand = operand; // this.expressionRight = expressionRight; // } // // public Expression(Expression expressionLeft, Expression expressionRight, Operand operand) // { // this.primaryLeft = null; // this.primaryRight = null; // // this.expressionLeft = expressionLeft; // this.operand = operand; // this.expressionRight = expressionRight; // } // // public void run(String path, int depth, PrinterConfig config) throws IOException // { // FsItem listing = new HdfsItem(HdfsAccess.get(), path, depth); // Printer printer = new Printer(listing, this, config); // // printer.run(); // } // // @Override // public String toString() // { // if (expressionLeft != null && expressionRight != null) { // return String.format("(%s) %s (%s)", expressionLeft, operand, expressionRight); // } // else if (primaryLeft != null && primaryRight != null) { // return String.format("%s %s %s", primaryLeft, operand, primaryRight); // } // else if (primaryLeft != null && expressionRight != null) { // return String.format("%s %s (%s)", primaryLeft, operand, expressionRight); // } // else { // throw new IllegalStateException(String.format("Malformatted expression: %s", toString())); // } // } // // public boolean evaluate(FileAttributes fileAttributes) // { // if (expressionLeft != null && expressionRight != null) { // return operand.evaluateOperand(expressionLeft, expressionRight, fileAttributes); // } // else if (primaryLeft != null && primaryRight != null) { // return operand.evaluateOperand(primaryLeft, primaryRight, fileAttributes); // } // else if (primaryLeft != null && expressionRight != null) { // return operand.evaluateOperand(primaryLeft, expressionRight, fileAttributes); // } // else { // throw new IllegalStateException(String.format("Malformatted expression: %s", toString())); // } // } // } // Path: src/main/java/com/ning/hfind/Printer.java import com.ning.hfind.primary.Expression; /* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind; public class Printer { private final FsItem topLevelItem;
private final Expression expression;
pierre/hfind
src/main/java/com/ning/hfind/primary/NoUserPrimary.java
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // }
import com.ning.hfind.FileAttributes;
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class NoUserPrimary implements Primary { @Override
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // } // Path: src/main/java/com/ning/hfind/primary/NoUserPrimary.java import com.ning.hfind.FileAttributes; /* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class NoUserPrimary implements Primary { @Override
public boolean passesFilter(FileAttributes attributes)
pierre/hfind
src/main/java/com/ning/hfind/primary/AtimePrimary.java
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // }
import com.ning.hfind.FileAttributes; import org.joda.time.DateTime;
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class AtimePrimary implements Primary { private final int atime; private final OperandModifier operandModifier; public AtimePrimary(String atime) { operandModifier = new OperandModifier(atime); this.atime = operandModifier.getSanitizedArgument(); } @Override
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // } // Path: src/main/java/com/ning/hfind/primary/AtimePrimary.java import com.ning.hfind.FileAttributes; import org.joda.time.DateTime; /* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class AtimePrimary implements Primary { private final int atime; private final OperandModifier operandModifier; public AtimePrimary(String atime) { operandModifier = new OperandModifier(atime); this.atime = operandModifier.getSanitizedArgument(); } @Override
public boolean passesFilter(FileAttributes attributes)
pierre/hfind
src/main/java/com/ning/hfind/primary/Operand.java
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // }
import com.ning.hfind.FileAttributes;
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; interface Operand {
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // } // Path: src/main/java/com/ning/hfind/primary/Operand.java import com.ning.hfind.FileAttributes; /* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; interface Operand {
public boolean evaluateOperand(Primary primaryLeft, Primary primaryRight, FileAttributes fileAttributes);
pierre/hfind
src/test/java/com/ning/hfind/TestPrinter.java
// Path: src/main/java/com/ning/hfind/primary/Expression.java // public class Expression // { // private final Expression expressionLeft; // private final Expression expressionRight; // // private final Primary primaryLeft; // private final Primary primaryRight; // // private final Operand operand; // // public static final Expression TRUE = new Expression(Primary.ALWAYS_MATCH, Primary.ALWAYS_MATCH, new AndOperand()); // // /** // * Base expression // * // * @param primaryLeft primary on the left of the operand (higher precedence) // * @param primaryRight primary on the right of the operand // * @param operand operand evaluating primaryLeft OP primaryRight // */ // public Expression( // Primary primaryLeft, // Primary primaryRight, // Operand operand // ) // { // this.expressionLeft = null; // this.expressionRight = null; // // this.primaryLeft = primaryLeft; // this.operand = operand; // this.primaryRight = primaryRight; // } // // public Expression( // Primary primaryLeft, // Expression expressionRight, // Operand operand // ) // { // this.expressionLeft = null; // this.primaryRight = null; // // this.primaryLeft = primaryLeft; // this.operand = operand; // this.expressionRight = expressionRight; // } // // public Expression(Expression expressionLeft, Expression expressionRight, Operand operand) // { // this.primaryLeft = null; // this.primaryRight = null; // // this.expressionLeft = expressionLeft; // this.operand = operand; // this.expressionRight = expressionRight; // } // // public void run(String path, int depth, PrinterConfig config) throws IOException // { // FsItem listing = new HdfsItem(HdfsAccess.get(), path, depth); // Printer printer = new Printer(listing, this, config); // // printer.run(); // } // // @Override // public String toString() // { // if (expressionLeft != null && expressionRight != null) { // return String.format("(%s) %s (%s)", expressionLeft, operand, expressionRight); // } // else if (primaryLeft != null && primaryRight != null) { // return String.format("%s %s %s", primaryLeft, operand, primaryRight); // } // else if (primaryLeft != null && expressionRight != null) { // return String.format("%s %s (%s)", primaryLeft, operand, expressionRight); // } // else { // throw new IllegalStateException(String.format("Malformatted expression: %s", toString())); // } // } // // public boolean evaluate(FileAttributes fileAttributes) // { // if (expressionLeft != null && expressionRight != null) { // return operand.evaluateOperand(expressionLeft, expressionRight, fileAttributes); // } // else if (primaryLeft != null && primaryRight != null) { // return operand.evaluateOperand(primaryLeft, primaryRight, fileAttributes); // } // else if (primaryLeft != null && expressionRight != null) { // return operand.evaluateOperand(primaryLeft, expressionRight, fileAttributes); // } // else { // throw new IllegalStateException(String.format("Malformatted expression: %s", toString())); // } // } // }
import com.ning.hfind.primary.Expression; import org.testng.Assert; import org.testng.annotations.Test;
package com.ning.hfind; public class TestPrinter { private static final Character NULL_CHARACTER = '\u0000'; @Test(groups = "fast") public void testDeleteIsOffByDefault() throws Exception { PrinterConfig config = new PrinterConfig(); Assert.assertFalse(config.deleteMode()); } @Test(groups = "fast") public void testPrint0() throws Exception { PrinterConfig config = new PrinterConfig(); config.setEndLineWithNull(true); testOneItem("/user/pierre/mouraf.org/", config, NULL_CHARACTER); testOneItem(String.format("/user/pierre/mouraf.org/%s", NULL_CHARACTER), config, NULL_CHARACTER); testOneItem(String.format("/user/ pierre %s /mouraf.org/", NULL_CHARACTER), config, NULL_CHARACTER); } private void testOneItem(String pathName, PrinterConfig config, Character lastCharacter) { FsItem item = new StubFsItem(pathName);
// Path: src/main/java/com/ning/hfind/primary/Expression.java // public class Expression // { // private final Expression expressionLeft; // private final Expression expressionRight; // // private final Primary primaryLeft; // private final Primary primaryRight; // // private final Operand operand; // // public static final Expression TRUE = new Expression(Primary.ALWAYS_MATCH, Primary.ALWAYS_MATCH, new AndOperand()); // // /** // * Base expression // * // * @param primaryLeft primary on the left of the operand (higher precedence) // * @param primaryRight primary on the right of the operand // * @param operand operand evaluating primaryLeft OP primaryRight // */ // public Expression( // Primary primaryLeft, // Primary primaryRight, // Operand operand // ) // { // this.expressionLeft = null; // this.expressionRight = null; // // this.primaryLeft = primaryLeft; // this.operand = operand; // this.primaryRight = primaryRight; // } // // public Expression( // Primary primaryLeft, // Expression expressionRight, // Operand operand // ) // { // this.expressionLeft = null; // this.primaryRight = null; // // this.primaryLeft = primaryLeft; // this.operand = operand; // this.expressionRight = expressionRight; // } // // public Expression(Expression expressionLeft, Expression expressionRight, Operand operand) // { // this.primaryLeft = null; // this.primaryRight = null; // // this.expressionLeft = expressionLeft; // this.operand = operand; // this.expressionRight = expressionRight; // } // // public void run(String path, int depth, PrinterConfig config) throws IOException // { // FsItem listing = new HdfsItem(HdfsAccess.get(), path, depth); // Printer printer = new Printer(listing, this, config); // // printer.run(); // } // // @Override // public String toString() // { // if (expressionLeft != null && expressionRight != null) { // return String.format("(%s) %s (%s)", expressionLeft, operand, expressionRight); // } // else if (primaryLeft != null && primaryRight != null) { // return String.format("%s %s %s", primaryLeft, operand, primaryRight); // } // else if (primaryLeft != null && expressionRight != null) { // return String.format("%s %s (%s)", primaryLeft, operand, expressionRight); // } // else { // throw new IllegalStateException(String.format("Malformatted expression: %s", toString())); // } // } // // public boolean evaluate(FileAttributes fileAttributes) // { // if (expressionLeft != null && expressionRight != null) { // return operand.evaluateOperand(expressionLeft, expressionRight, fileAttributes); // } // else if (primaryLeft != null && primaryRight != null) { // return operand.evaluateOperand(primaryLeft, primaryRight, fileAttributes); // } // else if (primaryLeft != null && expressionRight != null) { // return operand.evaluateOperand(primaryLeft, expressionRight, fileAttributes); // } // else { // throw new IllegalStateException(String.format("Malformatted expression: %s", toString())); // } // } // } // Path: src/test/java/com/ning/hfind/TestPrinter.java import com.ning.hfind.primary.Expression; import org.testng.Assert; import org.testng.annotations.Test; package com.ning.hfind; public class TestPrinter { private static final Character NULL_CHARACTER = '\u0000'; @Test(groups = "fast") public void testDeleteIsOffByDefault() throws Exception { PrinterConfig config = new PrinterConfig(); Assert.assertFalse(config.deleteMode()); } @Test(groups = "fast") public void testPrint0() throws Exception { PrinterConfig config = new PrinterConfig(); config.setEndLineWithNull(true); testOneItem("/user/pierre/mouraf.org/", config, NULL_CHARACTER); testOneItem(String.format("/user/pierre/mouraf.org/%s", NULL_CHARACTER), config, NULL_CHARACTER); testOneItem(String.format("/user/ pierre %s /mouraf.org/", NULL_CHARACTER), config, NULL_CHARACTER); } private void testOneItem(String pathName, PrinterConfig config, Character lastCharacter) { FsItem item = new StubFsItem(pathName);
Printer printer = new Printer(item, Expression.TRUE, config);
pierre/hfind
src/main/java/com/ning/hfind/primary/MtimePrimary.java
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // }
import com.ning.hfind.FileAttributes; import org.joda.time.DateTime;
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class MtimePrimary implements Primary { private final int mtime; private final OperandModifier operandModifier; public MtimePrimary(String mtime) { operandModifier = new OperandModifier(mtime); this.mtime = operandModifier.getSanitizedArgument(); } @Override
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // } // Path: src/main/java/com/ning/hfind/primary/MtimePrimary.java import com.ning.hfind.FileAttributes; import org.joda.time.DateTime; /* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class MtimePrimary implements Primary { private final int mtime; private final OperandModifier operandModifier; public MtimePrimary(String mtime) { operandModifier = new OperandModifier(mtime); this.mtime = operandModifier.getSanitizedArgument(); } @Override
public boolean passesFilter(FileAttributes attributes)
pierre/hfind
src/main/java/com/ning/hfind/primary/ExpressionFactory.java
// Path: src/main/java/com/ning/hfind/util/PushbackIterator.java // public class PushbackIterator<T> implements Iterator<T> // { // private final Iterator<T> delegate; // private T last = null; // private boolean pushedBack; // // public PushbackIterator(Iterator<T> delegate) // { // this.delegate = delegate; // } // // public void pushBack() // { // pushedBack = true; // } // // @Override // public boolean hasNext() // { // return pushedBack || delegate.hasNext(); // } // // @Override // public T next() // { // if (pushedBack) { // pushedBack = false; // // return last; // } // // last = delegate.next(); // // return last; // } // // @Override // public void remove() // { // throw new UnsupportedOperationException(); // } // }
import com.ning.hfind.util.PushbackIterator; import org.apache.commons.cli.Option; import org.apache.oro.text.regex.MalformedPatternException; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator;
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; public class ExpressionFactory {
// Path: src/main/java/com/ning/hfind/util/PushbackIterator.java // public class PushbackIterator<T> implements Iterator<T> // { // private final Iterator<T> delegate; // private T last = null; // private boolean pushedBack; // // public PushbackIterator(Iterator<T> delegate) // { // this.delegate = delegate; // } // // public void pushBack() // { // pushedBack = true; // } // // @Override // public boolean hasNext() // { // return pushedBack || delegate.hasNext(); // } // // @Override // public T next() // { // if (pushedBack) { // pushedBack = false; // // return last; // } // // last = delegate.next(); // // return last; // } // // @Override // public void remove() // { // throw new UnsupportedOperationException(); // } // } // Path: src/main/java/com/ning/hfind/primary/ExpressionFactory.java import com.ning.hfind.util.PushbackIterator; import org.apache.commons.cli.Option; import org.apache.oro.text.regex.MalformedPatternException; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; /* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; public class ExpressionFactory {
public static Expression buildExpressionFromCommandLine(PushbackIterator<Option> iterator)
pierre/hfind
src/test/java/com/ning/hfind/primary/TestNamePrimary.java
// Path: src/test/java/com/ning/hfind/StubFileAttributes.java // public class StubFileAttributes implements FileAttributes // { // private String path; // // @Override // public ReadableDateTime getAccessDate() // { // return null; // } // // @Override // public ReadableDateTime getModificationDate() // { // return null; // } // // @Override // public boolean isDirectory() // { // return false; // } // // @Override // public long getLength() // { // return 0; // } // // @Override // public long getBlockSize() // { // return 0; // } // // @Override // public int getReplicationCount() // { // return 0; // } // // @Override // public String getOwner() // { // return null; // } // // @Override // public String getGroup() // { // return null; // } // // @Override // public String getPath() // { // return path; // } // // public void setPath(String path) // { // this.path = path; // } // // @Override // public boolean isReadableBy(String user, Collection<String> groups) // { // return false; // } // // @Override // public boolean isWritableBy(String user, Collection<String> groups) // { // return false; // } // // @Override // public boolean isExecutableBy(String user, Collection<String> groups) // { // return false; // } // // @Override // public FileStatus[] children() throws IOException // { // return new FileStatus[0]; // } // // @Override // public int compareTo(FileAttributes fileAttributes) // { // return 0; // } // }
import com.ning.hfind.StubFileAttributes; import org.apache.oro.text.regex.MalformedPatternException; import org.testng.Assert; import org.testng.annotations.Test;
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; public class TestNamePrimary { @Test(groups = "fast") public void testPatternMatching() throws Exception { Assert.assertTrue(testOneMatch("pierre*", "pierreR0cks")); Assert.assertTrue(testOneMatch("*pierre*", "pierreR0cks")); Assert.assertTrue(testOneMatch("*pierre*", "noReallYpierreR0cks")); Assert.assertTrue(testOneMatch("*.thrift", "my.thrift")); Assert.assertFalse(testOneMatch("*.thrift", "mythrift")); Assert.assertTrue(testOneMatch("[mM][yY][fF][iI][lL][eE]*", "mYfIle")); } private boolean testOneMatch(String patternToTest, String path) throws MalformedPatternException { Primary namePrimary = new NamePrimary(patternToTest);
// Path: src/test/java/com/ning/hfind/StubFileAttributes.java // public class StubFileAttributes implements FileAttributes // { // private String path; // // @Override // public ReadableDateTime getAccessDate() // { // return null; // } // // @Override // public ReadableDateTime getModificationDate() // { // return null; // } // // @Override // public boolean isDirectory() // { // return false; // } // // @Override // public long getLength() // { // return 0; // } // // @Override // public long getBlockSize() // { // return 0; // } // // @Override // public int getReplicationCount() // { // return 0; // } // // @Override // public String getOwner() // { // return null; // } // // @Override // public String getGroup() // { // return null; // } // // @Override // public String getPath() // { // return path; // } // // public void setPath(String path) // { // this.path = path; // } // // @Override // public boolean isReadableBy(String user, Collection<String> groups) // { // return false; // } // // @Override // public boolean isWritableBy(String user, Collection<String> groups) // { // return false; // } // // @Override // public boolean isExecutableBy(String user, Collection<String> groups) // { // return false; // } // // @Override // public FileStatus[] children() throws IOException // { // return new FileStatus[0]; // } // // @Override // public int compareTo(FileAttributes fileAttributes) // { // return 0; // } // } // Path: src/test/java/com/ning/hfind/primary/TestNamePrimary.java import com.ning.hfind.StubFileAttributes; import org.apache.oro.text.regex.MalformedPatternException; import org.testng.Assert; import org.testng.annotations.Test; /* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; public class TestNamePrimary { @Test(groups = "fast") public void testPatternMatching() throws Exception { Assert.assertTrue(testOneMatch("pierre*", "pierreR0cks")); Assert.assertTrue(testOneMatch("*pierre*", "pierreR0cks")); Assert.assertTrue(testOneMatch("*pierre*", "noReallYpierreR0cks")); Assert.assertTrue(testOneMatch("*.thrift", "my.thrift")); Assert.assertFalse(testOneMatch("*.thrift", "mythrift")); Assert.assertTrue(testOneMatch("[mM][yY][fF][iI][lL][eE]*", "mYfIle")); } private boolean testOneMatch(String patternToTest, String path) throws MalformedPatternException { Primary namePrimary = new NamePrimary(patternToTest);
StubFileAttributes fileAttributes = new StubFileAttributes();
pierre/hfind
src/main/java/com/ning/hfind/HdfsAccess.java
// Path: src/main/java/com/ning/hfind/config/HdfsConfig.java // public class HdfsConfig // { // private final Configuration hdfsConfig; // // public HdfsConfig() // { // this.hdfsConfig = configureHDFSAccess(); // } // // private Configuration configureHDFSAccess() // { // HFindConfig hfindConfig = new ConfigurationObjectFactory(System.getProperties()).build(HFindConfig.class); // Configuration hdfsConfig = new Configuration(); // // hdfsConfig.set("fs.default.name", hfindConfig.getNamenodeUrl()); // hdfsConfig.set("hadoop.job.ugi", hfindConfig.getHadoopUgi()); // // // Set the URI schema to file:///, this will make FileSystem.get return a LocalFileSystem instance // if (hfindConfig.localMode()) { // hdfsConfig.set("fs.default.name", "file:///"); // } // // return hdfsConfig; // } // // public Configuration getConfiguration() // { // return hdfsConfig; // } // }
import com.ning.hfind.config.HdfsConfig; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import java.io.IOException;
package com.ning.hfind; public class HdfsAccess { private static HdfsAccess singletonHdfsAccess;
// Path: src/main/java/com/ning/hfind/config/HdfsConfig.java // public class HdfsConfig // { // private final Configuration hdfsConfig; // // public HdfsConfig() // { // this.hdfsConfig = configureHDFSAccess(); // } // // private Configuration configureHDFSAccess() // { // HFindConfig hfindConfig = new ConfigurationObjectFactory(System.getProperties()).build(HFindConfig.class); // Configuration hdfsConfig = new Configuration(); // // hdfsConfig.set("fs.default.name", hfindConfig.getNamenodeUrl()); // hdfsConfig.set("hadoop.job.ugi", hfindConfig.getHadoopUgi()); // // // Set the URI schema to file:///, this will make FileSystem.get return a LocalFileSystem instance // if (hfindConfig.localMode()) { // hdfsConfig.set("fs.default.name", "file:///"); // } // // return hdfsConfig; // } // // public Configuration getConfiguration() // { // return hdfsConfig; // } // } // Path: src/main/java/com/ning/hfind/HdfsAccess.java import com.ning.hfind.config.HdfsConfig; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import java.io.IOException; package com.ning.hfind; public class HdfsAccess { private static HdfsAccess singletonHdfsAccess;
private final HdfsConfig hdfsConfig;
pierre/hfind
src/main/java/com/ning/hfind/primary/EmptyPrimary.java
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // }
import com.ning.hfind.FileAttributes; import java.io.IOException;
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class EmptyPrimary implements Primary { @Override
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // } // Path: src/main/java/com/ning/hfind/primary/EmptyPrimary.java import com.ning.hfind.FileAttributes; import java.io.IOException; /* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class EmptyPrimary implements Primary { @Override
public boolean passesFilter(FileAttributes attributes)
pierre/hfind
src/main/java/com/ning/hfind/primary/UserPrimary.java
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // }
import com.ning.hfind.FileAttributes;
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class UserPrimary implements Primary { private final String user; public UserPrimary(String user) { this.user = user; } @Override
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // } // Path: src/main/java/com/ning/hfind/primary/UserPrimary.java import com.ning.hfind.FileAttributes; /* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class UserPrimary implements Primary { private final String user; public UserPrimary(String user) { this.user = user; } @Override
public boolean passesFilter(FileAttributes attributes)
pierre/hfind
src/main/java/com/ning/hfind/primary/GroupPrimary.java
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // }
import com.ning.hfind.FileAttributes;
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class GroupPrimary implements Primary { private final String group; public GroupPrimary(String group) { this.group = group; } @Override
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // } // Path: src/main/java/com/ning/hfind/primary/GroupPrimary.java import com.ning.hfind.FileAttributes; /* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class GroupPrimary implements Primary { private final String group; public GroupPrimary(String group) { this.group = group; } @Override
public boolean passesFilter(FileAttributes attributes)
pierre/hfind
src/main/java/com/ning/hfind/primary/OrOperand.java
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // }
import com.ning.hfind.FileAttributes;
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class OrOperand implements Operand { @Override
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // } // Path: src/main/java/com/ning/hfind/primary/OrOperand.java import com.ning.hfind.FileAttributes; /* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class OrOperand implements Operand { @Override
public boolean evaluateOperand(Primary primaryLeft, Primary primaryRight, FileAttributes fileAttributes)
pierre/hfind
src/main/java/com/ning/hfind/primary/SizePrimary.java
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // }
import com.ning.hfind.FileAttributes; import org.apache.commons.lang.StringUtils;
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class SizePrimary implements Primary { private final int size; private static final String SIZE_CHARACTER = "c"; private boolean blockMode = true; private final OperandModifier operandModifier; public SizePrimary(String size) { if (StringUtils.endsWith(size, SIZE_CHARACTER)) { blockMode = false; size = StringUtils.chop(size); } operandModifier = new OperandModifier(size); this.size = operandModifier.getSanitizedArgument(); } @Override
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // } // Path: src/main/java/com/ning/hfind/primary/SizePrimary.java import com.ning.hfind.FileAttributes; import org.apache.commons.lang.StringUtils; /* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class SizePrimary implements Primary { private final int size; private static final String SIZE_CHARACTER = "c"; private boolean blockMode = true; private final OperandModifier operandModifier; public SizePrimary(String size) { if (StringUtils.endsWith(size, SIZE_CHARACTER)) { blockMode = false; size = StringUtils.chop(size); } operandModifier = new OperandModifier(size); this.size = operandModifier.getSanitizedArgument(); } @Override
public boolean passesFilter(FileAttributes attributes)
pierre/hfind
src/main/java/com/ning/hfind/primary/TypePrimary.java
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // }
import com.ning.hfind.FileAttributes;
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class TypePrimary implements Primary { private final String type; private static final String TYPE_DIRECTORY = "d"; private static final String TYPE_FILE = "f"; public TypePrimary(String type) { if (!type.equals(TYPE_DIRECTORY) && !type.equals(TYPE_FILE)) { throw new IllegalArgumentException(String.format("File type must be %s or %s", TYPE_DIRECTORY, TYPE_FILE)); } this.type = type; } @Override
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // } // Path: src/main/java/com/ning/hfind/primary/TypePrimary.java import com.ning.hfind.FileAttributes; /* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class TypePrimary implements Primary { private final String type; private static final String TYPE_DIRECTORY = "d"; private static final String TYPE_FILE = "f"; public TypePrimary(String type) { if (!type.equals(TYPE_DIRECTORY) && !type.equals(TYPE_FILE)) { throw new IllegalArgumentException(String.format("File type must be %s or %s", TYPE_DIRECTORY, TYPE_FILE)); } this.type = type; } @Override
public boolean passesFilter(FileAttributes attributes)
pierre/hfind
src/main/java/com/ning/hfind/primary/NoGroupPrimary.java
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // }
import com.ning.hfind.FileAttributes;
/* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class NoGroupPrimary implements Primary { @Override
// Path: src/main/java/com/ning/hfind/FileAttributes.java // public interface FileAttributes extends Comparable<FileAttributes> // { // public ReadableDateTime getAccessDate(); // // public ReadableDateTime getModificationDate(); // // public boolean isDirectory(); // // public long getLength(); // // public long getBlockSize(); // // public int getReplicationCount(); // // public String getOwner(); // // public String getGroup(); // // public String getPath(); // // public boolean isReadableBy(String user, Collection<String> groups); // // public boolean isWritableBy(String user, Collection<String> groups); // // public boolean isExecutableBy(String user, Collection<String> groups); // // public FileStatus[] children() throws IOException; // } // Path: src/main/java/com/ning/hfind/primary/NoGroupPrimary.java import com.ning.hfind.FileAttributes; /* * Copyright 2010 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.hfind.primary; class NoGroupPrimary implements Primary { @Override
public boolean passesFilter(FileAttributes attributes)
javaquery/Examples
src/main/java/com/javaquery/collections/list/ListStreamSum.java
// Path: src/main/java/com/javaquery/bean/Item.java // public class Item { // // private Long id; // private String name; // private Double price; // // public Item() { // } // // public Item(String name, Double price) { // this.name = name; // this.price = price; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // public Comparator<Item> orderByNameASC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o1.getName().compareTo(o2.getName()); // } // return -1; // } // }; // } // // public Comparator<Item> orderByNameDESC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o2.getName().compareTo(o1.getName()); // } // return -1; // } // }; // } // // @Override // public String toString() { // return "Item{" + "name=" + name + ", price=" + price + '}'; // } // }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.javaquery.bean.Item;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.collections.list; /** * Summation of element in List using Stream api in java 8. * * @author javaQuery * @date 17th October, 2016 * @Github: https://github.com/javaquery/Examples */ public class ListStreamSum { public static void main(String[] args) { /* Summation of Integers in List */ List<Integer> integers = new ArrayList<>(Arrays.asList(10, 20, 30)); Integer integerSum = integers.stream().mapToInt(Integer::intValue).sum(); System.out.println("summation: " + integerSum); /* Summation when you have list of beans */
// Path: src/main/java/com/javaquery/bean/Item.java // public class Item { // // private Long id; // private String name; // private Double price; // // public Item() { // } // // public Item(String name, Double price) { // this.name = name; // this.price = price; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // public Comparator<Item> orderByNameASC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o1.getName().compareTo(o2.getName()); // } // return -1; // } // }; // } // // public Comparator<Item> orderByNameDESC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o2.getName().compareTo(o1.getName()); // } // return -1; // } // }; // } // // @Override // public String toString() { // return "Item{" + "name=" + name + ", price=" + price + '}'; // } // } // Path: src/main/java/com/javaquery/collections/list/ListStreamSum.java import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.javaquery.bean.Item; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.collections.list; /** * Summation of element in List using Stream api in java 8. * * @author javaQuery * @date 17th October, 2016 * @Github: https://github.com/javaquery/Examples */ public class ListStreamSum { public static void main(String[] args) { /* Summation of Integers in List */ List<Integer> integers = new ArrayList<>(Arrays.asList(10, 20, 30)); Integer integerSum = integers.stream().mapToInt(Integer::intValue).sum(); System.out.println("summation: " + integerSum); /* Summation when you have list of beans */
Item motoG = new Item("MotoG", 100.12);
javaquery/Examples
src/main/java/com/javaquery/java/util/ComparatorExample.java
// Path: src/main/java/com/javaquery/bean/Item.java // public class Item { // // private Long id; // private String name; // private Double price; // // public Item() { // } // // public Item(String name, Double price) { // this.name = name; // this.price = price; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // public Comparator<Item> orderByNameASC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o1.getName().compareTo(o2.getName()); // } // return -1; // } // }; // } // // public Comparator<Item> orderByNameDESC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o2.getName().compareTo(o1.getName()); // } // return -1; // } // }; // } // // @Override // public String toString() { // return "Item{" + "name=" + name + ", price=" + price + '}'; // } // }
import com.javaquery.bean.Item; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.java.util; /** * Example of Comparator. * @author javaQuery * @date 9th August, 2016 * @Github: https://github.com/javaquery/Examples */ public class ComparatorExample { public static void main(String[] args) {
// Path: src/main/java/com/javaquery/bean/Item.java // public class Item { // // private Long id; // private String name; // private Double price; // // public Item() { // } // // public Item(String name, Double price) { // this.name = name; // this.price = price; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // public Comparator<Item> orderByNameASC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o1.getName().compareTo(o2.getName()); // } // return -1; // } // }; // } // // public Comparator<Item> orderByNameDESC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o2.getName().compareTo(o1.getName()); // } // return -1; // } // }; // } // // @Override // public String toString() { // return "Item{" + "name=" + name + ", price=" + price + '}'; // } // } // Path: src/main/java/com/javaquery/java/util/ComparatorExample.java import com.javaquery.bean.Item; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.java.util; /** * Example of Comparator. * @author javaQuery * @date 9th August, 2016 * @Github: https://github.com/javaquery/Examples */ public class ComparatorExample { public static void main(String[] args) {
Item samsung = new Item();
javaquery/Examples
src/main/java/com/javaquery/google/firebase/FirebasePushObject.java
// Path: src/main/java/com/javaquery/bean/Item.java // public class Item { // // private Long id; // private String name; // private Double price; // // public Item() { // } // // public Item(String name, Double price) { // this.name = name; // this.price = price; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // public Comparator<Item> orderByNameASC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o1.getName().compareTo(o2.getName()); // } // return -1; // } // }; // } // // public Comparator<Item> orderByNameDESC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o2.getName().compareTo(o1.getName()); // } // return -1; // } // }; // } // // @Override // public String toString() { // return "Item{" + "name=" + name + ", price=" + price + '}'; // } // }
import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.javaquery.bean.Item; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.concurrent.CountDownLatch;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.google.firebase; /** * Example of Firebase push. * * @author javaQuery * @date 22nd September, 2016 * @Github: https://github.com/javaquery/Examples */ public class FirebasePushObject { public static void main(String[] args) {
// Path: src/main/java/com/javaquery/bean/Item.java // public class Item { // // private Long id; // private String name; // private Double price; // // public Item() { // } // // public Item(String name, Double price) { // this.name = name; // this.price = price; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // public Comparator<Item> orderByNameASC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o1.getName().compareTo(o2.getName()); // } // return -1; // } // }; // } // // public Comparator<Item> orderByNameDESC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o2.getName().compareTo(o1.getName()); // } // return -1; // } // }; // } // // @Override // public String toString() { // return "Item{" + "name=" + name + ", price=" + price + '}'; // } // } // Path: src/main/java/com/javaquery/google/firebase/FirebasePushObject.java import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.javaquery.bean.Item; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.concurrent.CountDownLatch; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.google.firebase; /** * Example of Firebase push. * * @author javaQuery * @date 22nd September, 2016 * @Github: https://github.com/javaquery/Examples */ public class FirebasePushObject { public static void main(String[] args) {
Item item = new Item();
javaquery/Examples
src/main/java/com/javaquery/collections/map/MapStreamSum.java
// Path: src/main/java/com/javaquery/bean/Item.java // public class Item { // // private Long id; // private String name; // private Double price; // // public Item() { // } // // public Item(String name, Double price) { // this.name = name; // this.price = price; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // public Comparator<Item> orderByNameASC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o1.getName().compareTo(o2.getName()); // } // return -1; // } // }; // } // // public Comparator<Item> orderByNameDESC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o2.getName().compareTo(o1.getName()); // } // return -1; // } // }; // } // // @Override // public String toString() { // return "Item{" + "name=" + name + ", price=" + price + '}'; // } // }
import com.javaquery.bean.Item; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.collections.map; /** * Summation of element in Map using Stream api in java 8. * * @author javaQuery * @date 17th October, 2016 * @Github: https://github.com/javaquery/Examples */ public class MapStreamSum { public static void main(String[] args) { /* Summation of Integers in Map */ Map<String, Integer> integers = new HashMap<>(); integers.put("A", 10); integers.put("B", 20); integers.put("C", 30); Integer integerSum = integers.values().stream().mapToInt(Integer::intValue).sum(); System.out.println("summation: " + integerSum); /* Summation when you have List/Set in Map */ Map<String, List<Integer>> listInMap = new HashMap<>(); listInMap.put("even_numbers", new ArrayList<>(Arrays.asList(2, 4, 6))); integerSum = listInMap.values().stream() .flatMapToInt(list -> list.stream().mapToInt(Integer::intValue)) .sum(); System.out.println("summation: " + integerSum); /* Summation when you have List/Set of beans in Map */
// Path: src/main/java/com/javaquery/bean/Item.java // public class Item { // // private Long id; // private String name; // private Double price; // // public Item() { // } // // public Item(String name, Double price) { // this.name = name; // this.price = price; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // public Comparator<Item> orderByNameASC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o1.getName().compareTo(o2.getName()); // } // return -1; // } // }; // } // // public Comparator<Item> orderByNameDESC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o2.getName().compareTo(o1.getName()); // } // return -1; // } // }; // } // // @Override // public String toString() { // return "Item{" + "name=" + name + ", price=" + price + '}'; // } // } // Path: src/main/java/com/javaquery/collections/map/MapStreamSum.java import com.javaquery.bean.Item; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.collections.map; /** * Summation of element in Map using Stream api in java 8. * * @author javaQuery * @date 17th October, 2016 * @Github: https://github.com/javaquery/Examples */ public class MapStreamSum { public static void main(String[] args) { /* Summation of Integers in Map */ Map<String, Integer> integers = new HashMap<>(); integers.put("A", 10); integers.put("B", 20); integers.put("C", 30); Integer integerSum = integers.values().stream().mapToInt(Integer::intValue).sum(); System.out.println("summation: " + integerSum); /* Summation when you have List/Set in Map */ Map<String, List<Integer>> listInMap = new HashMap<>(); listInMap.put("even_numbers", new ArrayList<>(Arrays.asList(2, 4, 6))); integerSum = listInMap.values().stream() .flatMapToInt(list -> list.stream().mapToInt(Integer::intValue)) .sum(); System.out.println("summation: " + integerSum); /* Summation when you have List/Set of beans in Map */
Item motoG = new Item("MotoG", 100.12);
javaquery/Examples
src/main/java/com/javaquery/google/gson/ObjectToJSON.java
// Path: src/main/java/com/javaquery/bean/Item.java // public class Item { // // private Long id; // private String name; // private Double price; // // public Item() { // } // // public Item(String name, Double price) { // this.name = name; // this.price = price; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // public Comparator<Item> orderByNameASC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o1.getName().compareTo(o2.getName()); // } // return -1; // } // }; // } // // public Comparator<Item> orderByNameDESC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o2.getName().compareTo(o1.getName()); // } // return -1; // } // }; // } // // @Override // public String toString() { // return "Item{" + "name=" + name + ", price=" + price + '}'; // } // }
import com.javaquery.bean.Item; import java.util.Arrays; import java.util.List; import com.google.gson.Gson;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.google.gson; /** * Convert Java object to json using gson. * @author javaQuery * @date 24th March, 2017 * @Github: https://github.com/javaquery/Examples */ public class ObjectToJSON { public static void main(String[] args) { /* Java object */
// Path: src/main/java/com/javaquery/bean/Item.java // public class Item { // // private Long id; // private String name; // private Double price; // // public Item() { // } // // public Item(String name, Double price) { // this.name = name; // this.price = price; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // public Comparator<Item> orderByNameASC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o1.getName().compareTo(o2.getName()); // } // return -1; // } // }; // } // // public Comparator<Item> orderByNameDESC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o2.getName().compareTo(o1.getName()); // } // return -1; // } // }; // } // // @Override // public String toString() { // return "Item{" + "name=" + name + ", price=" + price + '}'; // } // } // Path: src/main/java/com/javaquery/google/gson/ObjectToJSON.java import com.javaquery.bean.Item; import java.util.Arrays; import java.util.List; import com.google.gson.Gson; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.google.gson; /** * Convert Java object to json using gson. * @author javaQuery * @date 24th March, 2017 * @Github: https://github.com/javaquery/Examples */ public class ObjectToJSON { public static void main(String[] args) { /* Java object */
Item iPhone = new Item("iPhone 7", 100.12);
javaquery/Examples
src/main/java/com/javaquery/java/util/ComparableExample.java
// Path: src/main/java/com/javaquery/bean/ComparableItem.java // public class ComparableItem implements Comparable<ComparableItem>{ // // private String name; // private Double price; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // @Override // public int compareTo(ComparableItem item) { // if(item != null && item.getName() != null){ // return this.getName().compareTo(item.getName()); // } // return -1; // } // // @Override // public String toString() { // return "ComparableItem{" + "name=" + name + ", price=" + price + '}'; // } // }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.javaquery.bean.ComparableItem;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.java.util; /** * Example of Comparable. * @author javaQuery * @date 11th August, 2016 * @Github: https://github.com/javaquery/Examples */ public class ComparableExample { public static void main(String[] args) {
// Path: src/main/java/com/javaquery/bean/ComparableItem.java // public class ComparableItem implements Comparable<ComparableItem>{ // // private String name; // private Double price; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // @Override // public int compareTo(ComparableItem item) { // if(item != null && item.getName() != null){ // return this.getName().compareTo(item.getName()); // } // return -1; // } // // @Override // public String toString() { // return "ComparableItem{" + "name=" + name + ", price=" + price + '}'; // } // } // Path: src/main/java/com/javaquery/java/util/ComparableExample.java import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.javaquery.bean.ComparableItem; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.java.util; /** * Example of Comparable. * @author javaQuery * @date 11th August, 2016 * @Github: https://github.com/javaquery/Examples */ public class ComparableExample { public static void main(String[] args) {
ComparableItem samsung = new ComparableItem();
javaquery/Examples
src/main/java/com/javaquery/google/firebase/FirebaseSaveObject.java
// Path: src/main/java/com/javaquery/bean/Item.java // public class Item { // // private Long id; // private String name; // private Double price; // // public Item() { // } // // public Item(String name, Double price) { // this.name = name; // this.price = price; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // public Comparator<Item> orderByNameASC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o1.getName().compareTo(o2.getName()); // } // return -1; // } // }; // } // // public Comparator<Item> orderByNameDESC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o2.getName().compareTo(o1.getName()); // } // return -1; // } // }; // } // // @Override // public String toString() { // return "Item{" + "name=" + name + ", price=" + price + '}'; // } // }
import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.javaquery.bean.Item; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.concurrent.CountDownLatch;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.google.firebase; /** * Example of Firebase save. * * @author javaQuery * @date 7th September, 2016 * @Github: https://github.com/javaquery/Examples */ public class FirebaseSaveObject { public static void main(String[] args) {
// Path: src/main/java/com/javaquery/bean/Item.java // public class Item { // // private Long id; // private String name; // private Double price; // // public Item() { // } // // public Item(String name, Double price) { // this.name = name; // this.price = price; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // public Comparator<Item> orderByNameASC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o1.getName().compareTo(o2.getName()); // } // return -1; // } // }; // } // // public Comparator<Item> orderByNameDESC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o2.getName().compareTo(o1.getName()); // } // return -1; // } // }; // } // // @Override // public String toString() { // return "Item{" + "name=" + name + ", price=" + price + '}'; // } // } // Path: src/main/java/com/javaquery/google/firebase/FirebaseSaveObject.java import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.javaquery.bean.Item; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.concurrent.CountDownLatch; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.google.firebase; /** * Example of Firebase save. * * @author javaQuery * @date 7th September, 2016 * @Github: https://github.com/javaquery/Examples */ public class FirebaseSaveObject { public static void main(String[] args) {
Item item = new Item();
javaquery/Examples
src/main/java/com/javaquery/database/hibernate/OneToOneMappingExample.java
// Path: src/main/java/com/javaquery/bean/Country.java // @Entity // @Table(name = "country") // public class Country implements Serializable { // // @Id // @GeneratedValue // @Column(name = "id") // private Long id; // // @Column(name = "name") // private String name; // // @OneToOne(cascade = CascadeType.ALL, mappedBy = "country") // private Capital capital; // // @OneToOne // @JoinColumn(name = "primary_language_id", referencedColumnName = "id") // private Language language; // // @OneToMany(mappedBy = "country" /*, fetch = FetchType.LAZY*/) // Set<State> states = new HashSet<State>(); // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Capital getCapital() { // return capital; // } // // public void setCapital(Capital capital) { // this.capital = capital; // } // // public Language getLanguage() { // return language; // } // // public void setLanguage(Language language) { // this.language = language; // } // // public Set<State> getStates() { // return states; // } // // public void setStates(Set<State> states) { // this.states = states; // } // // @Override // public String toString() { // return "Country{" + "id=" + id + ", name=" + name + ", capital=" + capital + ", language=" + language + '}'; // } // }
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.javaquery.bean.Country;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.database.hibernate; /** * @author javaQuery * @date 11th April, 2017 * @Github: https://github.com/javaquery/Examples */ public class OneToOneMappingExample { public static void main(String[] args) { try { /* Create hibernate configuration. */ Configuration configuration = new Configuration(); configuration.configure("com\\javaquery\\database\\hibernate\\hibernate.cfg.xml"); /* Open session and begin database transaction for database operation. */ SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession();
// Path: src/main/java/com/javaquery/bean/Country.java // @Entity // @Table(name = "country") // public class Country implements Serializable { // // @Id // @GeneratedValue // @Column(name = "id") // private Long id; // // @Column(name = "name") // private String name; // // @OneToOne(cascade = CascadeType.ALL, mappedBy = "country") // private Capital capital; // // @OneToOne // @JoinColumn(name = "primary_language_id", referencedColumnName = "id") // private Language language; // // @OneToMany(mappedBy = "country" /*, fetch = FetchType.LAZY*/) // Set<State> states = new HashSet<State>(); // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Capital getCapital() { // return capital; // } // // public void setCapital(Capital capital) { // this.capital = capital; // } // // public Language getLanguage() { // return language; // } // // public void setLanguage(Language language) { // this.language = language; // } // // public Set<State> getStates() { // return states; // } // // public void setStates(Set<State> states) { // this.states = states; // } // // @Override // public String toString() { // return "Country{" + "id=" + id + ", name=" + name + ", capital=" + capital + ", language=" + language + '}'; // } // } // Path: src/main/java/com/javaquery/database/hibernate/OneToOneMappingExample.java import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.javaquery.bean.Country; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.database.hibernate; /** * @author javaQuery * @date 11th April, 2017 * @Github: https://github.com/javaquery/Examples */ public class OneToOneMappingExample { public static void main(String[] args) { try { /* Create hibernate configuration. */ Configuration configuration = new Configuration(); configuration.configure("com\\javaquery\\database\\hibernate\\hibernate.cfg.xml"); /* Open session and begin database transaction for database operation. */ SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession();
Country country = session.load(Country.class, 1L);
javaquery/Examples
src/main/java/com/javaquery/java/validation/ValidatorFactoryExample.java
// Path: src/main/java/com/javaquery/java/validation/bean/User.java // public class User { // // @NotEmpty(message = "firstName can not be empty") // @Size(min = 2, max = 20, message = "firstName length must be between 2 and 20") // private String firstName; // // @NotEmpty(message = "lastName can not be empty") // @Size(min = 2, max = 20, message = "lastName length must be between 2 and 20") // private String lastName; // // @NotEmpty(message = "nickNames can not be empty") // private List<@Size(min = 2, message = "nickName length must be greater than 2") String> nickNames; // // @Email // private String email; // // @NotEmpty(message = "password can not be empty") // @Size(min = 6, message = "password length must be at least 6 character") // private String password; // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public List<String> getNickNames() { // return nickNames; // } // // public void setNickNames(List<String> nickNames) { // this.nickNames = nickNames; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // }
import com.javaquery.java.validation.bean.User; import java.util.Arrays; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.java.validation; /** * @author javaQuery * @since 2018-02-24 * @github: https://github.com/javaquery/Examples */ public class ValidatorFactoryExample { public static void main(String[] args) { /* Prepare user object */
// Path: src/main/java/com/javaquery/java/validation/bean/User.java // public class User { // // @NotEmpty(message = "firstName can not be empty") // @Size(min = 2, max = 20, message = "firstName length must be between 2 and 20") // private String firstName; // // @NotEmpty(message = "lastName can not be empty") // @Size(min = 2, max = 20, message = "lastName length must be between 2 and 20") // private String lastName; // // @NotEmpty(message = "nickNames can not be empty") // private List<@Size(min = 2, message = "nickName length must be greater than 2") String> nickNames; // // @Email // private String email; // // @NotEmpty(message = "password can not be empty") // @Size(min = 6, message = "password length must be at least 6 character") // private String password; // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public List<String> getNickNames() { // return nickNames; // } // // public void setNickNames(List<String> nickNames) { // this.nickNames = nickNames; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // Path: src/main/java/com/javaquery/java/validation/ValidatorFactoryExample.java import com.javaquery.java.validation.bean.User; import java.util.Arrays; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.java.validation; /** * @author javaQuery * @since 2018-02-24 * @github: https://github.com/javaquery/Examples */ public class ValidatorFactoryExample { public static void main(String[] args) { /* Prepare user object */
User user = new User();
javaquery/Examples
src/main/java/com/javaquery/jasper/JasperTableExample.java
// Path: src/main/java/com/javaquery/bean/Item.java // public class Item { // // private Long id; // private String name; // private Double price; // // public Item() { // } // // public Item(String name, Double price) { // this.name = name; // this.price = price; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // public Comparator<Item> orderByNameASC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o1.getName().compareTo(o2.getName()); // } // return -1; // } // }; // } // // public Comparator<Item> orderByNameDESC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o2.getName().compareTo(o1.getName()); // } // return -1; // } // }; // } // // @Override // public String toString() { // return "Item{" + "name=" + name + ", price=" + price + '}'; // } // }
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.javaquery.bean.Item; import net.sf.jasperreports.engine.JREmptyDataSource; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.jasper; /** * @author javaQuery * @date 24nd November, 2015 * @Github: https://github.com/javaquery/Examples */ public class JasperTableExample { public static void main(String[] args) { try { /* User home directory location */ String userHomeDirectory = System.getProperty("user.home"); /* Output file location */ String outputFile = userHomeDirectory + File.separatorChar + "JasperTableExample.pdf"; /* List to hold Items */
// Path: src/main/java/com/javaquery/bean/Item.java // public class Item { // // private Long id; // private String name; // private Double price; // // public Item() { // } // // public Item(String name, Double price) { // this.name = name; // this.price = price; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // public Comparator<Item> orderByNameASC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o1.getName().compareTo(o2.getName()); // } // return -1; // } // }; // } // // public Comparator<Item> orderByNameDESC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o2.getName().compareTo(o1.getName()); // } // return -1; // } // }; // } // // @Override // public String toString() { // return "Item{" + "name=" + name + ", price=" + price + '}'; // } // } // Path: src/main/java/com/javaquery/jasper/JasperTableExample.java import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.javaquery.bean.Item; import net.sf.jasperreports.engine.JREmptyDataSource; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.jasper; /** * @author javaQuery * @date 24nd November, 2015 * @Github: https://github.com/javaquery/Examples */ public class JasperTableExample { public static void main(String[] args) { try { /* User home directory location */ String userHomeDirectory = System.getProperty("user.home"); /* Output file location */ String outputFile = userHomeDirectory + File.separatorChar + "JasperTableExample.pdf"; /* List to hold Items */
List<Item> listItems = new ArrayList<Item>();
javaquery/Examples
src/main/java/com/javaquery/google/gson/JSONToObject.java
// Path: src/main/java/com/javaquery/bean/Item.java // public class Item { // // private Long id; // private String name; // private Double price; // // public Item() { // } // // public Item(String name, Double price) { // this.name = name; // this.price = price; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // public Comparator<Item> orderByNameASC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o1.getName().compareTo(o2.getName()); // } // return -1; // } // }; // } // // public Comparator<Item> orderByNameDESC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o2.getName().compareTo(o1.getName()); // } // return -1; // } // }; // } // // @Override // public String toString() { // return "Item{" + "name=" + name + ", price=" + price + '}'; // } // }
import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.javaquery.bean.Item; import java.lang.reflect.Type; import java.util.List;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.google.gson; /** * Convert json string to java object using gson. * @author javaQuery * @date 24th March, 2017 * @Github: https://github.com/javaquery/Examples */ public class JSONToObject { public static void main(String[] args) { String jsonObjectString = "{\"name\":\"iPhone 7\",\"price\":100.12}"; String jsonArrayString = "[{\"name\":\"iPhone 7\",\"price\":100.12},{\"name\":\"Black Berry\",\"price\":50.12}]"; Gson gson = new Gson(); /* Convert JSONObject String to Object */
// Path: src/main/java/com/javaquery/bean/Item.java // public class Item { // // private Long id; // private String name; // private Double price; // // public Item() { // } // // public Item(String name, Double price) { // this.name = name; // this.price = price; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // public Comparator<Item> orderByNameASC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o1.getName().compareTo(o2.getName()); // } // return -1; // } // }; // } // // public Comparator<Item> orderByNameDESC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o2.getName().compareTo(o1.getName()); // } // return -1; // } // }; // } // // @Override // public String toString() { // return "Item{" + "name=" + name + ", price=" + price + '}'; // } // } // Path: src/main/java/com/javaquery/google/gson/JSONToObject.java import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.javaquery.bean.Item; import java.lang.reflect.Type; import java.util.List; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.google.gson; /** * Convert json string to java object using gson. * @author javaQuery * @date 24th March, 2017 * @Github: https://github.com/javaquery/Examples */ public class JSONToObject { public static void main(String[] args) { String jsonObjectString = "{\"name\":\"iPhone 7\",\"price\":100.12}"; String jsonArrayString = "[{\"name\":\"iPhone 7\",\"price\":100.12},{\"name\":\"Black Berry\",\"price\":50.12}]"; Gson gson = new Gson(); /* Convert JSONObject String to Object */
Item item = gson.fromJson(jsonObjectString, Item.class);
javaquery/Examples
src/main/java/com/javaquery/database/hibernate/OneToManyMappingExample.java
// Path: src/main/java/com/javaquery/bean/Country.java // @Entity // @Table(name = "country") // public class Country implements Serializable { // // @Id // @GeneratedValue // @Column(name = "id") // private Long id; // // @Column(name = "name") // private String name; // // @OneToOne(cascade = CascadeType.ALL, mappedBy = "country") // private Capital capital; // // @OneToOne // @JoinColumn(name = "primary_language_id", referencedColumnName = "id") // private Language language; // // @OneToMany(mappedBy = "country" /*, fetch = FetchType.LAZY*/) // Set<State> states = new HashSet<State>(); // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Capital getCapital() { // return capital; // } // // public void setCapital(Capital capital) { // this.capital = capital; // } // // public Language getLanguage() { // return language; // } // // public void setLanguage(Language language) { // this.language = language; // } // // public Set<State> getStates() { // return states; // } // // public void setStates(Set<State> states) { // this.states = states; // } // // @Override // public String toString() { // return "Country{" + "id=" + id + ", name=" + name + ", capital=" + capital + ", language=" + language + '}'; // } // } // // Path: src/main/java/com/javaquery/bean/State.java // @Entity // @Table(name = "state") // public class State implements Serializable{ // // @Id // @GeneratedValue // @Column(name = "id") // private Long id; // // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "country_id") // private Country country; // // @Column(name = "name") // private String name; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Country getCountry() { // return country; // } // // public void setCountry(Country country) { // this.country = country; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.javaquery.bean.Country; import com.javaquery.bean.State; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.database.hibernate; /** * Hibernate one to many example. * * @author javaQuery * @date 15th June, 2017 * @Github: https://github.com/javaquery/Examples */ public class OneToManyMappingExample { public static void main(String[] args) { try { /* Create hibernate configuration. */ Configuration configuration = new Configuration(); configuration.configure("com\\javaquery\\database\\hibernate\\hibernate.cfg.xml"); /* Open session and begin database transaction for database operation. */ SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession();
// Path: src/main/java/com/javaquery/bean/Country.java // @Entity // @Table(name = "country") // public class Country implements Serializable { // // @Id // @GeneratedValue // @Column(name = "id") // private Long id; // // @Column(name = "name") // private String name; // // @OneToOne(cascade = CascadeType.ALL, mappedBy = "country") // private Capital capital; // // @OneToOne // @JoinColumn(name = "primary_language_id", referencedColumnName = "id") // private Language language; // // @OneToMany(mappedBy = "country" /*, fetch = FetchType.LAZY*/) // Set<State> states = new HashSet<State>(); // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Capital getCapital() { // return capital; // } // // public void setCapital(Capital capital) { // this.capital = capital; // } // // public Language getLanguage() { // return language; // } // // public void setLanguage(Language language) { // this.language = language; // } // // public Set<State> getStates() { // return states; // } // // public void setStates(Set<State> states) { // this.states = states; // } // // @Override // public String toString() { // return "Country{" + "id=" + id + ", name=" + name + ", capital=" + capital + ", language=" + language + '}'; // } // } // // Path: src/main/java/com/javaquery/bean/State.java // @Entity // @Table(name = "state") // public class State implements Serializable{ // // @Id // @GeneratedValue // @Column(name = "id") // private Long id; // // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "country_id") // private Country country; // // @Column(name = "name") // private String name; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Country getCountry() { // return country; // } // // public void setCountry(Country country) { // this.country = country; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: src/main/java/com/javaquery/database/hibernate/OneToManyMappingExample.java import com.javaquery.bean.Country; import com.javaquery.bean.State; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.database.hibernate; /** * Hibernate one to many example. * * @author javaQuery * @date 15th June, 2017 * @Github: https://github.com/javaquery/Examples */ public class OneToManyMappingExample { public static void main(String[] args) { try { /* Create hibernate configuration. */ Configuration configuration = new Configuration(); configuration.configure("com\\javaquery\\database\\hibernate\\hibernate.cfg.xml"); /* Open session and begin database transaction for database operation. */ SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession();
Country country = session.load(Country.class, 1L);
javaquery/Examples
src/main/java/com/javaquery/database/hibernate/OneToManyMappingExample.java
// Path: src/main/java/com/javaquery/bean/Country.java // @Entity // @Table(name = "country") // public class Country implements Serializable { // // @Id // @GeneratedValue // @Column(name = "id") // private Long id; // // @Column(name = "name") // private String name; // // @OneToOne(cascade = CascadeType.ALL, mappedBy = "country") // private Capital capital; // // @OneToOne // @JoinColumn(name = "primary_language_id", referencedColumnName = "id") // private Language language; // // @OneToMany(mappedBy = "country" /*, fetch = FetchType.LAZY*/) // Set<State> states = new HashSet<State>(); // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Capital getCapital() { // return capital; // } // // public void setCapital(Capital capital) { // this.capital = capital; // } // // public Language getLanguage() { // return language; // } // // public void setLanguage(Language language) { // this.language = language; // } // // public Set<State> getStates() { // return states; // } // // public void setStates(Set<State> states) { // this.states = states; // } // // @Override // public String toString() { // return "Country{" + "id=" + id + ", name=" + name + ", capital=" + capital + ", language=" + language + '}'; // } // } // // Path: src/main/java/com/javaquery/bean/State.java // @Entity // @Table(name = "state") // public class State implements Serializable{ // // @Id // @GeneratedValue // @Column(name = "id") // private Long id; // // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "country_id") // private Country country; // // @Column(name = "name") // private String name; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Country getCountry() { // return country; // } // // public void setCountry(Country country) { // this.country = country; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.javaquery.bean.Country; import com.javaquery.bean.State; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.database.hibernate; /** * Hibernate one to many example. * * @author javaQuery * @date 15th June, 2017 * @Github: https://github.com/javaquery/Examples */ public class OneToManyMappingExample { public static void main(String[] args) { try { /* Create hibernate configuration. */ Configuration configuration = new Configuration(); configuration.configure("com\\javaquery\\database\\hibernate\\hibernate.cfg.xml"); /* Open session and begin database transaction for database operation. */ SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); Country country = session.load(Country.class, 1L); if(!country.getStates().isEmpty()){
// Path: src/main/java/com/javaquery/bean/Country.java // @Entity // @Table(name = "country") // public class Country implements Serializable { // // @Id // @GeneratedValue // @Column(name = "id") // private Long id; // // @Column(name = "name") // private String name; // // @OneToOne(cascade = CascadeType.ALL, mappedBy = "country") // private Capital capital; // // @OneToOne // @JoinColumn(name = "primary_language_id", referencedColumnName = "id") // private Language language; // // @OneToMany(mappedBy = "country" /*, fetch = FetchType.LAZY*/) // Set<State> states = new HashSet<State>(); // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Capital getCapital() { // return capital; // } // // public void setCapital(Capital capital) { // this.capital = capital; // } // // public Language getLanguage() { // return language; // } // // public void setLanguage(Language language) { // this.language = language; // } // // public Set<State> getStates() { // return states; // } // // public void setStates(Set<State> states) { // this.states = states; // } // // @Override // public String toString() { // return "Country{" + "id=" + id + ", name=" + name + ", capital=" + capital + ", language=" + language + '}'; // } // } // // Path: src/main/java/com/javaquery/bean/State.java // @Entity // @Table(name = "state") // public class State implements Serializable{ // // @Id // @GeneratedValue // @Column(name = "id") // private Long id; // // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "country_id") // private Country country; // // @Column(name = "name") // private String name; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Country getCountry() { // return country; // } // // public void setCountry(Country country) { // this.country = country; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: src/main/java/com/javaquery/database/hibernate/OneToManyMappingExample.java import com.javaquery.bean.Country; import com.javaquery.bean.State; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.database.hibernate; /** * Hibernate one to many example. * * @author javaQuery * @date 15th June, 2017 * @Github: https://github.com/javaquery/Examples */ public class OneToManyMappingExample { public static void main(String[] args) { try { /* Create hibernate configuration. */ Configuration configuration = new Configuration(); configuration.configure("com\\javaquery\\database\\hibernate\\hibernate.cfg.xml"); /* Open session and begin database transaction for database operation. */ SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); Country country = session.load(Country.class, 1L); if(!country.getStates().isEmpty()){
for (State state: country.getStates()) {
javaquery/Examples
src/main/java/com/javaquery/collections/set/SetStreamSum.java
// Path: src/main/java/com/javaquery/bean/Item.java // public class Item { // // private Long id; // private String name; // private Double price; // // public Item() { // } // // public Item(String name, Double price) { // this.name = name; // this.price = price; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // public Comparator<Item> orderByNameASC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o1.getName().compareTo(o2.getName()); // } // return -1; // } // }; // } // // public Comparator<Item> orderByNameDESC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o2.getName().compareTo(o1.getName()); // } // return -1; // } // }; // } // // @Override // public String toString() { // return "Item{" + "name=" + name + ", price=" + price + '}'; // } // }
import java.util.Arrays; import java.util.HashSet; import java.util.Set; import com.javaquery.bean.Item;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.collections.set; /** * Summation of element in Set using Stream api in java 8. * * @author javaQuery * @date 17th October, 2016 * @Github: https://github.com/javaquery/Examples */ public class SetStreamSum { public static void main(String[] args) { /* Summation of Integers in Set */ Set<Integer> integers = new HashSet<>(Arrays.asList(10, 20, 30)); Integer integerSum = integers.stream().mapToInt(Integer::intValue).sum(); System.out.println("summation: " + integerSum); /* Summation when you have set of beans */
// Path: src/main/java/com/javaquery/bean/Item.java // public class Item { // // private Long id; // private String name; // private Double price; // // public Item() { // } // // public Item(String name, Double price) { // this.name = name; // this.price = price; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Double getPrice() { // return price; // } // // public void setPrice(Double price) { // this.price = price; // } // // public Comparator<Item> orderByNameASC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o1.getName().compareTo(o2.getName()); // } // return -1; // } // }; // } // // public Comparator<Item> orderByNameDESC(){ // return new Comparator<Item>() { // @Override // public int compare(Item o1, Item o2) { // if(o1 != null && o1.getName() != null // && o2 != null && o2.getName() != null){ // return o2.getName().compareTo(o1.getName()); // } // return -1; // } // }; // } // // @Override // public String toString() { // return "Item{" + "name=" + name + ", price=" + price + '}'; // } // } // Path: src/main/java/com/javaquery/collections/set/SetStreamSum.java import java.util.Arrays; import java.util.HashSet; import java.util.Set; import com.javaquery.bean.Item; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javaquery.collections.set; /** * Summation of element in Set using Stream api in java 8. * * @author javaQuery * @date 17th October, 2016 * @Github: https://github.com/javaquery/Examples */ public class SetStreamSum { public static void main(String[] args) { /* Summation of Integers in Set */ Set<Integer> integers = new HashSet<>(Arrays.asList(10, 20, 30)); Integer integerSum = integers.stream().mapToInt(Integer::intValue).sum(); System.out.println("summation: " + integerSum); /* Summation when you have set of beans */
Item motoG = new Item("MotoG", 100.12);
WANdisco/s3hdfs
src/main/java/com/wandisco/s3hdfs/rewrite/redirect/CopyFileRedirect.java
// Path: src/main/java/com/wandisco/s3hdfs/rewrite/wrapper/RequestStreamWrapper.java // public class RequestStreamWrapper extends ServletInputStream { // // private final InputStream _in; // // public RequestStreamWrapper(InputStream realStream) { // this._in = realStream; // } // // @Override // public int read() throws IOException { // return _in.read(); // } // // @Override // public int read(byte[] bytes) throws IOException { // return _in.read(bytes); // } // // @Override // public int read(byte[] bytes, int i, int i2) throws IOException { // return _in.read(bytes, i, i2); // } // // @Override // public long skip(long l) throws IOException { // return _in.skip(l); // } // // @Override // public int available() throws IOException { // return _in.available(); // } // // @Override // public void close() throws IOException { // _in.close(); // } // // @Override // public synchronized void mark(int i) { // _in.mark(i); // } // // @Override // public synchronized void reset() throws IOException { // _in.reset(); // } // // @Override // public boolean markSupported() { // return _in.markSupported(); // } // // @Override // public String toString() { // return _in.toString(); // } // } // // Path: src/main/java/com/wandisco/s3hdfs/rewrite/wrapper/S3HdfsRequestWrapper.java // public class S3HdfsRequestWrapper extends HttpServletRequestWrapper { // // private ServletInputStream inputStream; // // /** // * Constructs a response adaptor wrapping the given response. // * // * @throws IllegalArgumentException if the response is null // */ // public S3HdfsRequestWrapper(HttpServletRequest request) { // super(request); // } // // @Override // public ServletInputStream getInputStream() throws IOException { // if (inputStream != null) // return inputStream; // return getRequest().getInputStream(); // } // // public void setInputStream(ServletInputStream is) { // inputStream = is; // } // // @Override // public String toString() { // return getRequest().toString(); // } // }
import com.wandisco.s3hdfs.rewrite.wrapper.RequestStreamWrapper; import com.wandisco.s3hdfs.rewrite.wrapper.S3HdfsRequestWrapper; import org.apache.commons.httpclient.methods.GetMethod; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import static com.wandisco.s3hdfs.conf.S3HdfsConstants.HTTP_METHOD.GET;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wandisco.s3hdfs.rewrite.redirect; public class CopyFileRedirect extends Redirect { public CopyFileRedirect(HttpServletRequest request, HttpServletResponse response) { super(request, response, null); LOG.debug("Created " + getClass().getSimpleName() + "."); } /** * Sends a PUT command to create the container directory inside of HDFS. * It uses the URL from the original request to do so. * * @param nameNodeHttpHost * @param userName * @throws IOException * @throws ServletException */ public void sendCopy(String nameNodeHttpHost, String userName, String srcBucket, String srcObject) throws IOException, ServletException { // Set up HttpGet and get original file String uri = replaceSrcs(request.getRequestURI(), srcBucket, srcObject); String[] nnHost = nameNodeHttpHost.split(":"); GetMethod httpGet = (GetMethod) getHttpMethod(request.getScheme(), nnHost[0], Integer.decode(nnHost[1]), "OPEN", userName, uri, GET); // Try up to 5 times to get the source file httpClient.executeMethod(httpGet); LOG.debug("1st response: " + httpGet.getStatusLine().toString()); for (int i = 0; i < 5 && httpGet.getStatusCode() == 403; i++) { httpGet.releaseConnection(); httpClient.executeMethod(httpGet); LOG.debug("Next response: " + httpGet.getStatusLine().toString()); } assert httpGet.getStatusCode() == 200;
// Path: src/main/java/com/wandisco/s3hdfs/rewrite/wrapper/RequestStreamWrapper.java // public class RequestStreamWrapper extends ServletInputStream { // // private final InputStream _in; // // public RequestStreamWrapper(InputStream realStream) { // this._in = realStream; // } // // @Override // public int read() throws IOException { // return _in.read(); // } // // @Override // public int read(byte[] bytes) throws IOException { // return _in.read(bytes); // } // // @Override // public int read(byte[] bytes, int i, int i2) throws IOException { // return _in.read(bytes, i, i2); // } // // @Override // public long skip(long l) throws IOException { // return _in.skip(l); // } // // @Override // public int available() throws IOException { // return _in.available(); // } // // @Override // public void close() throws IOException { // _in.close(); // } // // @Override // public synchronized void mark(int i) { // _in.mark(i); // } // // @Override // public synchronized void reset() throws IOException { // _in.reset(); // } // // @Override // public boolean markSupported() { // return _in.markSupported(); // } // // @Override // public String toString() { // return _in.toString(); // } // } // // Path: src/main/java/com/wandisco/s3hdfs/rewrite/wrapper/S3HdfsRequestWrapper.java // public class S3HdfsRequestWrapper extends HttpServletRequestWrapper { // // private ServletInputStream inputStream; // // /** // * Constructs a response adaptor wrapping the given response. // * // * @throws IllegalArgumentException if the response is null // */ // public S3HdfsRequestWrapper(HttpServletRequest request) { // super(request); // } // // @Override // public ServletInputStream getInputStream() throws IOException { // if (inputStream != null) // return inputStream; // return getRequest().getInputStream(); // } // // public void setInputStream(ServletInputStream is) { // inputStream = is; // } // // @Override // public String toString() { // return getRequest().toString(); // } // } // Path: src/main/java/com/wandisco/s3hdfs/rewrite/redirect/CopyFileRedirect.java import com.wandisco.s3hdfs.rewrite.wrapper.RequestStreamWrapper; import com.wandisco.s3hdfs.rewrite.wrapper.S3HdfsRequestWrapper; import org.apache.commons.httpclient.methods.GetMethod; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import static com.wandisco.s3hdfs.conf.S3HdfsConstants.HTTP_METHOD.GET; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wandisco.s3hdfs.rewrite.redirect; public class CopyFileRedirect extends Redirect { public CopyFileRedirect(HttpServletRequest request, HttpServletResponse response) { super(request, response, null); LOG.debug("Created " + getClass().getSimpleName() + "."); } /** * Sends a PUT command to create the container directory inside of HDFS. * It uses the URL from the original request to do so. * * @param nameNodeHttpHost * @param userName * @throws IOException * @throws ServletException */ public void sendCopy(String nameNodeHttpHost, String userName, String srcBucket, String srcObject) throws IOException, ServletException { // Set up HttpGet and get original file String uri = replaceSrcs(request.getRequestURI(), srcBucket, srcObject); String[] nnHost = nameNodeHttpHost.split(":"); GetMethod httpGet = (GetMethod) getHttpMethod(request.getScheme(), nnHost[0], Integer.decode(nnHost[1]), "OPEN", userName, uri, GET); // Try up to 5 times to get the source file httpClient.executeMethod(httpGet); LOG.debug("1st response: " + httpGet.getStatusLine().toString()); for (int i = 0; i < 5 && httpGet.getStatusCode() == 403; i++) { httpGet.releaseConnection(); httpClient.executeMethod(httpGet); LOG.debug("Next response: " + httpGet.getStatusLine().toString()); } assert httpGet.getStatusCode() == 200;
assert request instanceof S3HdfsRequestWrapper;
WANdisco/s3hdfs
src/main/java/com/wandisco/s3hdfs/rewrite/redirect/CopyFileRedirect.java
// Path: src/main/java/com/wandisco/s3hdfs/rewrite/wrapper/RequestStreamWrapper.java // public class RequestStreamWrapper extends ServletInputStream { // // private final InputStream _in; // // public RequestStreamWrapper(InputStream realStream) { // this._in = realStream; // } // // @Override // public int read() throws IOException { // return _in.read(); // } // // @Override // public int read(byte[] bytes) throws IOException { // return _in.read(bytes); // } // // @Override // public int read(byte[] bytes, int i, int i2) throws IOException { // return _in.read(bytes, i, i2); // } // // @Override // public long skip(long l) throws IOException { // return _in.skip(l); // } // // @Override // public int available() throws IOException { // return _in.available(); // } // // @Override // public void close() throws IOException { // _in.close(); // } // // @Override // public synchronized void mark(int i) { // _in.mark(i); // } // // @Override // public synchronized void reset() throws IOException { // _in.reset(); // } // // @Override // public boolean markSupported() { // return _in.markSupported(); // } // // @Override // public String toString() { // return _in.toString(); // } // } // // Path: src/main/java/com/wandisco/s3hdfs/rewrite/wrapper/S3HdfsRequestWrapper.java // public class S3HdfsRequestWrapper extends HttpServletRequestWrapper { // // private ServletInputStream inputStream; // // /** // * Constructs a response adaptor wrapping the given response. // * // * @throws IllegalArgumentException if the response is null // */ // public S3HdfsRequestWrapper(HttpServletRequest request) { // super(request); // } // // @Override // public ServletInputStream getInputStream() throws IOException { // if (inputStream != null) // return inputStream; // return getRequest().getInputStream(); // } // // public void setInputStream(ServletInputStream is) { // inputStream = is; // } // // @Override // public String toString() { // return getRequest().toString(); // } // }
import com.wandisco.s3hdfs.rewrite.wrapper.RequestStreamWrapper; import com.wandisco.s3hdfs.rewrite.wrapper.S3HdfsRequestWrapper; import org.apache.commons.httpclient.methods.GetMethod; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import static com.wandisco.s3hdfs.conf.S3HdfsConstants.HTTP_METHOD.GET;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wandisco.s3hdfs.rewrite.redirect; public class CopyFileRedirect extends Redirect { public CopyFileRedirect(HttpServletRequest request, HttpServletResponse response) { super(request, response, null); LOG.debug("Created " + getClass().getSimpleName() + "."); } /** * Sends a PUT command to create the container directory inside of HDFS. * It uses the URL from the original request to do so. * * @param nameNodeHttpHost * @param userName * @throws IOException * @throws ServletException */ public void sendCopy(String nameNodeHttpHost, String userName, String srcBucket, String srcObject) throws IOException, ServletException { // Set up HttpGet and get original file String uri = replaceSrcs(request.getRequestURI(), srcBucket, srcObject); String[] nnHost = nameNodeHttpHost.split(":"); GetMethod httpGet = (GetMethod) getHttpMethod(request.getScheme(), nnHost[0], Integer.decode(nnHost[1]), "OPEN", userName, uri, GET); // Try up to 5 times to get the source file httpClient.executeMethod(httpGet); LOG.debug("1st response: " + httpGet.getStatusLine().toString()); for (int i = 0; i < 5 && httpGet.getStatusCode() == 403; i++) { httpGet.releaseConnection(); httpClient.executeMethod(httpGet); LOG.debug("Next response: " + httpGet.getStatusLine().toString()); } assert httpGet.getStatusCode() == 200; assert request instanceof S3HdfsRequestWrapper; ((S3HdfsRequestWrapper) request).setInputStream(
// Path: src/main/java/com/wandisco/s3hdfs/rewrite/wrapper/RequestStreamWrapper.java // public class RequestStreamWrapper extends ServletInputStream { // // private final InputStream _in; // // public RequestStreamWrapper(InputStream realStream) { // this._in = realStream; // } // // @Override // public int read() throws IOException { // return _in.read(); // } // // @Override // public int read(byte[] bytes) throws IOException { // return _in.read(bytes); // } // // @Override // public int read(byte[] bytes, int i, int i2) throws IOException { // return _in.read(bytes, i, i2); // } // // @Override // public long skip(long l) throws IOException { // return _in.skip(l); // } // // @Override // public int available() throws IOException { // return _in.available(); // } // // @Override // public void close() throws IOException { // _in.close(); // } // // @Override // public synchronized void mark(int i) { // _in.mark(i); // } // // @Override // public synchronized void reset() throws IOException { // _in.reset(); // } // // @Override // public boolean markSupported() { // return _in.markSupported(); // } // // @Override // public String toString() { // return _in.toString(); // } // } // // Path: src/main/java/com/wandisco/s3hdfs/rewrite/wrapper/S3HdfsRequestWrapper.java // public class S3HdfsRequestWrapper extends HttpServletRequestWrapper { // // private ServletInputStream inputStream; // // /** // * Constructs a response adaptor wrapping the given response. // * // * @throws IllegalArgumentException if the response is null // */ // public S3HdfsRequestWrapper(HttpServletRequest request) { // super(request); // } // // @Override // public ServletInputStream getInputStream() throws IOException { // if (inputStream != null) // return inputStream; // return getRequest().getInputStream(); // } // // public void setInputStream(ServletInputStream is) { // inputStream = is; // } // // @Override // public String toString() { // return getRequest().toString(); // } // } // Path: src/main/java/com/wandisco/s3hdfs/rewrite/redirect/CopyFileRedirect.java import com.wandisco.s3hdfs.rewrite.wrapper.RequestStreamWrapper; import com.wandisco.s3hdfs.rewrite.wrapper.S3HdfsRequestWrapper; import org.apache.commons.httpclient.methods.GetMethod; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import static com.wandisco.s3hdfs.conf.S3HdfsConstants.HTTP_METHOD.GET; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wandisco.s3hdfs.rewrite.redirect; public class CopyFileRedirect extends Redirect { public CopyFileRedirect(HttpServletRequest request, HttpServletResponse response) { super(request, response, null); LOG.debug("Created " + getClass().getSimpleName() + "."); } /** * Sends a PUT command to create the container directory inside of HDFS. * It uses the URL from the original request to do so. * * @param nameNodeHttpHost * @param userName * @throws IOException * @throws ServletException */ public void sendCopy(String nameNodeHttpHost, String userName, String srcBucket, String srcObject) throws IOException, ServletException { // Set up HttpGet and get original file String uri = replaceSrcs(request.getRequestURI(), srcBucket, srcObject); String[] nnHost = nameNodeHttpHost.split(":"); GetMethod httpGet = (GetMethod) getHttpMethod(request.getScheme(), nnHost[0], Integer.decode(nnHost[1]), "OPEN", userName, uri, GET); // Try up to 5 times to get the source file httpClient.executeMethod(httpGet); LOG.debug("1st response: " + httpGet.getStatusLine().toString()); for (int i = 0; i < 5 && httpGet.getStatusCode() == 403; i++) { httpGet.releaseConnection(); httpClient.executeMethod(httpGet); LOG.debug("Next response: " + httpGet.getStatusLine().toString()); } assert httpGet.getStatusCode() == 200; assert request instanceof S3HdfsRequestWrapper; ((S3HdfsRequestWrapper) request).setInputStream(
new RequestStreamWrapper(httpGet.getResponseBodyAsStream()));
WANdisco/s3hdfs
src/main/java/com/wandisco/s3hdfs/rewrite/xml/S3XmlWriter.java
// Path: src/main/java/com/wandisco/s3hdfs/rewrite/wrapper/S3HdfsFileStatus.java // public class S3HdfsFileStatus extends HdfsFileStatus { // private long objectModTime; // private long objectSize; // private String versionId; // private boolean isDelMarker; // private boolean isLatest; // // // public S3HdfsFileStatus(long length, boolean isdir, int block_replication, // long blocksize, long modification_time, long access_time, // FsPermission permission, String owner, String group, // byte[] symlink, byte[] path, long fileId, // int childrenNum) { // super(length, isdir, block_replication, blocksize, modification_time, // access_time, permission, owner, group, symlink, path, fileId, // childrenNum); // } // // public String getVersionId() { // return versionId; // } // // public void setVersionId(String versionId) { // this.versionId = versionId; // } // // public long getObjectModTime() { // return objectModTime; // } // // public void setObjectModTime(long time) { // this.objectModTime = time; // } // // public long getObjectSize() { // return objectSize; // } // // public void setObjectSize(long size) { // this.objectSize = size; // } // // public boolean isLatest() { // return isLatest; // } // // public void setLatest(boolean latest) { // isLatest = latest; // } // // public boolean isDelMarker() { // return isDelMarker; // } // // public void setDelMarker(boolean delMarker) { // isDelMarker = delMarker; // } // // }
import com.wandisco.s3hdfs.rewrite.wrapper.S3HdfsFileStatus; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import java.io.IOException; import java.util.Date; import java.util.List; import java.util.Map; import java.util.UUID; import static com.wandisco.s3hdfs.conf.S3HdfsConstants.PART_FILE_NAME; import static com.wandisco.s3hdfs.conf.S3HdfsConstants.S3_VERSION;
final String maxParts) { //writes once writeXMLHeader(); //writes once writeListPartsHead(); //writes once writeListPartsSubHead(bucketName, objectName, userName, uploadId, partNumberMarker, maxParts); //writes MULTIPLE writeParts(); //writes once writeListPartsTail(); return finalOutput.toString(); } public String writeMultiPartCompleteToXml(final String bucketName, final String objectName, final String serviceHost, final String proxyPort) { //writes once writeXMLHeader(); //writes once writeCompleteMultiPartHead(); //writes once writeCompleteMultiPartBody(bucketName, objectName, serviceHost, proxyPort); //writes once writeCompleteMultiPartTail(); return finalOutput.toString(); }
// Path: src/main/java/com/wandisco/s3hdfs/rewrite/wrapper/S3HdfsFileStatus.java // public class S3HdfsFileStatus extends HdfsFileStatus { // private long objectModTime; // private long objectSize; // private String versionId; // private boolean isDelMarker; // private boolean isLatest; // // // public S3HdfsFileStatus(long length, boolean isdir, int block_replication, // long blocksize, long modification_time, long access_time, // FsPermission permission, String owner, String group, // byte[] symlink, byte[] path, long fileId, // int childrenNum) { // super(length, isdir, block_replication, blocksize, modification_time, // access_time, permission, owner, group, symlink, path, fileId, // childrenNum); // } // // public String getVersionId() { // return versionId; // } // // public void setVersionId(String versionId) { // this.versionId = versionId; // } // // public long getObjectModTime() { // return objectModTime; // } // // public void setObjectModTime(long time) { // this.objectModTime = time; // } // // public long getObjectSize() { // return objectSize; // } // // public void setObjectSize(long size) { // this.objectSize = size; // } // // public boolean isLatest() { // return isLatest; // } // // public void setLatest(boolean latest) { // isLatest = latest; // } // // public boolean isDelMarker() { // return isDelMarker; // } // // public void setDelMarker(boolean delMarker) { // isDelMarker = delMarker; // } // // } // Path: src/main/java/com/wandisco/s3hdfs/rewrite/xml/S3XmlWriter.java import com.wandisco.s3hdfs.rewrite.wrapper.S3HdfsFileStatus; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import java.io.IOException; import java.util.Date; import java.util.List; import java.util.Map; import java.util.UUID; import static com.wandisco.s3hdfs.conf.S3HdfsConstants.PART_FILE_NAME; import static com.wandisco.s3hdfs.conf.S3HdfsConstants.S3_VERSION; final String maxParts) { //writes once writeXMLHeader(); //writes once writeListPartsHead(); //writes once writeListPartsSubHead(bucketName, objectName, userName, uploadId, partNumberMarker, maxParts); //writes MULTIPLE writeParts(); //writes once writeListPartsTail(); return finalOutput.toString(); } public String writeMultiPartCompleteToXml(final String bucketName, final String objectName, final String serviceHost, final String proxyPort) { //writes once writeXMLHeader(); //writes once writeCompleteMultiPartHead(); //writes once writeCompleteMultiPartBody(bucketName, objectName, serviceHost, proxyPort); //writes once writeCompleteMultiPartTail(); return finalOutput.toString(); }
public String writeListVersionsToXml(final Map<String, List<S3HdfsFileStatus>> versions,
neowu/frontend-demo-project
website/src/main/java/app/web/controller/ProductAJAXWebServiceImpl.java
// Path: website/src/main/java/app/api/ProductAJAXWebService.java // public interface ProductAJAXWebService { // @GET // @Path("/ajax/product") // ListProductResponse list(); // // @GET // @Path("/ajax/product/create-config") // CreateProductConfigResponse createConfig(); // // @GET // @Path("/ajax/product/:id") // GetProductResponse get(@PathParam("id") String id); // // @GET // @Path("/ajax/product/:id/child/:childId") // GetProductResponse getChild(@PathParam("id") String id, @PathParam("childId") String childId); // } // // Path: website/src/main/java/app/api/product/CreateProductConfigResponse.java // public class CreateProductConfigResponse { // @NotNull // @Property(name = "types") // public List<ProductType> types; // // @NotNull // @Property(name = "now") // public ZonedDateTime now = ZonedDateTime.now(); // // public static class ProductType { // @NotNull // @Property(name = "name") // public String name; // // @NotNull // @Property(name = "value") // public String value; // } // } // // Path: website/src/main/java/app/api/product/GetProductResponse.java // public class GetProductResponse { // // } // // Path: website/src/main/java/app/api/product/ListProductResponse.java // public class ListProductResponse { // // }
import app.api.ProductAJAXWebService; import app.api.product.CreateProductConfigResponse; import app.api.product.GetProductResponse; import app.api.product.ListProductResponse; import core.framework.util.Lists;
package app.web.controller; /** * @author neo */ public class ProductAJAXWebServiceImpl implements ProductAJAXWebService { @Override
// Path: website/src/main/java/app/api/ProductAJAXWebService.java // public interface ProductAJAXWebService { // @GET // @Path("/ajax/product") // ListProductResponse list(); // // @GET // @Path("/ajax/product/create-config") // CreateProductConfigResponse createConfig(); // // @GET // @Path("/ajax/product/:id") // GetProductResponse get(@PathParam("id") String id); // // @GET // @Path("/ajax/product/:id/child/:childId") // GetProductResponse getChild(@PathParam("id") String id, @PathParam("childId") String childId); // } // // Path: website/src/main/java/app/api/product/CreateProductConfigResponse.java // public class CreateProductConfigResponse { // @NotNull // @Property(name = "types") // public List<ProductType> types; // // @NotNull // @Property(name = "now") // public ZonedDateTime now = ZonedDateTime.now(); // // public static class ProductType { // @NotNull // @Property(name = "name") // public String name; // // @NotNull // @Property(name = "value") // public String value; // } // } // // Path: website/src/main/java/app/api/product/GetProductResponse.java // public class GetProductResponse { // // } // // Path: website/src/main/java/app/api/product/ListProductResponse.java // public class ListProductResponse { // // } // Path: website/src/main/java/app/web/controller/ProductAJAXWebServiceImpl.java import app.api.ProductAJAXWebService; import app.api.product.CreateProductConfigResponse; import app.api.product.GetProductResponse; import app.api.product.ListProductResponse; import core.framework.util.Lists; package app.web.controller; /** * @author neo */ public class ProductAJAXWebServiceImpl implements ProductAJAXWebService { @Override
public ListProductResponse list() {
neowu/frontend-demo-project
website/src/main/java/app/web/controller/ProductAJAXWebServiceImpl.java
// Path: website/src/main/java/app/api/ProductAJAXWebService.java // public interface ProductAJAXWebService { // @GET // @Path("/ajax/product") // ListProductResponse list(); // // @GET // @Path("/ajax/product/create-config") // CreateProductConfigResponse createConfig(); // // @GET // @Path("/ajax/product/:id") // GetProductResponse get(@PathParam("id") String id); // // @GET // @Path("/ajax/product/:id/child/:childId") // GetProductResponse getChild(@PathParam("id") String id, @PathParam("childId") String childId); // } // // Path: website/src/main/java/app/api/product/CreateProductConfigResponse.java // public class CreateProductConfigResponse { // @NotNull // @Property(name = "types") // public List<ProductType> types; // // @NotNull // @Property(name = "now") // public ZonedDateTime now = ZonedDateTime.now(); // // public static class ProductType { // @NotNull // @Property(name = "name") // public String name; // // @NotNull // @Property(name = "value") // public String value; // } // } // // Path: website/src/main/java/app/api/product/GetProductResponse.java // public class GetProductResponse { // // } // // Path: website/src/main/java/app/api/product/ListProductResponse.java // public class ListProductResponse { // // }
import app.api.ProductAJAXWebService; import app.api.product.CreateProductConfigResponse; import app.api.product.GetProductResponse; import app.api.product.ListProductResponse; import core.framework.util.Lists;
package app.web.controller; /** * @author neo */ public class ProductAJAXWebServiceImpl implements ProductAJAXWebService { @Override public ListProductResponse list() { try { Thread.sleep(3000); } catch (InterruptedException e) { throw new Error(e); } return new ListProductResponse(); } @Override
// Path: website/src/main/java/app/api/ProductAJAXWebService.java // public interface ProductAJAXWebService { // @GET // @Path("/ajax/product") // ListProductResponse list(); // // @GET // @Path("/ajax/product/create-config") // CreateProductConfigResponse createConfig(); // // @GET // @Path("/ajax/product/:id") // GetProductResponse get(@PathParam("id") String id); // // @GET // @Path("/ajax/product/:id/child/:childId") // GetProductResponse getChild(@PathParam("id") String id, @PathParam("childId") String childId); // } // // Path: website/src/main/java/app/api/product/CreateProductConfigResponse.java // public class CreateProductConfigResponse { // @NotNull // @Property(name = "types") // public List<ProductType> types; // // @NotNull // @Property(name = "now") // public ZonedDateTime now = ZonedDateTime.now(); // // public static class ProductType { // @NotNull // @Property(name = "name") // public String name; // // @NotNull // @Property(name = "value") // public String value; // } // } // // Path: website/src/main/java/app/api/product/GetProductResponse.java // public class GetProductResponse { // // } // // Path: website/src/main/java/app/api/product/ListProductResponse.java // public class ListProductResponse { // // } // Path: website/src/main/java/app/web/controller/ProductAJAXWebServiceImpl.java import app.api.ProductAJAXWebService; import app.api.product.CreateProductConfigResponse; import app.api.product.GetProductResponse; import app.api.product.ListProductResponse; import core.framework.util.Lists; package app.web.controller; /** * @author neo */ public class ProductAJAXWebServiceImpl implements ProductAJAXWebService { @Override public ListProductResponse list() { try { Thread.sleep(3000); } catch (InterruptedException e) { throw new Error(e); } return new ListProductResponse(); } @Override
public CreateProductConfigResponse createConfig() {
neowu/frontend-demo-project
website/src/main/java/app/web/controller/ProductAJAXWebServiceImpl.java
// Path: website/src/main/java/app/api/ProductAJAXWebService.java // public interface ProductAJAXWebService { // @GET // @Path("/ajax/product") // ListProductResponse list(); // // @GET // @Path("/ajax/product/create-config") // CreateProductConfigResponse createConfig(); // // @GET // @Path("/ajax/product/:id") // GetProductResponse get(@PathParam("id") String id); // // @GET // @Path("/ajax/product/:id/child/:childId") // GetProductResponse getChild(@PathParam("id") String id, @PathParam("childId") String childId); // } // // Path: website/src/main/java/app/api/product/CreateProductConfigResponse.java // public class CreateProductConfigResponse { // @NotNull // @Property(name = "types") // public List<ProductType> types; // // @NotNull // @Property(name = "now") // public ZonedDateTime now = ZonedDateTime.now(); // // public static class ProductType { // @NotNull // @Property(name = "name") // public String name; // // @NotNull // @Property(name = "value") // public String value; // } // } // // Path: website/src/main/java/app/api/product/GetProductResponse.java // public class GetProductResponse { // // } // // Path: website/src/main/java/app/api/product/ListProductResponse.java // public class ListProductResponse { // // }
import app.api.ProductAJAXWebService; import app.api.product.CreateProductConfigResponse; import app.api.product.GetProductResponse; import app.api.product.ListProductResponse; import core.framework.util.Lists;
package app.web.controller; /** * @author neo */ public class ProductAJAXWebServiceImpl implements ProductAJAXWebService { @Override public ListProductResponse list() { try { Thread.sleep(3000); } catch (InterruptedException e) { throw new Error(e); } return new ListProductResponse(); } @Override public CreateProductConfigResponse createConfig() { CreateProductConfigResponse response = new CreateProductConfigResponse(); response.types = Lists.newArrayList(); response.types.add(type("type1", "1")); response.types.add(type("type2", "2")); return response; } @Override
// Path: website/src/main/java/app/api/ProductAJAXWebService.java // public interface ProductAJAXWebService { // @GET // @Path("/ajax/product") // ListProductResponse list(); // // @GET // @Path("/ajax/product/create-config") // CreateProductConfigResponse createConfig(); // // @GET // @Path("/ajax/product/:id") // GetProductResponse get(@PathParam("id") String id); // // @GET // @Path("/ajax/product/:id/child/:childId") // GetProductResponse getChild(@PathParam("id") String id, @PathParam("childId") String childId); // } // // Path: website/src/main/java/app/api/product/CreateProductConfigResponse.java // public class CreateProductConfigResponse { // @NotNull // @Property(name = "types") // public List<ProductType> types; // // @NotNull // @Property(name = "now") // public ZonedDateTime now = ZonedDateTime.now(); // // public static class ProductType { // @NotNull // @Property(name = "name") // public String name; // // @NotNull // @Property(name = "value") // public String value; // } // } // // Path: website/src/main/java/app/api/product/GetProductResponse.java // public class GetProductResponse { // // } // // Path: website/src/main/java/app/api/product/ListProductResponse.java // public class ListProductResponse { // // } // Path: website/src/main/java/app/web/controller/ProductAJAXWebServiceImpl.java import app.api.ProductAJAXWebService; import app.api.product.CreateProductConfigResponse; import app.api.product.GetProductResponse; import app.api.product.ListProductResponse; import core.framework.util.Lists; package app.web.controller; /** * @author neo */ public class ProductAJAXWebServiceImpl implements ProductAJAXWebService { @Override public ListProductResponse list() { try { Thread.sleep(3000); } catch (InterruptedException e) { throw new Error(e); } return new ListProductResponse(); } @Override public CreateProductConfigResponse createConfig() { CreateProductConfigResponse response = new CreateProductConfigResponse(); response.types = Lists.newArrayList(); response.types.add(type("type1", "1")); response.types.add(type("type2", "2")); return response; } @Override
public GetProductResponse get(String id) {
neowu/frontend-demo-project
website/src/main/java/app/web/interceptor/LoginInterceptor.java
// Path: website/src/main/java/app/web/Sessions.java // public final class Sessions { // private static final String USER = "LOGIN_USER"; // // public static boolean isUserLogin(Request request) { // return request.session().get(USER).isPresent(); // } // // public static LoginUser loginUser(Request request) { // String loginUser = request.session().get(USER).orElseThrow(() -> new UnauthorizedException("user not login")); // return JSON.fromJSON(LoginUser.class, loginUser); // } // // public static void setLoginUser(Request request, LoginUser user) { // request.session().set(USER, JSON.toJSON(user)); // } // }
import app.web.Sessions; import core.framework.web.Interceptor; import core.framework.web.Invocation; import core.framework.web.Request; import core.framework.web.Response; import core.framework.web.WebContext;
package app.web.interceptor; /** * @author neo */ public class LoginInterceptor implements Interceptor { @Override public Response intercept(Invocation invocation) throws Exception { if (invocation.annotation(LoginRequired.class) != null) { WebContext context = invocation.context(); Request request = context.request();
// Path: website/src/main/java/app/web/Sessions.java // public final class Sessions { // private static final String USER = "LOGIN_USER"; // // public static boolean isUserLogin(Request request) { // return request.session().get(USER).isPresent(); // } // // public static LoginUser loginUser(Request request) { // String loginUser = request.session().get(USER).orElseThrow(() -> new UnauthorizedException("user not login")); // return JSON.fromJSON(LoginUser.class, loginUser); // } // // public static void setLoginUser(Request request, LoginUser user) { // request.session().set(USER, JSON.toJSON(user)); // } // } // Path: website/src/main/java/app/web/interceptor/LoginInterceptor.java import app.web.Sessions; import core.framework.web.Interceptor; import core.framework.web.Invocation; import core.framework.web.Request; import core.framework.web.Response; import core.framework.web.WebContext; package app.web.interceptor; /** * @author neo */ public class LoginInterceptor implements Interceptor { @Override public Response intercept(Invocation invocation) throws Exception { if (invocation.annotation(LoginRequired.class) != null) { WebContext context = invocation.context(); Request request = context.request();
Sessions.loginUser(request);
neowu/frontend-demo-project
website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/user/CurrentUserAJAXResponse.java // public class CurrentUserAJAXResponse { // @NotNull // @Property(name = "loggedIn") // public Boolean loggedIn; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // // Path: website/src/main/java/app/api/user/LoginAJAXRequest.java // public class LoginAJAXRequest { // @NotNull // @Property(name = "username") // public String username; // // @NotNull // @Size(min = 3) // @Property(name = "password") // public String password; // } // // Path: website/src/main/java/app/api/user/LoginAJAXResponse.java // public class LoginAJAXResponse { // @NotNull // @Property(name = "success") // public Boolean success; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // // @Property(name = "errorMessage") // public String errorMessage; // } // // Path: website/src/main/java/app/web/Sessions.java // public final class Sessions { // private static final String USER = "LOGIN_USER"; // // public static boolean isUserLogin(Request request) { // return request.session().get(USER).isPresent(); // } // // public static LoginUser loginUser(Request request) { // String loginUser = request.session().get(USER).orElseThrow(() -> new UnauthorizedException("user not login")); // return JSON.fromJSON(LoginUser.class, loginUser); // } // // public static void setLoginUser(Request request, LoginUser user) { // request.session().set(USER, JSON.toJSON(user)); // } // } // // Path: website/src/main/java/app/web/session/LoginUser.java // public class LoginUser { // @Property(name = "userId") // public String userId; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // }
import app.api.AccountAJAXWebService; import app.api.user.CurrentUserAJAXResponse; import app.api.user.LoginAJAXRequest; import app.api.user.LoginAJAXResponse; import app.web.Sessions; import app.web.session.LoginUser; import core.framework.inject.Inject; import core.framework.web.WebContext;
package app.web.controller; /** * @author neo */ public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { @Inject WebContext context; @Override
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/user/CurrentUserAJAXResponse.java // public class CurrentUserAJAXResponse { // @NotNull // @Property(name = "loggedIn") // public Boolean loggedIn; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // // Path: website/src/main/java/app/api/user/LoginAJAXRequest.java // public class LoginAJAXRequest { // @NotNull // @Property(name = "username") // public String username; // // @NotNull // @Size(min = 3) // @Property(name = "password") // public String password; // } // // Path: website/src/main/java/app/api/user/LoginAJAXResponse.java // public class LoginAJAXResponse { // @NotNull // @Property(name = "success") // public Boolean success; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // // @Property(name = "errorMessage") // public String errorMessage; // } // // Path: website/src/main/java/app/web/Sessions.java // public final class Sessions { // private static final String USER = "LOGIN_USER"; // // public static boolean isUserLogin(Request request) { // return request.session().get(USER).isPresent(); // } // // public static LoginUser loginUser(Request request) { // String loginUser = request.session().get(USER).orElseThrow(() -> new UnauthorizedException("user not login")); // return JSON.fromJSON(LoginUser.class, loginUser); // } // // public static void setLoginUser(Request request, LoginUser user) { // request.session().set(USER, JSON.toJSON(user)); // } // } // // Path: website/src/main/java/app/web/session/LoginUser.java // public class LoginUser { // @Property(name = "userId") // public String userId; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // Path: website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java import app.api.AccountAJAXWebService; import app.api.user.CurrentUserAJAXResponse; import app.api.user.LoginAJAXRequest; import app.api.user.LoginAJAXResponse; import app.web.Sessions; import app.web.session.LoginUser; import core.framework.inject.Inject; import core.framework.web.WebContext; package app.web.controller; /** * @author neo */ public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { @Inject WebContext context; @Override
public LoginAJAXResponse login(LoginAJAXRequest request) {
neowu/frontend-demo-project
website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/user/CurrentUserAJAXResponse.java // public class CurrentUserAJAXResponse { // @NotNull // @Property(name = "loggedIn") // public Boolean loggedIn; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // // Path: website/src/main/java/app/api/user/LoginAJAXRequest.java // public class LoginAJAXRequest { // @NotNull // @Property(name = "username") // public String username; // // @NotNull // @Size(min = 3) // @Property(name = "password") // public String password; // } // // Path: website/src/main/java/app/api/user/LoginAJAXResponse.java // public class LoginAJAXResponse { // @NotNull // @Property(name = "success") // public Boolean success; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // // @Property(name = "errorMessage") // public String errorMessage; // } // // Path: website/src/main/java/app/web/Sessions.java // public final class Sessions { // private static final String USER = "LOGIN_USER"; // // public static boolean isUserLogin(Request request) { // return request.session().get(USER).isPresent(); // } // // public static LoginUser loginUser(Request request) { // String loginUser = request.session().get(USER).orElseThrow(() -> new UnauthorizedException("user not login")); // return JSON.fromJSON(LoginUser.class, loginUser); // } // // public static void setLoginUser(Request request, LoginUser user) { // request.session().set(USER, JSON.toJSON(user)); // } // } // // Path: website/src/main/java/app/web/session/LoginUser.java // public class LoginUser { // @Property(name = "userId") // public String userId; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // }
import app.api.AccountAJAXWebService; import app.api.user.CurrentUserAJAXResponse; import app.api.user.LoginAJAXRequest; import app.api.user.LoginAJAXResponse; import app.web.Sessions; import app.web.session.LoginUser; import core.framework.inject.Inject; import core.framework.web.WebContext;
package app.web.controller; /** * @author neo */ public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { @Inject WebContext context; @Override
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/user/CurrentUserAJAXResponse.java // public class CurrentUserAJAXResponse { // @NotNull // @Property(name = "loggedIn") // public Boolean loggedIn; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // // Path: website/src/main/java/app/api/user/LoginAJAXRequest.java // public class LoginAJAXRequest { // @NotNull // @Property(name = "username") // public String username; // // @NotNull // @Size(min = 3) // @Property(name = "password") // public String password; // } // // Path: website/src/main/java/app/api/user/LoginAJAXResponse.java // public class LoginAJAXResponse { // @NotNull // @Property(name = "success") // public Boolean success; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // // @Property(name = "errorMessage") // public String errorMessage; // } // // Path: website/src/main/java/app/web/Sessions.java // public final class Sessions { // private static final String USER = "LOGIN_USER"; // // public static boolean isUserLogin(Request request) { // return request.session().get(USER).isPresent(); // } // // public static LoginUser loginUser(Request request) { // String loginUser = request.session().get(USER).orElseThrow(() -> new UnauthorizedException("user not login")); // return JSON.fromJSON(LoginUser.class, loginUser); // } // // public static void setLoginUser(Request request, LoginUser user) { // request.session().set(USER, JSON.toJSON(user)); // } // } // // Path: website/src/main/java/app/web/session/LoginUser.java // public class LoginUser { // @Property(name = "userId") // public String userId; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // Path: website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java import app.api.AccountAJAXWebService; import app.api.user.CurrentUserAJAXResponse; import app.api.user.LoginAJAXRequest; import app.api.user.LoginAJAXResponse; import app.web.Sessions; import app.web.session.LoginUser; import core.framework.inject.Inject; import core.framework.web.WebContext; package app.web.controller; /** * @author neo */ public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { @Inject WebContext context; @Override
public LoginAJAXResponse login(LoginAJAXRequest request) {
neowu/frontend-demo-project
website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/user/CurrentUserAJAXResponse.java // public class CurrentUserAJAXResponse { // @NotNull // @Property(name = "loggedIn") // public Boolean loggedIn; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // // Path: website/src/main/java/app/api/user/LoginAJAXRequest.java // public class LoginAJAXRequest { // @NotNull // @Property(name = "username") // public String username; // // @NotNull // @Size(min = 3) // @Property(name = "password") // public String password; // } // // Path: website/src/main/java/app/api/user/LoginAJAXResponse.java // public class LoginAJAXResponse { // @NotNull // @Property(name = "success") // public Boolean success; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // // @Property(name = "errorMessage") // public String errorMessage; // } // // Path: website/src/main/java/app/web/Sessions.java // public final class Sessions { // private static final String USER = "LOGIN_USER"; // // public static boolean isUserLogin(Request request) { // return request.session().get(USER).isPresent(); // } // // public static LoginUser loginUser(Request request) { // String loginUser = request.session().get(USER).orElseThrow(() -> new UnauthorizedException("user not login")); // return JSON.fromJSON(LoginUser.class, loginUser); // } // // public static void setLoginUser(Request request, LoginUser user) { // request.session().set(USER, JSON.toJSON(user)); // } // } // // Path: website/src/main/java/app/web/session/LoginUser.java // public class LoginUser { // @Property(name = "userId") // public String userId; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // }
import app.api.AccountAJAXWebService; import app.api.user.CurrentUserAJAXResponse; import app.api.user.LoginAJAXRequest; import app.api.user.LoginAJAXResponse; import app.web.Sessions; import app.web.session.LoginUser; import core.framework.inject.Inject; import core.framework.web.WebContext;
package app.web.controller; /** * @author neo */ public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { @Inject WebContext context; @Override public LoginAJAXResponse login(LoginAJAXRequest request) { LoginAJAXResponse response = new LoginAJAXResponse(); if ("user".equals(request.username) && "123".equals(request.password)) {
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/user/CurrentUserAJAXResponse.java // public class CurrentUserAJAXResponse { // @NotNull // @Property(name = "loggedIn") // public Boolean loggedIn; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // // Path: website/src/main/java/app/api/user/LoginAJAXRequest.java // public class LoginAJAXRequest { // @NotNull // @Property(name = "username") // public String username; // // @NotNull // @Size(min = 3) // @Property(name = "password") // public String password; // } // // Path: website/src/main/java/app/api/user/LoginAJAXResponse.java // public class LoginAJAXResponse { // @NotNull // @Property(name = "success") // public Boolean success; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // // @Property(name = "errorMessage") // public String errorMessage; // } // // Path: website/src/main/java/app/web/Sessions.java // public final class Sessions { // private static final String USER = "LOGIN_USER"; // // public static boolean isUserLogin(Request request) { // return request.session().get(USER).isPresent(); // } // // public static LoginUser loginUser(Request request) { // String loginUser = request.session().get(USER).orElseThrow(() -> new UnauthorizedException("user not login")); // return JSON.fromJSON(LoginUser.class, loginUser); // } // // public static void setLoginUser(Request request, LoginUser user) { // request.session().set(USER, JSON.toJSON(user)); // } // } // // Path: website/src/main/java/app/web/session/LoginUser.java // public class LoginUser { // @Property(name = "userId") // public String userId; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // Path: website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java import app.api.AccountAJAXWebService; import app.api.user.CurrentUserAJAXResponse; import app.api.user.LoginAJAXRequest; import app.api.user.LoginAJAXResponse; import app.web.Sessions; import app.web.session.LoginUser; import core.framework.inject.Inject; import core.framework.web.WebContext; package app.web.controller; /** * @author neo */ public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { @Inject WebContext context; @Override public LoginAJAXResponse login(LoginAJAXRequest request) { LoginAJAXResponse response = new LoginAJAXResponse(); if ("user".equals(request.username) && "123".equals(request.password)) {
LoginUser loginUser = new LoginUser();
neowu/frontend-demo-project
website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/user/CurrentUserAJAXResponse.java // public class CurrentUserAJAXResponse { // @NotNull // @Property(name = "loggedIn") // public Boolean loggedIn; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // // Path: website/src/main/java/app/api/user/LoginAJAXRequest.java // public class LoginAJAXRequest { // @NotNull // @Property(name = "username") // public String username; // // @NotNull // @Size(min = 3) // @Property(name = "password") // public String password; // } // // Path: website/src/main/java/app/api/user/LoginAJAXResponse.java // public class LoginAJAXResponse { // @NotNull // @Property(name = "success") // public Boolean success; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // // @Property(name = "errorMessage") // public String errorMessage; // } // // Path: website/src/main/java/app/web/Sessions.java // public final class Sessions { // private static final String USER = "LOGIN_USER"; // // public static boolean isUserLogin(Request request) { // return request.session().get(USER).isPresent(); // } // // public static LoginUser loginUser(Request request) { // String loginUser = request.session().get(USER).orElseThrow(() -> new UnauthorizedException("user not login")); // return JSON.fromJSON(LoginUser.class, loginUser); // } // // public static void setLoginUser(Request request, LoginUser user) { // request.session().set(USER, JSON.toJSON(user)); // } // } // // Path: website/src/main/java/app/web/session/LoginUser.java // public class LoginUser { // @Property(name = "userId") // public String userId; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // }
import app.api.AccountAJAXWebService; import app.api.user.CurrentUserAJAXResponse; import app.api.user.LoginAJAXRequest; import app.api.user.LoginAJAXResponse; import app.web.Sessions; import app.web.session.LoginUser; import core.framework.inject.Inject; import core.framework.web.WebContext;
package app.web.controller; /** * @author neo */ public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { @Inject WebContext context; @Override public LoginAJAXResponse login(LoginAJAXRequest request) { LoginAJAXResponse response = new LoginAJAXResponse(); if ("user".equals(request.username) && "123".equals(request.password)) { LoginUser loginUser = new LoginUser(); loginUser.userId = "1"; loginUser.name = "user"; loginUser.role = "user";
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/user/CurrentUserAJAXResponse.java // public class CurrentUserAJAXResponse { // @NotNull // @Property(name = "loggedIn") // public Boolean loggedIn; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // // Path: website/src/main/java/app/api/user/LoginAJAXRequest.java // public class LoginAJAXRequest { // @NotNull // @Property(name = "username") // public String username; // // @NotNull // @Size(min = 3) // @Property(name = "password") // public String password; // } // // Path: website/src/main/java/app/api/user/LoginAJAXResponse.java // public class LoginAJAXResponse { // @NotNull // @Property(name = "success") // public Boolean success; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // // @Property(name = "errorMessage") // public String errorMessage; // } // // Path: website/src/main/java/app/web/Sessions.java // public final class Sessions { // private static final String USER = "LOGIN_USER"; // // public static boolean isUserLogin(Request request) { // return request.session().get(USER).isPresent(); // } // // public static LoginUser loginUser(Request request) { // String loginUser = request.session().get(USER).orElseThrow(() -> new UnauthorizedException("user not login")); // return JSON.fromJSON(LoginUser.class, loginUser); // } // // public static void setLoginUser(Request request, LoginUser user) { // request.session().set(USER, JSON.toJSON(user)); // } // } // // Path: website/src/main/java/app/web/session/LoginUser.java // public class LoginUser { // @Property(name = "userId") // public String userId; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // Path: website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java import app.api.AccountAJAXWebService; import app.api.user.CurrentUserAJAXResponse; import app.api.user.LoginAJAXRequest; import app.api.user.LoginAJAXResponse; import app.web.Sessions; import app.web.session.LoginUser; import core.framework.inject.Inject; import core.framework.web.WebContext; package app.web.controller; /** * @author neo */ public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { @Inject WebContext context; @Override public LoginAJAXResponse login(LoginAJAXRequest request) { LoginAJAXResponse response = new LoginAJAXResponse(); if ("user".equals(request.username) && "123".equals(request.password)) { LoginUser loginUser = new LoginUser(); loginUser.userId = "1"; loginUser.name = "user"; loginUser.role = "user";
Sessions.setLoginUser(context.request(), loginUser);
neowu/frontend-demo-project
website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/user/CurrentUserAJAXResponse.java // public class CurrentUserAJAXResponse { // @NotNull // @Property(name = "loggedIn") // public Boolean loggedIn; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // // Path: website/src/main/java/app/api/user/LoginAJAXRequest.java // public class LoginAJAXRequest { // @NotNull // @Property(name = "username") // public String username; // // @NotNull // @Size(min = 3) // @Property(name = "password") // public String password; // } // // Path: website/src/main/java/app/api/user/LoginAJAXResponse.java // public class LoginAJAXResponse { // @NotNull // @Property(name = "success") // public Boolean success; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // // @Property(name = "errorMessage") // public String errorMessage; // } // // Path: website/src/main/java/app/web/Sessions.java // public final class Sessions { // private static final String USER = "LOGIN_USER"; // // public static boolean isUserLogin(Request request) { // return request.session().get(USER).isPresent(); // } // // public static LoginUser loginUser(Request request) { // String loginUser = request.session().get(USER).orElseThrow(() -> new UnauthorizedException("user not login")); // return JSON.fromJSON(LoginUser.class, loginUser); // } // // public static void setLoginUser(Request request, LoginUser user) { // request.session().set(USER, JSON.toJSON(user)); // } // } // // Path: website/src/main/java/app/web/session/LoginUser.java // public class LoginUser { // @Property(name = "userId") // public String userId; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // }
import app.api.AccountAJAXWebService; import app.api.user.CurrentUserAJAXResponse; import app.api.user.LoginAJAXRequest; import app.api.user.LoginAJAXResponse; import app.web.Sessions; import app.web.session.LoginUser; import core.framework.inject.Inject; import core.framework.web.WebContext;
LoginUser loginUser = new LoginUser(); loginUser.userId = "1"; loginUser.name = "user"; loginUser.role = "user"; Sessions.setLoginUser(context.request(), loginUser); response.success = Boolean.TRUE; response.name = "user"; response.role = "user"; } else if ("admin".equals(request.username) && "123".equals(request.password)) { LoginUser loginUser = new LoginUser(); loginUser.userId = "2"; loginUser.name = "admin"; loginUser.role = "admin"; Sessions.setLoginUser(context.request(), loginUser); response.success = Boolean.TRUE; response.name = "admin"; response.role = "admin"; } else { response.success = Boolean.FALSE; response.errorMessage = "login failed"; } return response; } @Override public void logout() { context.request().session().invalidate(); } @Override
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/user/CurrentUserAJAXResponse.java // public class CurrentUserAJAXResponse { // @NotNull // @Property(name = "loggedIn") // public Boolean loggedIn; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // // Path: website/src/main/java/app/api/user/LoginAJAXRequest.java // public class LoginAJAXRequest { // @NotNull // @Property(name = "username") // public String username; // // @NotNull // @Size(min = 3) // @Property(name = "password") // public String password; // } // // Path: website/src/main/java/app/api/user/LoginAJAXResponse.java // public class LoginAJAXResponse { // @NotNull // @Property(name = "success") // public Boolean success; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // // @Property(name = "errorMessage") // public String errorMessage; // } // // Path: website/src/main/java/app/web/Sessions.java // public final class Sessions { // private static final String USER = "LOGIN_USER"; // // public static boolean isUserLogin(Request request) { // return request.session().get(USER).isPresent(); // } // // public static LoginUser loginUser(Request request) { // String loginUser = request.session().get(USER).orElseThrow(() -> new UnauthorizedException("user not login")); // return JSON.fromJSON(LoginUser.class, loginUser); // } // // public static void setLoginUser(Request request, LoginUser user) { // request.session().set(USER, JSON.toJSON(user)); // } // } // // Path: website/src/main/java/app/web/session/LoginUser.java // public class LoginUser { // @Property(name = "userId") // public String userId; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // Path: website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java import app.api.AccountAJAXWebService; import app.api.user.CurrentUserAJAXResponse; import app.api.user.LoginAJAXRequest; import app.api.user.LoginAJAXResponse; import app.web.Sessions; import app.web.session.LoginUser; import core.framework.inject.Inject; import core.framework.web.WebContext; LoginUser loginUser = new LoginUser(); loginUser.userId = "1"; loginUser.name = "user"; loginUser.role = "user"; Sessions.setLoginUser(context.request(), loginUser); response.success = Boolean.TRUE; response.name = "user"; response.role = "user"; } else if ("admin".equals(request.username) && "123".equals(request.password)) { LoginUser loginUser = new LoginUser(); loginUser.userId = "2"; loginUser.name = "admin"; loginUser.role = "admin"; Sessions.setLoginUser(context.request(), loginUser); response.success = Boolean.TRUE; response.name = "admin"; response.role = "admin"; } else { response.success = Boolean.FALSE; response.errorMessage = "login failed"; } return response; } @Override public void logout() { context.request().session().invalidate(); } @Override
public CurrentUserAJAXResponse currentUser() {
neowu/frontend-demo-project
website/src/main/java/app/WebModule.java
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/ProductAJAXWebService.java // public interface ProductAJAXWebService { // @GET // @Path("/ajax/product") // ListProductResponse list(); // // @GET // @Path("/ajax/product/create-config") // CreateProductConfigResponse createConfig(); // // @GET // @Path("/ajax/product/:id") // GetProductResponse get(@PathParam("id") String id); // // @GET // @Path("/ajax/product/:id/child/:childId") // GetProductResponse getChild(@PathParam("id") String id, @PathParam("childId") String childId); // } // // Path: website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java // public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { // @Inject // WebContext context; // // @Override // public LoginAJAXResponse login(LoginAJAXRequest request) { // LoginAJAXResponse response = new LoginAJAXResponse(); // if ("user".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "1"; // loginUser.name = "user"; // loginUser.role = "user"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "user"; // response.role = "user"; // } else if ("admin".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "2"; // loginUser.name = "admin"; // loginUser.role = "admin"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "admin"; // response.role = "admin"; // } else { // response.success = Boolean.FALSE; // response.errorMessage = "login failed"; // } // return response; // } // // @Override // public void logout() { // context.request().session().invalidate(); // } // // @Override // public CurrentUserAJAXResponse currentUser() { // CurrentUserAJAXResponse response = new CurrentUserAJAXResponse(); // if (Sessions.isUserLogin(context.request())) { // LoginUser loginUser = Sessions.loginUser(context.request()); // response.loggedIn = Boolean.TRUE; // response.name = loginUser.name; // response.role = loginUser.role; // } else { // response.loggedIn = Boolean.FALSE; // } // return response; // } // } // // Path: website/src/main/java/app/web/controller/HomeController.java // public class HomeController { // @Inject // WebDirectory webDirectory; // // public Response home(Request request) { // if (request.path().startsWith("/ajax/")) throw new NotFoundException("not found"); // // return Response.file(webDirectory.path("/index.html")).contentType(ContentType.TEXT_HTML); // } // } // // Path: website/src/main/java/app/web/controller/ProductAJAXWebServiceImpl.java // public class ProductAJAXWebServiceImpl implements ProductAJAXWebService { // @Override // public ListProductResponse list() { // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // throw new Error(e); // } // return new ListProductResponse(); // } // // @Override // public CreateProductConfigResponse createConfig() { // CreateProductConfigResponse response = new CreateProductConfigResponse(); // response.types = Lists.newArrayList(); // response.types.add(type("type1", "1")); // response.types.add(type("type2", "2")); // return response; // } // // @Override // public GetProductResponse get(String id) { // return new GetProductResponse(); // } // // @Override // public GetProductResponse getChild(String id, String childId) { // return new GetProductResponse(); // } // // private CreateProductConfigResponse.ProductType type(String name, String value) { // CreateProductConfigResponse.ProductType type = new CreateProductConfigResponse.ProductType(); // type.name = name; // type.value = value; // return type; // } // } // // Path: website/src/main/java/app/web/interceptor/LoginInterceptor.java // public class LoginInterceptor implements Interceptor { // @Override // public Response intercept(Invocation invocation) throws Exception { // if (invocation.annotation(LoginRequired.class) != null) { // WebContext context = invocation.context(); // Request request = context.request(); // Sessions.loginUser(request); // } // // // later we may need auto login by token (aka, remember me) // return invocation.proceed(); // } // }
import app.api.AccountAJAXWebService; import app.api.ProductAJAXWebService; import app.web.controller.AccountAJAXWebServiceImpl; import app.web.controller.HomeController; import app.web.controller.ProductAJAXWebServiceImpl; import app.web.interceptor.LoginInterceptor; import core.framework.http.HTTPMethod; import core.framework.module.Module;
package app; /** * @author neo */ public class WebModule extends Module { @Override protected void initialize() {
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/ProductAJAXWebService.java // public interface ProductAJAXWebService { // @GET // @Path("/ajax/product") // ListProductResponse list(); // // @GET // @Path("/ajax/product/create-config") // CreateProductConfigResponse createConfig(); // // @GET // @Path("/ajax/product/:id") // GetProductResponse get(@PathParam("id") String id); // // @GET // @Path("/ajax/product/:id/child/:childId") // GetProductResponse getChild(@PathParam("id") String id, @PathParam("childId") String childId); // } // // Path: website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java // public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { // @Inject // WebContext context; // // @Override // public LoginAJAXResponse login(LoginAJAXRequest request) { // LoginAJAXResponse response = new LoginAJAXResponse(); // if ("user".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "1"; // loginUser.name = "user"; // loginUser.role = "user"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "user"; // response.role = "user"; // } else if ("admin".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "2"; // loginUser.name = "admin"; // loginUser.role = "admin"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "admin"; // response.role = "admin"; // } else { // response.success = Boolean.FALSE; // response.errorMessage = "login failed"; // } // return response; // } // // @Override // public void logout() { // context.request().session().invalidate(); // } // // @Override // public CurrentUserAJAXResponse currentUser() { // CurrentUserAJAXResponse response = new CurrentUserAJAXResponse(); // if (Sessions.isUserLogin(context.request())) { // LoginUser loginUser = Sessions.loginUser(context.request()); // response.loggedIn = Boolean.TRUE; // response.name = loginUser.name; // response.role = loginUser.role; // } else { // response.loggedIn = Boolean.FALSE; // } // return response; // } // } // // Path: website/src/main/java/app/web/controller/HomeController.java // public class HomeController { // @Inject // WebDirectory webDirectory; // // public Response home(Request request) { // if (request.path().startsWith("/ajax/")) throw new NotFoundException("not found"); // // return Response.file(webDirectory.path("/index.html")).contentType(ContentType.TEXT_HTML); // } // } // // Path: website/src/main/java/app/web/controller/ProductAJAXWebServiceImpl.java // public class ProductAJAXWebServiceImpl implements ProductAJAXWebService { // @Override // public ListProductResponse list() { // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // throw new Error(e); // } // return new ListProductResponse(); // } // // @Override // public CreateProductConfigResponse createConfig() { // CreateProductConfigResponse response = new CreateProductConfigResponse(); // response.types = Lists.newArrayList(); // response.types.add(type("type1", "1")); // response.types.add(type("type2", "2")); // return response; // } // // @Override // public GetProductResponse get(String id) { // return new GetProductResponse(); // } // // @Override // public GetProductResponse getChild(String id, String childId) { // return new GetProductResponse(); // } // // private CreateProductConfigResponse.ProductType type(String name, String value) { // CreateProductConfigResponse.ProductType type = new CreateProductConfigResponse.ProductType(); // type.name = name; // type.value = value; // return type; // } // } // // Path: website/src/main/java/app/web/interceptor/LoginInterceptor.java // public class LoginInterceptor implements Interceptor { // @Override // public Response intercept(Invocation invocation) throws Exception { // if (invocation.annotation(LoginRequired.class) != null) { // WebContext context = invocation.context(); // Request request = context.request(); // Sessions.loginUser(request); // } // // // later we may need auto login by token (aka, remember me) // return invocation.proceed(); // } // } // Path: website/src/main/java/app/WebModule.java import app.api.AccountAJAXWebService; import app.api.ProductAJAXWebService; import app.web.controller.AccountAJAXWebServiceImpl; import app.web.controller.HomeController; import app.web.controller.ProductAJAXWebServiceImpl; import app.web.interceptor.LoginInterceptor; import core.framework.http.HTTPMethod; import core.framework.module.Module; package app; /** * @author neo */ public class WebModule extends Module { @Override protected void initialize() {
http().intercept(bind(LoginInterceptor.class));
neowu/frontend-demo-project
website/src/main/java/app/WebModule.java
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/ProductAJAXWebService.java // public interface ProductAJAXWebService { // @GET // @Path("/ajax/product") // ListProductResponse list(); // // @GET // @Path("/ajax/product/create-config") // CreateProductConfigResponse createConfig(); // // @GET // @Path("/ajax/product/:id") // GetProductResponse get(@PathParam("id") String id); // // @GET // @Path("/ajax/product/:id/child/:childId") // GetProductResponse getChild(@PathParam("id") String id, @PathParam("childId") String childId); // } // // Path: website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java // public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { // @Inject // WebContext context; // // @Override // public LoginAJAXResponse login(LoginAJAXRequest request) { // LoginAJAXResponse response = new LoginAJAXResponse(); // if ("user".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "1"; // loginUser.name = "user"; // loginUser.role = "user"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "user"; // response.role = "user"; // } else if ("admin".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "2"; // loginUser.name = "admin"; // loginUser.role = "admin"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "admin"; // response.role = "admin"; // } else { // response.success = Boolean.FALSE; // response.errorMessage = "login failed"; // } // return response; // } // // @Override // public void logout() { // context.request().session().invalidate(); // } // // @Override // public CurrentUserAJAXResponse currentUser() { // CurrentUserAJAXResponse response = new CurrentUserAJAXResponse(); // if (Sessions.isUserLogin(context.request())) { // LoginUser loginUser = Sessions.loginUser(context.request()); // response.loggedIn = Boolean.TRUE; // response.name = loginUser.name; // response.role = loginUser.role; // } else { // response.loggedIn = Boolean.FALSE; // } // return response; // } // } // // Path: website/src/main/java/app/web/controller/HomeController.java // public class HomeController { // @Inject // WebDirectory webDirectory; // // public Response home(Request request) { // if (request.path().startsWith("/ajax/")) throw new NotFoundException("not found"); // // return Response.file(webDirectory.path("/index.html")).contentType(ContentType.TEXT_HTML); // } // } // // Path: website/src/main/java/app/web/controller/ProductAJAXWebServiceImpl.java // public class ProductAJAXWebServiceImpl implements ProductAJAXWebService { // @Override // public ListProductResponse list() { // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // throw new Error(e); // } // return new ListProductResponse(); // } // // @Override // public CreateProductConfigResponse createConfig() { // CreateProductConfigResponse response = new CreateProductConfigResponse(); // response.types = Lists.newArrayList(); // response.types.add(type("type1", "1")); // response.types.add(type("type2", "2")); // return response; // } // // @Override // public GetProductResponse get(String id) { // return new GetProductResponse(); // } // // @Override // public GetProductResponse getChild(String id, String childId) { // return new GetProductResponse(); // } // // private CreateProductConfigResponse.ProductType type(String name, String value) { // CreateProductConfigResponse.ProductType type = new CreateProductConfigResponse.ProductType(); // type.name = name; // type.value = value; // return type; // } // } // // Path: website/src/main/java/app/web/interceptor/LoginInterceptor.java // public class LoginInterceptor implements Interceptor { // @Override // public Response intercept(Invocation invocation) throws Exception { // if (invocation.annotation(LoginRequired.class) != null) { // WebContext context = invocation.context(); // Request request = context.request(); // Sessions.loginUser(request); // } // // // later we may need auto login by token (aka, remember me) // return invocation.proceed(); // } // }
import app.api.AccountAJAXWebService; import app.api.ProductAJAXWebService; import app.web.controller.AccountAJAXWebServiceImpl; import app.web.controller.HomeController; import app.web.controller.ProductAJAXWebServiceImpl; import app.web.interceptor.LoginInterceptor; import core.framework.http.HTTPMethod; import core.framework.module.Module;
package app; /** * @author neo */ public class WebModule extends Module { @Override protected void initialize() { http().intercept(bind(LoginInterceptor.class)); site().staticContent("/static"); site().staticContent("/robots.txt");
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/ProductAJAXWebService.java // public interface ProductAJAXWebService { // @GET // @Path("/ajax/product") // ListProductResponse list(); // // @GET // @Path("/ajax/product/create-config") // CreateProductConfigResponse createConfig(); // // @GET // @Path("/ajax/product/:id") // GetProductResponse get(@PathParam("id") String id); // // @GET // @Path("/ajax/product/:id/child/:childId") // GetProductResponse getChild(@PathParam("id") String id, @PathParam("childId") String childId); // } // // Path: website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java // public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { // @Inject // WebContext context; // // @Override // public LoginAJAXResponse login(LoginAJAXRequest request) { // LoginAJAXResponse response = new LoginAJAXResponse(); // if ("user".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "1"; // loginUser.name = "user"; // loginUser.role = "user"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "user"; // response.role = "user"; // } else if ("admin".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "2"; // loginUser.name = "admin"; // loginUser.role = "admin"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "admin"; // response.role = "admin"; // } else { // response.success = Boolean.FALSE; // response.errorMessage = "login failed"; // } // return response; // } // // @Override // public void logout() { // context.request().session().invalidate(); // } // // @Override // public CurrentUserAJAXResponse currentUser() { // CurrentUserAJAXResponse response = new CurrentUserAJAXResponse(); // if (Sessions.isUserLogin(context.request())) { // LoginUser loginUser = Sessions.loginUser(context.request()); // response.loggedIn = Boolean.TRUE; // response.name = loginUser.name; // response.role = loginUser.role; // } else { // response.loggedIn = Boolean.FALSE; // } // return response; // } // } // // Path: website/src/main/java/app/web/controller/HomeController.java // public class HomeController { // @Inject // WebDirectory webDirectory; // // public Response home(Request request) { // if (request.path().startsWith("/ajax/")) throw new NotFoundException("not found"); // // return Response.file(webDirectory.path("/index.html")).contentType(ContentType.TEXT_HTML); // } // } // // Path: website/src/main/java/app/web/controller/ProductAJAXWebServiceImpl.java // public class ProductAJAXWebServiceImpl implements ProductAJAXWebService { // @Override // public ListProductResponse list() { // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // throw new Error(e); // } // return new ListProductResponse(); // } // // @Override // public CreateProductConfigResponse createConfig() { // CreateProductConfigResponse response = new CreateProductConfigResponse(); // response.types = Lists.newArrayList(); // response.types.add(type("type1", "1")); // response.types.add(type("type2", "2")); // return response; // } // // @Override // public GetProductResponse get(String id) { // return new GetProductResponse(); // } // // @Override // public GetProductResponse getChild(String id, String childId) { // return new GetProductResponse(); // } // // private CreateProductConfigResponse.ProductType type(String name, String value) { // CreateProductConfigResponse.ProductType type = new CreateProductConfigResponse.ProductType(); // type.name = name; // type.value = value; // return type; // } // } // // Path: website/src/main/java/app/web/interceptor/LoginInterceptor.java // public class LoginInterceptor implements Interceptor { // @Override // public Response intercept(Invocation invocation) throws Exception { // if (invocation.annotation(LoginRequired.class) != null) { // WebContext context = invocation.context(); // Request request = context.request(); // Sessions.loginUser(request); // } // // // later we may need auto login by token (aka, remember me) // return invocation.proceed(); // } // } // Path: website/src/main/java/app/WebModule.java import app.api.AccountAJAXWebService; import app.api.ProductAJAXWebService; import app.web.controller.AccountAJAXWebServiceImpl; import app.web.controller.HomeController; import app.web.controller.ProductAJAXWebServiceImpl; import app.web.interceptor.LoginInterceptor; import core.framework.http.HTTPMethod; import core.framework.module.Module; package app; /** * @author neo */ public class WebModule extends Module { @Override protected void initialize() { http().intercept(bind(LoginInterceptor.class)); site().staticContent("/static"); site().staticContent("/robots.txt");
HomeController homeController = bind(HomeController.class);
neowu/frontend-demo-project
website/src/main/java/app/WebModule.java
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/ProductAJAXWebService.java // public interface ProductAJAXWebService { // @GET // @Path("/ajax/product") // ListProductResponse list(); // // @GET // @Path("/ajax/product/create-config") // CreateProductConfigResponse createConfig(); // // @GET // @Path("/ajax/product/:id") // GetProductResponse get(@PathParam("id") String id); // // @GET // @Path("/ajax/product/:id/child/:childId") // GetProductResponse getChild(@PathParam("id") String id, @PathParam("childId") String childId); // } // // Path: website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java // public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { // @Inject // WebContext context; // // @Override // public LoginAJAXResponse login(LoginAJAXRequest request) { // LoginAJAXResponse response = new LoginAJAXResponse(); // if ("user".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "1"; // loginUser.name = "user"; // loginUser.role = "user"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "user"; // response.role = "user"; // } else if ("admin".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "2"; // loginUser.name = "admin"; // loginUser.role = "admin"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "admin"; // response.role = "admin"; // } else { // response.success = Boolean.FALSE; // response.errorMessage = "login failed"; // } // return response; // } // // @Override // public void logout() { // context.request().session().invalidate(); // } // // @Override // public CurrentUserAJAXResponse currentUser() { // CurrentUserAJAXResponse response = new CurrentUserAJAXResponse(); // if (Sessions.isUserLogin(context.request())) { // LoginUser loginUser = Sessions.loginUser(context.request()); // response.loggedIn = Boolean.TRUE; // response.name = loginUser.name; // response.role = loginUser.role; // } else { // response.loggedIn = Boolean.FALSE; // } // return response; // } // } // // Path: website/src/main/java/app/web/controller/HomeController.java // public class HomeController { // @Inject // WebDirectory webDirectory; // // public Response home(Request request) { // if (request.path().startsWith("/ajax/")) throw new NotFoundException("not found"); // // return Response.file(webDirectory.path("/index.html")).contentType(ContentType.TEXT_HTML); // } // } // // Path: website/src/main/java/app/web/controller/ProductAJAXWebServiceImpl.java // public class ProductAJAXWebServiceImpl implements ProductAJAXWebService { // @Override // public ListProductResponse list() { // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // throw new Error(e); // } // return new ListProductResponse(); // } // // @Override // public CreateProductConfigResponse createConfig() { // CreateProductConfigResponse response = new CreateProductConfigResponse(); // response.types = Lists.newArrayList(); // response.types.add(type("type1", "1")); // response.types.add(type("type2", "2")); // return response; // } // // @Override // public GetProductResponse get(String id) { // return new GetProductResponse(); // } // // @Override // public GetProductResponse getChild(String id, String childId) { // return new GetProductResponse(); // } // // private CreateProductConfigResponse.ProductType type(String name, String value) { // CreateProductConfigResponse.ProductType type = new CreateProductConfigResponse.ProductType(); // type.name = name; // type.value = value; // return type; // } // } // // Path: website/src/main/java/app/web/interceptor/LoginInterceptor.java // public class LoginInterceptor implements Interceptor { // @Override // public Response intercept(Invocation invocation) throws Exception { // if (invocation.annotation(LoginRequired.class) != null) { // WebContext context = invocation.context(); // Request request = context.request(); // Sessions.loginUser(request); // } // // // later we may need auto login by token (aka, remember me) // return invocation.proceed(); // } // }
import app.api.AccountAJAXWebService; import app.api.ProductAJAXWebService; import app.web.controller.AccountAJAXWebServiceImpl; import app.web.controller.HomeController; import app.web.controller.ProductAJAXWebServiceImpl; import app.web.interceptor.LoginInterceptor; import core.framework.http.HTTPMethod; import core.framework.module.Module;
package app; /** * @author neo */ public class WebModule extends Module { @Override protected void initialize() { http().intercept(bind(LoginInterceptor.class)); site().staticContent("/static"); site().staticContent("/robots.txt"); HomeController homeController = bind(HomeController.class); http().route(HTTPMethod.GET, "/", homeController::home); http().route(HTTPMethod.GET, "/:path(*)", homeController::home);
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/ProductAJAXWebService.java // public interface ProductAJAXWebService { // @GET // @Path("/ajax/product") // ListProductResponse list(); // // @GET // @Path("/ajax/product/create-config") // CreateProductConfigResponse createConfig(); // // @GET // @Path("/ajax/product/:id") // GetProductResponse get(@PathParam("id") String id); // // @GET // @Path("/ajax/product/:id/child/:childId") // GetProductResponse getChild(@PathParam("id") String id, @PathParam("childId") String childId); // } // // Path: website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java // public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { // @Inject // WebContext context; // // @Override // public LoginAJAXResponse login(LoginAJAXRequest request) { // LoginAJAXResponse response = new LoginAJAXResponse(); // if ("user".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "1"; // loginUser.name = "user"; // loginUser.role = "user"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "user"; // response.role = "user"; // } else if ("admin".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "2"; // loginUser.name = "admin"; // loginUser.role = "admin"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "admin"; // response.role = "admin"; // } else { // response.success = Boolean.FALSE; // response.errorMessage = "login failed"; // } // return response; // } // // @Override // public void logout() { // context.request().session().invalidate(); // } // // @Override // public CurrentUserAJAXResponse currentUser() { // CurrentUserAJAXResponse response = new CurrentUserAJAXResponse(); // if (Sessions.isUserLogin(context.request())) { // LoginUser loginUser = Sessions.loginUser(context.request()); // response.loggedIn = Boolean.TRUE; // response.name = loginUser.name; // response.role = loginUser.role; // } else { // response.loggedIn = Boolean.FALSE; // } // return response; // } // } // // Path: website/src/main/java/app/web/controller/HomeController.java // public class HomeController { // @Inject // WebDirectory webDirectory; // // public Response home(Request request) { // if (request.path().startsWith("/ajax/")) throw new NotFoundException("not found"); // // return Response.file(webDirectory.path("/index.html")).contentType(ContentType.TEXT_HTML); // } // } // // Path: website/src/main/java/app/web/controller/ProductAJAXWebServiceImpl.java // public class ProductAJAXWebServiceImpl implements ProductAJAXWebService { // @Override // public ListProductResponse list() { // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // throw new Error(e); // } // return new ListProductResponse(); // } // // @Override // public CreateProductConfigResponse createConfig() { // CreateProductConfigResponse response = new CreateProductConfigResponse(); // response.types = Lists.newArrayList(); // response.types.add(type("type1", "1")); // response.types.add(type("type2", "2")); // return response; // } // // @Override // public GetProductResponse get(String id) { // return new GetProductResponse(); // } // // @Override // public GetProductResponse getChild(String id, String childId) { // return new GetProductResponse(); // } // // private CreateProductConfigResponse.ProductType type(String name, String value) { // CreateProductConfigResponse.ProductType type = new CreateProductConfigResponse.ProductType(); // type.name = name; // type.value = value; // return type; // } // } // // Path: website/src/main/java/app/web/interceptor/LoginInterceptor.java // public class LoginInterceptor implements Interceptor { // @Override // public Response intercept(Invocation invocation) throws Exception { // if (invocation.annotation(LoginRequired.class) != null) { // WebContext context = invocation.context(); // Request request = context.request(); // Sessions.loginUser(request); // } // // // later we may need auto login by token (aka, remember me) // return invocation.proceed(); // } // } // Path: website/src/main/java/app/WebModule.java import app.api.AccountAJAXWebService; import app.api.ProductAJAXWebService; import app.web.controller.AccountAJAXWebServiceImpl; import app.web.controller.HomeController; import app.web.controller.ProductAJAXWebServiceImpl; import app.web.interceptor.LoginInterceptor; import core.framework.http.HTTPMethod; import core.framework.module.Module; package app; /** * @author neo */ public class WebModule extends Module { @Override protected void initialize() { http().intercept(bind(LoginInterceptor.class)); site().staticContent("/static"); site().staticContent("/robots.txt"); HomeController homeController = bind(HomeController.class); http().route(HTTPMethod.GET, "/", homeController::home); http().route(HTTPMethod.GET, "/:path(*)", homeController::home);
api().service(AccountAJAXWebService.class, bind(AccountAJAXWebServiceImpl.class));
neowu/frontend-demo-project
website/src/main/java/app/WebModule.java
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/ProductAJAXWebService.java // public interface ProductAJAXWebService { // @GET // @Path("/ajax/product") // ListProductResponse list(); // // @GET // @Path("/ajax/product/create-config") // CreateProductConfigResponse createConfig(); // // @GET // @Path("/ajax/product/:id") // GetProductResponse get(@PathParam("id") String id); // // @GET // @Path("/ajax/product/:id/child/:childId") // GetProductResponse getChild(@PathParam("id") String id, @PathParam("childId") String childId); // } // // Path: website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java // public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { // @Inject // WebContext context; // // @Override // public LoginAJAXResponse login(LoginAJAXRequest request) { // LoginAJAXResponse response = new LoginAJAXResponse(); // if ("user".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "1"; // loginUser.name = "user"; // loginUser.role = "user"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "user"; // response.role = "user"; // } else if ("admin".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "2"; // loginUser.name = "admin"; // loginUser.role = "admin"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "admin"; // response.role = "admin"; // } else { // response.success = Boolean.FALSE; // response.errorMessage = "login failed"; // } // return response; // } // // @Override // public void logout() { // context.request().session().invalidate(); // } // // @Override // public CurrentUserAJAXResponse currentUser() { // CurrentUserAJAXResponse response = new CurrentUserAJAXResponse(); // if (Sessions.isUserLogin(context.request())) { // LoginUser loginUser = Sessions.loginUser(context.request()); // response.loggedIn = Boolean.TRUE; // response.name = loginUser.name; // response.role = loginUser.role; // } else { // response.loggedIn = Boolean.FALSE; // } // return response; // } // } // // Path: website/src/main/java/app/web/controller/HomeController.java // public class HomeController { // @Inject // WebDirectory webDirectory; // // public Response home(Request request) { // if (request.path().startsWith("/ajax/")) throw new NotFoundException("not found"); // // return Response.file(webDirectory.path("/index.html")).contentType(ContentType.TEXT_HTML); // } // } // // Path: website/src/main/java/app/web/controller/ProductAJAXWebServiceImpl.java // public class ProductAJAXWebServiceImpl implements ProductAJAXWebService { // @Override // public ListProductResponse list() { // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // throw new Error(e); // } // return new ListProductResponse(); // } // // @Override // public CreateProductConfigResponse createConfig() { // CreateProductConfigResponse response = new CreateProductConfigResponse(); // response.types = Lists.newArrayList(); // response.types.add(type("type1", "1")); // response.types.add(type("type2", "2")); // return response; // } // // @Override // public GetProductResponse get(String id) { // return new GetProductResponse(); // } // // @Override // public GetProductResponse getChild(String id, String childId) { // return new GetProductResponse(); // } // // private CreateProductConfigResponse.ProductType type(String name, String value) { // CreateProductConfigResponse.ProductType type = new CreateProductConfigResponse.ProductType(); // type.name = name; // type.value = value; // return type; // } // } // // Path: website/src/main/java/app/web/interceptor/LoginInterceptor.java // public class LoginInterceptor implements Interceptor { // @Override // public Response intercept(Invocation invocation) throws Exception { // if (invocation.annotation(LoginRequired.class) != null) { // WebContext context = invocation.context(); // Request request = context.request(); // Sessions.loginUser(request); // } // // // later we may need auto login by token (aka, remember me) // return invocation.proceed(); // } // }
import app.api.AccountAJAXWebService; import app.api.ProductAJAXWebService; import app.web.controller.AccountAJAXWebServiceImpl; import app.web.controller.HomeController; import app.web.controller.ProductAJAXWebServiceImpl; import app.web.interceptor.LoginInterceptor; import core.framework.http.HTTPMethod; import core.framework.module.Module;
package app; /** * @author neo */ public class WebModule extends Module { @Override protected void initialize() { http().intercept(bind(LoginInterceptor.class)); site().staticContent("/static"); site().staticContent("/robots.txt"); HomeController homeController = bind(HomeController.class); http().route(HTTPMethod.GET, "/", homeController::home); http().route(HTTPMethod.GET, "/:path(*)", homeController::home);
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/ProductAJAXWebService.java // public interface ProductAJAXWebService { // @GET // @Path("/ajax/product") // ListProductResponse list(); // // @GET // @Path("/ajax/product/create-config") // CreateProductConfigResponse createConfig(); // // @GET // @Path("/ajax/product/:id") // GetProductResponse get(@PathParam("id") String id); // // @GET // @Path("/ajax/product/:id/child/:childId") // GetProductResponse getChild(@PathParam("id") String id, @PathParam("childId") String childId); // } // // Path: website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java // public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { // @Inject // WebContext context; // // @Override // public LoginAJAXResponse login(LoginAJAXRequest request) { // LoginAJAXResponse response = new LoginAJAXResponse(); // if ("user".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "1"; // loginUser.name = "user"; // loginUser.role = "user"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "user"; // response.role = "user"; // } else if ("admin".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "2"; // loginUser.name = "admin"; // loginUser.role = "admin"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "admin"; // response.role = "admin"; // } else { // response.success = Boolean.FALSE; // response.errorMessage = "login failed"; // } // return response; // } // // @Override // public void logout() { // context.request().session().invalidate(); // } // // @Override // public CurrentUserAJAXResponse currentUser() { // CurrentUserAJAXResponse response = new CurrentUserAJAXResponse(); // if (Sessions.isUserLogin(context.request())) { // LoginUser loginUser = Sessions.loginUser(context.request()); // response.loggedIn = Boolean.TRUE; // response.name = loginUser.name; // response.role = loginUser.role; // } else { // response.loggedIn = Boolean.FALSE; // } // return response; // } // } // // Path: website/src/main/java/app/web/controller/HomeController.java // public class HomeController { // @Inject // WebDirectory webDirectory; // // public Response home(Request request) { // if (request.path().startsWith("/ajax/")) throw new NotFoundException("not found"); // // return Response.file(webDirectory.path("/index.html")).contentType(ContentType.TEXT_HTML); // } // } // // Path: website/src/main/java/app/web/controller/ProductAJAXWebServiceImpl.java // public class ProductAJAXWebServiceImpl implements ProductAJAXWebService { // @Override // public ListProductResponse list() { // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // throw new Error(e); // } // return new ListProductResponse(); // } // // @Override // public CreateProductConfigResponse createConfig() { // CreateProductConfigResponse response = new CreateProductConfigResponse(); // response.types = Lists.newArrayList(); // response.types.add(type("type1", "1")); // response.types.add(type("type2", "2")); // return response; // } // // @Override // public GetProductResponse get(String id) { // return new GetProductResponse(); // } // // @Override // public GetProductResponse getChild(String id, String childId) { // return new GetProductResponse(); // } // // private CreateProductConfigResponse.ProductType type(String name, String value) { // CreateProductConfigResponse.ProductType type = new CreateProductConfigResponse.ProductType(); // type.name = name; // type.value = value; // return type; // } // } // // Path: website/src/main/java/app/web/interceptor/LoginInterceptor.java // public class LoginInterceptor implements Interceptor { // @Override // public Response intercept(Invocation invocation) throws Exception { // if (invocation.annotation(LoginRequired.class) != null) { // WebContext context = invocation.context(); // Request request = context.request(); // Sessions.loginUser(request); // } // // // later we may need auto login by token (aka, remember me) // return invocation.proceed(); // } // } // Path: website/src/main/java/app/WebModule.java import app.api.AccountAJAXWebService; import app.api.ProductAJAXWebService; import app.web.controller.AccountAJAXWebServiceImpl; import app.web.controller.HomeController; import app.web.controller.ProductAJAXWebServiceImpl; import app.web.interceptor.LoginInterceptor; import core.framework.http.HTTPMethod; import core.framework.module.Module; package app; /** * @author neo */ public class WebModule extends Module { @Override protected void initialize() { http().intercept(bind(LoginInterceptor.class)); site().staticContent("/static"); site().staticContent("/robots.txt"); HomeController homeController = bind(HomeController.class); http().route(HTTPMethod.GET, "/", homeController::home); http().route(HTTPMethod.GET, "/:path(*)", homeController::home);
api().service(AccountAJAXWebService.class, bind(AccountAJAXWebServiceImpl.class));
neowu/frontend-demo-project
website/src/main/java/app/WebModule.java
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/ProductAJAXWebService.java // public interface ProductAJAXWebService { // @GET // @Path("/ajax/product") // ListProductResponse list(); // // @GET // @Path("/ajax/product/create-config") // CreateProductConfigResponse createConfig(); // // @GET // @Path("/ajax/product/:id") // GetProductResponse get(@PathParam("id") String id); // // @GET // @Path("/ajax/product/:id/child/:childId") // GetProductResponse getChild(@PathParam("id") String id, @PathParam("childId") String childId); // } // // Path: website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java // public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { // @Inject // WebContext context; // // @Override // public LoginAJAXResponse login(LoginAJAXRequest request) { // LoginAJAXResponse response = new LoginAJAXResponse(); // if ("user".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "1"; // loginUser.name = "user"; // loginUser.role = "user"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "user"; // response.role = "user"; // } else if ("admin".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "2"; // loginUser.name = "admin"; // loginUser.role = "admin"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "admin"; // response.role = "admin"; // } else { // response.success = Boolean.FALSE; // response.errorMessage = "login failed"; // } // return response; // } // // @Override // public void logout() { // context.request().session().invalidate(); // } // // @Override // public CurrentUserAJAXResponse currentUser() { // CurrentUserAJAXResponse response = new CurrentUserAJAXResponse(); // if (Sessions.isUserLogin(context.request())) { // LoginUser loginUser = Sessions.loginUser(context.request()); // response.loggedIn = Boolean.TRUE; // response.name = loginUser.name; // response.role = loginUser.role; // } else { // response.loggedIn = Boolean.FALSE; // } // return response; // } // } // // Path: website/src/main/java/app/web/controller/HomeController.java // public class HomeController { // @Inject // WebDirectory webDirectory; // // public Response home(Request request) { // if (request.path().startsWith("/ajax/")) throw new NotFoundException("not found"); // // return Response.file(webDirectory.path("/index.html")).contentType(ContentType.TEXT_HTML); // } // } // // Path: website/src/main/java/app/web/controller/ProductAJAXWebServiceImpl.java // public class ProductAJAXWebServiceImpl implements ProductAJAXWebService { // @Override // public ListProductResponse list() { // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // throw new Error(e); // } // return new ListProductResponse(); // } // // @Override // public CreateProductConfigResponse createConfig() { // CreateProductConfigResponse response = new CreateProductConfigResponse(); // response.types = Lists.newArrayList(); // response.types.add(type("type1", "1")); // response.types.add(type("type2", "2")); // return response; // } // // @Override // public GetProductResponse get(String id) { // return new GetProductResponse(); // } // // @Override // public GetProductResponse getChild(String id, String childId) { // return new GetProductResponse(); // } // // private CreateProductConfigResponse.ProductType type(String name, String value) { // CreateProductConfigResponse.ProductType type = new CreateProductConfigResponse.ProductType(); // type.name = name; // type.value = value; // return type; // } // } // // Path: website/src/main/java/app/web/interceptor/LoginInterceptor.java // public class LoginInterceptor implements Interceptor { // @Override // public Response intercept(Invocation invocation) throws Exception { // if (invocation.annotation(LoginRequired.class) != null) { // WebContext context = invocation.context(); // Request request = context.request(); // Sessions.loginUser(request); // } // // // later we may need auto login by token (aka, remember me) // return invocation.proceed(); // } // }
import app.api.AccountAJAXWebService; import app.api.ProductAJAXWebService; import app.web.controller.AccountAJAXWebServiceImpl; import app.web.controller.HomeController; import app.web.controller.ProductAJAXWebServiceImpl; import app.web.interceptor.LoginInterceptor; import core.framework.http.HTTPMethod; import core.framework.module.Module;
package app; /** * @author neo */ public class WebModule extends Module { @Override protected void initialize() { http().intercept(bind(LoginInterceptor.class)); site().staticContent("/static"); site().staticContent("/robots.txt"); HomeController homeController = bind(HomeController.class); http().route(HTTPMethod.GET, "/", homeController::home); http().route(HTTPMethod.GET, "/:path(*)", homeController::home); api().service(AccountAJAXWebService.class, bind(AccountAJAXWebServiceImpl.class));
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/ProductAJAXWebService.java // public interface ProductAJAXWebService { // @GET // @Path("/ajax/product") // ListProductResponse list(); // // @GET // @Path("/ajax/product/create-config") // CreateProductConfigResponse createConfig(); // // @GET // @Path("/ajax/product/:id") // GetProductResponse get(@PathParam("id") String id); // // @GET // @Path("/ajax/product/:id/child/:childId") // GetProductResponse getChild(@PathParam("id") String id, @PathParam("childId") String childId); // } // // Path: website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java // public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { // @Inject // WebContext context; // // @Override // public LoginAJAXResponse login(LoginAJAXRequest request) { // LoginAJAXResponse response = new LoginAJAXResponse(); // if ("user".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "1"; // loginUser.name = "user"; // loginUser.role = "user"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "user"; // response.role = "user"; // } else if ("admin".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "2"; // loginUser.name = "admin"; // loginUser.role = "admin"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "admin"; // response.role = "admin"; // } else { // response.success = Boolean.FALSE; // response.errorMessage = "login failed"; // } // return response; // } // // @Override // public void logout() { // context.request().session().invalidate(); // } // // @Override // public CurrentUserAJAXResponse currentUser() { // CurrentUserAJAXResponse response = new CurrentUserAJAXResponse(); // if (Sessions.isUserLogin(context.request())) { // LoginUser loginUser = Sessions.loginUser(context.request()); // response.loggedIn = Boolean.TRUE; // response.name = loginUser.name; // response.role = loginUser.role; // } else { // response.loggedIn = Boolean.FALSE; // } // return response; // } // } // // Path: website/src/main/java/app/web/controller/HomeController.java // public class HomeController { // @Inject // WebDirectory webDirectory; // // public Response home(Request request) { // if (request.path().startsWith("/ajax/")) throw new NotFoundException("not found"); // // return Response.file(webDirectory.path("/index.html")).contentType(ContentType.TEXT_HTML); // } // } // // Path: website/src/main/java/app/web/controller/ProductAJAXWebServiceImpl.java // public class ProductAJAXWebServiceImpl implements ProductAJAXWebService { // @Override // public ListProductResponse list() { // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // throw new Error(e); // } // return new ListProductResponse(); // } // // @Override // public CreateProductConfigResponse createConfig() { // CreateProductConfigResponse response = new CreateProductConfigResponse(); // response.types = Lists.newArrayList(); // response.types.add(type("type1", "1")); // response.types.add(type("type2", "2")); // return response; // } // // @Override // public GetProductResponse get(String id) { // return new GetProductResponse(); // } // // @Override // public GetProductResponse getChild(String id, String childId) { // return new GetProductResponse(); // } // // private CreateProductConfigResponse.ProductType type(String name, String value) { // CreateProductConfigResponse.ProductType type = new CreateProductConfigResponse.ProductType(); // type.name = name; // type.value = value; // return type; // } // } // // Path: website/src/main/java/app/web/interceptor/LoginInterceptor.java // public class LoginInterceptor implements Interceptor { // @Override // public Response intercept(Invocation invocation) throws Exception { // if (invocation.annotation(LoginRequired.class) != null) { // WebContext context = invocation.context(); // Request request = context.request(); // Sessions.loginUser(request); // } // // // later we may need auto login by token (aka, remember me) // return invocation.proceed(); // } // } // Path: website/src/main/java/app/WebModule.java import app.api.AccountAJAXWebService; import app.api.ProductAJAXWebService; import app.web.controller.AccountAJAXWebServiceImpl; import app.web.controller.HomeController; import app.web.controller.ProductAJAXWebServiceImpl; import app.web.interceptor.LoginInterceptor; import core.framework.http.HTTPMethod; import core.framework.module.Module; package app; /** * @author neo */ public class WebModule extends Module { @Override protected void initialize() { http().intercept(bind(LoginInterceptor.class)); site().staticContent("/static"); site().staticContent("/robots.txt"); HomeController homeController = bind(HomeController.class); http().route(HTTPMethod.GET, "/", homeController::home); http().route(HTTPMethod.GET, "/:path(*)", homeController::home); api().service(AccountAJAXWebService.class, bind(AccountAJAXWebServiceImpl.class));
api().service(ProductAJAXWebService.class, bind(ProductAJAXWebServiceImpl.class));
neowu/frontend-demo-project
website/src/main/java/app/WebModule.java
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/ProductAJAXWebService.java // public interface ProductAJAXWebService { // @GET // @Path("/ajax/product") // ListProductResponse list(); // // @GET // @Path("/ajax/product/create-config") // CreateProductConfigResponse createConfig(); // // @GET // @Path("/ajax/product/:id") // GetProductResponse get(@PathParam("id") String id); // // @GET // @Path("/ajax/product/:id/child/:childId") // GetProductResponse getChild(@PathParam("id") String id, @PathParam("childId") String childId); // } // // Path: website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java // public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { // @Inject // WebContext context; // // @Override // public LoginAJAXResponse login(LoginAJAXRequest request) { // LoginAJAXResponse response = new LoginAJAXResponse(); // if ("user".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "1"; // loginUser.name = "user"; // loginUser.role = "user"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "user"; // response.role = "user"; // } else if ("admin".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "2"; // loginUser.name = "admin"; // loginUser.role = "admin"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "admin"; // response.role = "admin"; // } else { // response.success = Boolean.FALSE; // response.errorMessage = "login failed"; // } // return response; // } // // @Override // public void logout() { // context.request().session().invalidate(); // } // // @Override // public CurrentUserAJAXResponse currentUser() { // CurrentUserAJAXResponse response = new CurrentUserAJAXResponse(); // if (Sessions.isUserLogin(context.request())) { // LoginUser loginUser = Sessions.loginUser(context.request()); // response.loggedIn = Boolean.TRUE; // response.name = loginUser.name; // response.role = loginUser.role; // } else { // response.loggedIn = Boolean.FALSE; // } // return response; // } // } // // Path: website/src/main/java/app/web/controller/HomeController.java // public class HomeController { // @Inject // WebDirectory webDirectory; // // public Response home(Request request) { // if (request.path().startsWith("/ajax/")) throw new NotFoundException("not found"); // // return Response.file(webDirectory.path("/index.html")).contentType(ContentType.TEXT_HTML); // } // } // // Path: website/src/main/java/app/web/controller/ProductAJAXWebServiceImpl.java // public class ProductAJAXWebServiceImpl implements ProductAJAXWebService { // @Override // public ListProductResponse list() { // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // throw new Error(e); // } // return new ListProductResponse(); // } // // @Override // public CreateProductConfigResponse createConfig() { // CreateProductConfigResponse response = new CreateProductConfigResponse(); // response.types = Lists.newArrayList(); // response.types.add(type("type1", "1")); // response.types.add(type("type2", "2")); // return response; // } // // @Override // public GetProductResponse get(String id) { // return new GetProductResponse(); // } // // @Override // public GetProductResponse getChild(String id, String childId) { // return new GetProductResponse(); // } // // private CreateProductConfigResponse.ProductType type(String name, String value) { // CreateProductConfigResponse.ProductType type = new CreateProductConfigResponse.ProductType(); // type.name = name; // type.value = value; // return type; // } // } // // Path: website/src/main/java/app/web/interceptor/LoginInterceptor.java // public class LoginInterceptor implements Interceptor { // @Override // public Response intercept(Invocation invocation) throws Exception { // if (invocation.annotation(LoginRequired.class) != null) { // WebContext context = invocation.context(); // Request request = context.request(); // Sessions.loginUser(request); // } // // // later we may need auto login by token (aka, remember me) // return invocation.proceed(); // } // }
import app.api.AccountAJAXWebService; import app.api.ProductAJAXWebService; import app.web.controller.AccountAJAXWebServiceImpl; import app.web.controller.HomeController; import app.web.controller.ProductAJAXWebServiceImpl; import app.web.interceptor.LoginInterceptor; import core.framework.http.HTTPMethod; import core.framework.module.Module;
package app; /** * @author neo */ public class WebModule extends Module { @Override protected void initialize() { http().intercept(bind(LoginInterceptor.class)); site().staticContent("/static"); site().staticContent("/robots.txt"); HomeController homeController = bind(HomeController.class); http().route(HTTPMethod.GET, "/", homeController::home); http().route(HTTPMethod.GET, "/:path(*)", homeController::home); api().service(AccountAJAXWebService.class, bind(AccountAJAXWebServiceImpl.class));
// Path: website/src/main/java/app/api/AccountAJAXWebService.java // public interface AccountAJAXWebService { // @PUT // @Path("/ajax/login") // LoginAJAXResponse login(LoginAJAXRequest request); // // @PUT // @Path("/ajax/logout") // void logout(); // // @GET // @Path("/ajax/currentUser") // CurrentUserAJAXResponse currentUser(); // } // // Path: website/src/main/java/app/api/ProductAJAXWebService.java // public interface ProductAJAXWebService { // @GET // @Path("/ajax/product") // ListProductResponse list(); // // @GET // @Path("/ajax/product/create-config") // CreateProductConfigResponse createConfig(); // // @GET // @Path("/ajax/product/:id") // GetProductResponse get(@PathParam("id") String id); // // @GET // @Path("/ajax/product/:id/child/:childId") // GetProductResponse getChild(@PathParam("id") String id, @PathParam("childId") String childId); // } // // Path: website/src/main/java/app/web/controller/AccountAJAXWebServiceImpl.java // public class AccountAJAXWebServiceImpl implements AccountAJAXWebService { // @Inject // WebContext context; // // @Override // public LoginAJAXResponse login(LoginAJAXRequest request) { // LoginAJAXResponse response = new LoginAJAXResponse(); // if ("user".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "1"; // loginUser.name = "user"; // loginUser.role = "user"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "user"; // response.role = "user"; // } else if ("admin".equals(request.username) && "123".equals(request.password)) { // LoginUser loginUser = new LoginUser(); // loginUser.userId = "2"; // loginUser.name = "admin"; // loginUser.role = "admin"; // Sessions.setLoginUser(context.request(), loginUser); // response.success = Boolean.TRUE; // response.name = "admin"; // response.role = "admin"; // } else { // response.success = Boolean.FALSE; // response.errorMessage = "login failed"; // } // return response; // } // // @Override // public void logout() { // context.request().session().invalidate(); // } // // @Override // public CurrentUserAJAXResponse currentUser() { // CurrentUserAJAXResponse response = new CurrentUserAJAXResponse(); // if (Sessions.isUserLogin(context.request())) { // LoginUser loginUser = Sessions.loginUser(context.request()); // response.loggedIn = Boolean.TRUE; // response.name = loginUser.name; // response.role = loginUser.role; // } else { // response.loggedIn = Boolean.FALSE; // } // return response; // } // } // // Path: website/src/main/java/app/web/controller/HomeController.java // public class HomeController { // @Inject // WebDirectory webDirectory; // // public Response home(Request request) { // if (request.path().startsWith("/ajax/")) throw new NotFoundException("not found"); // // return Response.file(webDirectory.path("/index.html")).contentType(ContentType.TEXT_HTML); // } // } // // Path: website/src/main/java/app/web/controller/ProductAJAXWebServiceImpl.java // public class ProductAJAXWebServiceImpl implements ProductAJAXWebService { // @Override // public ListProductResponse list() { // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // throw new Error(e); // } // return new ListProductResponse(); // } // // @Override // public CreateProductConfigResponse createConfig() { // CreateProductConfigResponse response = new CreateProductConfigResponse(); // response.types = Lists.newArrayList(); // response.types.add(type("type1", "1")); // response.types.add(type("type2", "2")); // return response; // } // // @Override // public GetProductResponse get(String id) { // return new GetProductResponse(); // } // // @Override // public GetProductResponse getChild(String id, String childId) { // return new GetProductResponse(); // } // // private CreateProductConfigResponse.ProductType type(String name, String value) { // CreateProductConfigResponse.ProductType type = new CreateProductConfigResponse.ProductType(); // type.name = name; // type.value = value; // return type; // } // } // // Path: website/src/main/java/app/web/interceptor/LoginInterceptor.java // public class LoginInterceptor implements Interceptor { // @Override // public Response intercept(Invocation invocation) throws Exception { // if (invocation.annotation(LoginRequired.class) != null) { // WebContext context = invocation.context(); // Request request = context.request(); // Sessions.loginUser(request); // } // // // later we may need auto login by token (aka, remember me) // return invocation.proceed(); // } // } // Path: website/src/main/java/app/WebModule.java import app.api.AccountAJAXWebService; import app.api.ProductAJAXWebService; import app.web.controller.AccountAJAXWebServiceImpl; import app.web.controller.HomeController; import app.web.controller.ProductAJAXWebServiceImpl; import app.web.interceptor.LoginInterceptor; import core.framework.http.HTTPMethod; import core.framework.module.Module; package app; /** * @author neo */ public class WebModule extends Module { @Override protected void initialize() { http().intercept(bind(LoginInterceptor.class)); site().staticContent("/static"); site().staticContent("/robots.txt"); HomeController homeController = bind(HomeController.class); http().route(HTTPMethod.GET, "/", homeController::home); http().route(HTTPMethod.GET, "/:path(*)", homeController::home); api().service(AccountAJAXWebService.class, bind(AccountAJAXWebServiceImpl.class));
api().service(ProductAJAXWebService.class, bind(ProductAJAXWebServiceImpl.class));
neowu/frontend-demo-project
website/src/main/java/app/web/Sessions.java
// Path: website/src/main/java/app/web/session/LoginUser.java // public class LoginUser { // @Property(name = "userId") // public String userId; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // }
import app.web.session.LoginUser; import core.framework.json.JSON; import core.framework.web.Request; import core.framework.web.exception.UnauthorizedException;
package app.web; /** * @author neo */ public final class Sessions { private static final String USER = "LOGIN_USER"; public static boolean isUserLogin(Request request) { return request.session().get(USER).isPresent(); }
// Path: website/src/main/java/app/web/session/LoginUser.java // public class LoginUser { // @Property(name = "userId") // public String userId; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // Path: website/src/main/java/app/web/Sessions.java import app.web.session.LoginUser; import core.framework.json.JSON; import core.framework.web.Request; import core.framework.web.exception.UnauthorizedException; package app.web; /** * @author neo */ public final class Sessions { private static final String USER = "LOGIN_USER"; public static boolean isUserLogin(Request request) { return request.session().get(USER).isPresent(); }
public static LoginUser loginUser(Request request) {
neowu/frontend-demo-project
website/src/main/java/app/api/ProductAJAXWebService.java
// Path: website/src/main/java/app/api/product/CreateProductConfigResponse.java // public class CreateProductConfigResponse { // @NotNull // @Property(name = "types") // public List<ProductType> types; // // @NotNull // @Property(name = "now") // public ZonedDateTime now = ZonedDateTime.now(); // // public static class ProductType { // @NotNull // @Property(name = "name") // public String name; // // @NotNull // @Property(name = "value") // public String value; // } // } // // Path: website/src/main/java/app/api/product/GetProductResponse.java // public class GetProductResponse { // // } // // Path: website/src/main/java/app/api/product/ListProductResponse.java // public class ListProductResponse { // // }
import app.api.product.CreateProductConfigResponse; import app.api.product.GetProductResponse; import app.api.product.ListProductResponse; import core.framework.api.web.service.GET; import core.framework.api.web.service.Path; import core.framework.api.web.service.PathParam;
package app.api; public interface ProductAJAXWebService { @GET @Path("/ajax/product")
// Path: website/src/main/java/app/api/product/CreateProductConfigResponse.java // public class CreateProductConfigResponse { // @NotNull // @Property(name = "types") // public List<ProductType> types; // // @NotNull // @Property(name = "now") // public ZonedDateTime now = ZonedDateTime.now(); // // public static class ProductType { // @NotNull // @Property(name = "name") // public String name; // // @NotNull // @Property(name = "value") // public String value; // } // } // // Path: website/src/main/java/app/api/product/GetProductResponse.java // public class GetProductResponse { // // } // // Path: website/src/main/java/app/api/product/ListProductResponse.java // public class ListProductResponse { // // } // Path: website/src/main/java/app/api/ProductAJAXWebService.java import app.api.product.CreateProductConfigResponse; import app.api.product.GetProductResponse; import app.api.product.ListProductResponse; import core.framework.api.web.service.GET; import core.framework.api.web.service.Path; import core.framework.api.web.service.PathParam; package app.api; public interface ProductAJAXWebService { @GET @Path("/ajax/product")
ListProductResponse list();
neowu/frontend-demo-project
website/src/main/java/app/api/ProductAJAXWebService.java
// Path: website/src/main/java/app/api/product/CreateProductConfigResponse.java // public class CreateProductConfigResponse { // @NotNull // @Property(name = "types") // public List<ProductType> types; // // @NotNull // @Property(name = "now") // public ZonedDateTime now = ZonedDateTime.now(); // // public static class ProductType { // @NotNull // @Property(name = "name") // public String name; // // @NotNull // @Property(name = "value") // public String value; // } // } // // Path: website/src/main/java/app/api/product/GetProductResponse.java // public class GetProductResponse { // // } // // Path: website/src/main/java/app/api/product/ListProductResponse.java // public class ListProductResponse { // // }
import app.api.product.CreateProductConfigResponse; import app.api.product.GetProductResponse; import app.api.product.ListProductResponse; import core.framework.api.web.service.GET; import core.framework.api.web.service.Path; import core.framework.api.web.service.PathParam;
package app.api; public interface ProductAJAXWebService { @GET @Path("/ajax/product") ListProductResponse list(); @GET @Path("/ajax/product/create-config")
// Path: website/src/main/java/app/api/product/CreateProductConfigResponse.java // public class CreateProductConfigResponse { // @NotNull // @Property(name = "types") // public List<ProductType> types; // // @NotNull // @Property(name = "now") // public ZonedDateTime now = ZonedDateTime.now(); // // public static class ProductType { // @NotNull // @Property(name = "name") // public String name; // // @NotNull // @Property(name = "value") // public String value; // } // } // // Path: website/src/main/java/app/api/product/GetProductResponse.java // public class GetProductResponse { // // } // // Path: website/src/main/java/app/api/product/ListProductResponse.java // public class ListProductResponse { // // } // Path: website/src/main/java/app/api/ProductAJAXWebService.java import app.api.product.CreateProductConfigResponse; import app.api.product.GetProductResponse; import app.api.product.ListProductResponse; import core.framework.api.web.service.GET; import core.framework.api.web.service.Path; import core.framework.api.web.service.PathParam; package app.api; public interface ProductAJAXWebService { @GET @Path("/ajax/product") ListProductResponse list(); @GET @Path("/ajax/product/create-config")
CreateProductConfigResponse createConfig();
neowu/frontend-demo-project
website/src/main/java/app/api/ProductAJAXWebService.java
// Path: website/src/main/java/app/api/product/CreateProductConfigResponse.java // public class CreateProductConfigResponse { // @NotNull // @Property(name = "types") // public List<ProductType> types; // // @NotNull // @Property(name = "now") // public ZonedDateTime now = ZonedDateTime.now(); // // public static class ProductType { // @NotNull // @Property(name = "name") // public String name; // // @NotNull // @Property(name = "value") // public String value; // } // } // // Path: website/src/main/java/app/api/product/GetProductResponse.java // public class GetProductResponse { // // } // // Path: website/src/main/java/app/api/product/ListProductResponse.java // public class ListProductResponse { // // }
import app.api.product.CreateProductConfigResponse; import app.api.product.GetProductResponse; import app.api.product.ListProductResponse; import core.framework.api.web.service.GET; import core.framework.api.web.service.Path; import core.framework.api.web.service.PathParam;
package app.api; public interface ProductAJAXWebService { @GET @Path("/ajax/product") ListProductResponse list(); @GET @Path("/ajax/product/create-config") CreateProductConfigResponse createConfig(); @GET @Path("/ajax/product/:id")
// Path: website/src/main/java/app/api/product/CreateProductConfigResponse.java // public class CreateProductConfigResponse { // @NotNull // @Property(name = "types") // public List<ProductType> types; // // @NotNull // @Property(name = "now") // public ZonedDateTime now = ZonedDateTime.now(); // // public static class ProductType { // @NotNull // @Property(name = "name") // public String name; // // @NotNull // @Property(name = "value") // public String value; // } // } // // Path: website/src/main/java/app/api/product/GetProductResponse.java // public class GetProductResponse { // // } // // Path: website/src/main/java/app/api/product/ListProductResponse.java // public class ListProductResponse { // // } // Path: website/src/main/java/app/api/ProductAJAXWebService.java import app.api.product.CreateProductConfigResponse; import app.api.product.GetProductResponse; import app.api.product.ListProductResponse; import core.framework.api.web.service.GET; import core.framework.api.web.service.Path; import core.framework.api.web.service.PathParam; package app.api; public interface ProductAJAXWebService { @GET @Path("/ajax/product") ListProductResponse list(); @GET @Path("/ajax/product/create-config") CreateProductConfigResponse createConfig(); @GET @Path("/ajax/product/:id")
GetProductResponse get(@PathParam("id") String id);
neowu/frontend-demo-project
website/src/main/java/app/api/AccountAJAXWebService.java
// Path: website/src/main/java/app/api/user/CurrentUserAJAXResponse.java // public class CurrentUserAJAXResponse { // @NotNull // @Property(name = "loggedIn") // public Boolean loggedIn; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // // Path: website/src/main/java/app/api/user/LoginAJAXRequest.java // public class LoginAJAXRequest { // @NotNull // @Property(name = "username") // public String username; // // @NotNull // @Size(min = 3) // @Property(name = "password") // public String password; // } // // Path: website/src/main/java/app/api/user/LoginAJAXResponse.java // public class LoginAJAXResponse { // @NotNull // @Property(name = "success") // public Boolean success; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // // @Property(name = "errorMessage") // public String errorMessage; // }
import app.api.user.CurrentUserAJAXResponse; import app.api.user.LoginAJAXRequest; import app.api.user.LoginAJAXResponse; import core.framework.api.web.service.GET; import core.framework.api.web.service.PUT; import core.framework.api.web.service.Path;
package app.api; public interface AccountAJAXWebService { @PUT @Path("/ajax/login")
// Path: website/src/main/java/app/api/user/CurrentUserAJAXResponse.java // public class CurrentUserAJAXResponse { // @NotNull // @Property(name = "loggedIn") // public Boolean loggedIn; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // // Path: website/src/main/java/app/api/user/LoginAJAXRequest.java // public class LoginAJAXRequest { // @NotNull // @Property(name = "username") // public String username; // // @NotNull // @Size(min = 3) // @Property(name = "password") // public String password; // } // // Path: website/src/main/java/app/api/user/LoginAJAXResponse.java // public class LoginAJAXResponse { // @NotNull // @Property(name = "success") // public Boolean success; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // // @Property(name = "errorMessage") // public String errorMessage; // } // Path: website/src/main/java/app/api/AccountAJAXWebService.java import app.api.user.CurrentUserAJAXResponse; import app.api.user.LoginAJAXRequest; import app.api.user.LoginAJAXResponse; import core.framework.api.web.service.GET; import core.framework.api.web.service.PUT; import core.framework.api.web.service.Path; package app.api; public interface AccountAJAXWebService { @PUT @Path("/ajax/login")
LoginAJAXResponse login(LoginAJAXRequest request);
neowu/frontend-demo-project
website/src/main/java/app/api/AccountAJAXWebService.java
// Path: website/src/main/java/app/api/user/CurrentUserAJAXResponse.java // public class CurrentUserAJAXResponse { // @NotNull // @Property(name = "loggedIn") // public Boolean loggedIn; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // // Path: website/src/main/java/app/api/user/LoginAJAXRequest.java // public class LoginAJAXRequest { // @NotNull // @Property(name = "username") // public String username; // // @NotNull // @Size(min = 3) // @Property(name = "password") // public String password; // } // // Path: website/src/main/java/app/api/user/LoginAJAXResponse.java // public class LoginAJAXResponse { // @NotNull // @Property(name = "success") // public Boolean success; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // // @Property(name = "errorMessage") // public String errorMessage; // }
import app.api.user.CurrentUserAJAXResponse; import app.api.user.LoginAJAXRequest; import app.api.user.LoginAJAXResponse; import core.framework.api.web.service.GET; import core.framework.api.web.service.PUT; import core.framework.api.web.service.Path;
package app.api; public interface AccountAJAXWebService { @PUT @Path("/ajax/login")
// Path: website/src/main/java/app/api/user/CurrentUserAJAXResponse.java // public class CurrentUserAJAXResponse { // @NotNull // @Property(name = "loggedIn") // public Boolean loggedIn; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // // Path: website/src/main/java/app/api/user/LoginAJAXRequest.java // public class LoginAJAXRequest { // @NotNull // @Property(name = "username") // public String username; // // @NotNull // @Size(min = 3) // @Property(name = "password") // public String password; // } // // Path: website/src/main/java/app/api/user/LoginAJAXResponse.java // public class LoginAJAXResponse { // @NotNull // @Property(name = "success") // public Boolean success; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // // @Property(name = "errorMessage") // public String errorMessage; // } // Path: website/src/main/java/app/api/AccountAJAXWebService.java import app.api.user.CurrentUserAJAXResponse; import app.api.user.LoginAJAXRequest; import app.api.user.LoginAJAXResponse; import core.framework.api.web.service.GET; import core.framework.api.web.service.PUT; import core.framework.api.web.service.Path; package app.api; public interface AccountAJAXWebService { @PUT @Path("/ajax/login")
LoginAJAXResponse login(LoginAJAXRequest request);
neowu/frontend-demo-project
website/src/main/java/app/api/AccountAJAXWebService.java
// Path: website/src/main/java/app/api/user/CurrentUserAJAXResponse.java // public class CurrentUserAJAXResponse { // @NotNull // @Property(name = "loggedIn") // public Boolean loggedIn; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // // Path: website/src/main/java/app/api/user/LoginAJAXRequest.java // public class LoginAJAXRequest { // @NotNull // @Property(name = "username") // public String username; // // @NotNull // @Size(min = 3) // @Property(name = "password") // public String password; // } // // Path: website/src/main/java/app/api/user/LoginAJAXResponse.java // public class LoginAJAXResponse { // @NotNull // @Property(name = "success") // public Boolean success; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // // @Property(name = "errorMessage") // public String errorMessage; // }
import app.api.user.CurrentUserAJAXResponse; import app.api.user.LoginAJAXRequest; import app.api.user.LoginAJAXResponse; import core.framework.api.web.service.GET; import core.framework.api.web.service.PUT; import core.framework.api.web.service.Path;
package app.api; public interface AccountAJAXWebService { @PUT @Path("/ajax/login") LoginAJAXResponse login(LoginAJAXRequest request); @PUT @Path("/ajax/logout") void logout(); @GET @Path("/ajax/currentUser")
// Path: website/src/main/java/app/api/user/CurrentUserAJAXResponse.java // public class CurrentUserAJAXResponse { // @NotNull // @Property(name = "loggedIn") // public Boolean loggedIn; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // } // // Path: website/src/main/java/app/api/user/LoginAJAXRequest.java // public class LoginAJAXRequest { // @NotNull // @Property(name = "username") // public String username; // // @NotNull // @Size(min = 3) // @Property(name = "password") // public String password; // } // // Path: website/src/main/java/app/api/user/LoginAJAXResponse.java // public class LoginAJAXResponse { // @NotNull // @Property(name = "success") // public Boolean success; // // @Property(name = "name") // public String name; // // @Property(name = "role") // public String role; // // @Property(name = "errorMessage") // public String errorMessage; // } // Path: website/src/main/java/app/api/AccountAJAXWebService.java import app.api.user.CurrentUserAJAXResponse; import app.api.user.LoginAJAXRequest; import app.api.user.LoginAJAXResponse; import core.framework.api.web.service.GET; import core.framework.api.web.service.PUT; import core.framework.api.web.service.Path; package app.api; public interface AccountAJAXWebService { @PUT @Path("/ajax/login") LoginAJAXResponse login(LoginAJAXRequest request); @PUT @Path("/ajax/logout") void logout(); @GET @Path("/ajax/currentUser")
CurrentUserAJAXResponse currentUser();
ov3rk1ll/KinoCast
app/src/main/java/com/ov3rk1ll/kinocast/ui/util/glide/OkHttpViewModelUrlLoader.java
// Path: app/src/main/java/com/ov3rk1ll/kinocast/utils/TheMovieDb.java // public class TheMovieDb { // public static final String IMAGE_BASE_PATH = "http://image.tmdb.org/t/p/"; // private static final String DISK_CACHE_PATH = "/themoviedb_cache/"; // private static final String API_KEY = "f9dc7e5d12b2640bf4ef1cf20835a1cc"; // // private ConcurrentHashMap<String, SoftReference<JSONObject>> memoryCache; // private String diskCachePath; // private boolean diskCacheEnabled = false; // private ExecutorService writeThread; // // // public TheMovieDb(Context context) { // // Set up in-memory cache store // memoryCache = new ConcurrentHashMap<>(); // // // Set up disk cache store // Context appContext = context.getApplicationContext(); // diskCachePath = appContext.getCacheDir().getAbsolutePath() + DISK_CACHE_PATH; // // File outFile = new File(diskCachePath); // outFile.mkdirs(); // // diskCacheEnabled = outFile.exists(); // // // Set up threadpool for image fetching tasks // writeThread = Executors.newSingleThreadExecutor(); // } // // public JSONObject get(String url) { // return get(url, true); // } // // public JSONObject get(String url, boolean fetchIfNeeded) { // JSONObject json; // //String url = request.getUrl(); // // // Check for image in memory // json = getFromMemory(url); // // // Check for image on disk cache // if(json == null) { // json = getFromDisk(url); // // // Write bitmap back into memory cache // if(json != null) { // cacheToMemory(url, json); // } // } // if(json == null || fetchIfNeeded) { // try { // // Get IMDB-ID from page // ViewModel item = Parser.getInstance().loadDetail(url); // String param = url.substring(url.indexOf("#") + 1); // // tt1646971?api_key=f9dc7e5d12b2640bf4ef1cf20835a1cc&language=de&external_source=imdb_id // JSONObject data = Utils.readJson("http://api.themoviedb.org/3/find/" + item.getImdbId() + "?api_key=" + API_KEY + "&external_source=imdb_id&" + param); // if(data == null) return null; // if(data.getJSONArray("movie_results").length() > 0) { // json = data.getJSONArray("movie_results").getJSONObject(0); // }else if(data.getJSONArray("tv_results").length() > 0) { // json = data.getJSONArray("tv_results").getJSONObject(0); // } // if(json != null) { // put(url, json); // } // } catch (JSONException e) { // e.printStackTrace(); // } // } // // return json; // } // // private void put(String url, JSONObject json) { // cacheToMemory(url, json); // cacheToDisk(url, json); // } // // private JSONObject getFromMemory(String url) { // JSONObject json = null; // SoftReference<JSONObject> softRef = memoryCache.get(getCacheKey(url)); // if(softRef != null){ // json = softRef.get(); // } // // return json; // } // // private JSONObject getFromDisk(String url) { // JSONObject json = null; // if(diskCacheEnabled){ // String filePath = getFilePath(url); // File file = new File(filePath); // if(file.exists()) { // try { // BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(file))); // StringBuilder content = new StringBuilder(); // char[] buffer = new char[1024]; // int num; // while ((num = input.read(buffer)) > 0) { // content.append(buffer, 0, num); // } // json = new JSONObject(content.toString()); // } catch (JSONException | IOException e) { // e.printStackTrace(); // } // // } // } // return json; // } // // private void cacheToMemory(final String url, final JSONObject json) { // memoryCache.put(getCacheKey(url), new SoftReference<>(json)); // } // // private void cacheToDisk(final String url, final JSONObject json) { // writeThread.execute(new Runnable() { // @Override // public void run() { // if(diskCacheEnabled) { // FileOutputStream ostream = null; // try { // ostream = new FileOutputStream(new File(diskCachePath, getCacheKey(url))); // ostream.write(json.toString().getBytes()); // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if(ostream != null) { // ostream.flush(); // ostream.close(); // } // } catch (IOException ignored) {} // } // } // } // }); // } // // private String getFilePath(String url) { // return diskCachePath + getCacheKey(url); // } // // private String getCacheKey(String url) { // if(url == null){ // throw new RuntimeException("Null url passed in"); // } else { // if(url.contains("#")) // url = url.substring(0, url.indexOf("#")); // return url.replaceAll("[.:/,%?&=]", "+").replaceAll("[+]+", "+"); // } // } // }
import android.content.Context; import com.bumptech.glide.load.data.DataFetcher; import com.bumptech.glide.load.model.GenericLoaderFactory; import com.bumptech.glide.load.model.ModelLoader; import com.bumptech.glide.load.model.ModelLoaderFactory; import com.ov3rk1ll.kinocast.utils.TheMovieDb; import java.io.InputStream; import okhttp3.Call; import okhttp3.OkHttpClient;
package com.ov3rk1ll.kinocast.ui.util.glide; /** * A simple model loader for fetching media over http/https using OkHttp. */ public class OkHttpViewModelUrlLoader implements ModelLoader<ViewModelGlideRequest, InputStream> { private final Call.Factory client;
// Path: app/src/main/java/com/ov3rk1ll/kinocast/utils/TheMovieDb.java // public class TheMovieDb { // public static final String IMAGE_BASE_PATH = "http://image.tmdb.org/t/p/"; // private static final String DISK_CACHE_PATH = "/themoviedb_cache/"; // private static final String API_KEY = "f9dc7e5d12b2640bf4ef1cf20835a1cc"; // // private ConcurrentHashMap<String, SoftReference<JSONObject>> memoryCache; // private String diskCachePath; // private boolean diskCacheEnabled = false; // private ExecutorService writeThread; // // // public TheMovieDb(Context context) { // // Set up in-memory cache store // memoryCache = new ConcurrentHashMap<>(); // // // Set up disk cache store // Context appContext = context.getApplicationContext(); // diskCachePath = appContext.getCacheDir().getAbsolutePath() + DISK_CACHE_PATH; // // File outFile = new File(diskCachePath); // outFile.mkdirs(); // // diskCacheEnabled = outFile.exists(); // // // Set up threadpool for image fetching tasks // writeThread = Executors.newSingleThreadExecutor(); // } // // public JSONObject get(String url) { // return get(url, true); // } // // public JSONObject get(String url, boolean fetchIfNeeded) { // JSONObject json; // //String url = request.getUrl(); // // // Check for image in memory // json = getFromMemory(url); // // // Check for image on disk cache // if(json == null) { // json = getFromDisk(url); // // // Write bitmap back into memory cache // if(json != null) { // cacheToMemory(url, json); // } // } // if(json == null || fetchIfNeeded) { // try { // // Get IMDB-ID from page // ViewModel item = Parser.getInstance().loadDetail(url); // String param = url.substring(url.indexOf("#") + 1); // // tt1646971?api_key=f9dc7e5d12b2640bf4ef1cf20835a1cc&language=de&external_source=imdb_id // JSONObject data = Utils.readJson("http://api.themoviedb.org/3/find/" + item.getImdbId() + "?api_key=" + API_KEY + "&external_source=imdb_id&" + param); // if(data == null) return null; // if(data.getJSONArray("movie_results").length() > 0) { // json = data.getJSONArray("movie_results").getJSONObject(0); // }else if(data.getJSONArray("tv_results").length() > 0) { // json = data.getJSONArray("tv_results").getJSONObject(0); // } // if(json != null) { // put(url, json); // } // } catch (JSONException e) { // e.printStackTrace(); // } // } // // return json; // } // // private void put(String url, JSONObject json) { // cacheToMemory(url, json); // cacheToDisk(url, json); // } // // private JSONObject getFromMemory(String url) { // JSONObject json = null; // SoftReference<JSONObject> softRef = memoryCache.get(getCacheKey(url)); // if(softRef != null){ // json = softRef.get(); // } // // return json; // } // // private JSONObject getFromDisk(String url) { // JSONObject json = null; // if(diskCacheEnabled){ // String filePath = getFilePath(url); // File file = new File(filePath); // if(file.exists()) { // try { // BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(file))); // StringBuilder content = new StringBuilder(); // char[] buffer = new char[1024]; // int num; // while ((num = input.read(buffer)) > 0) { // content.append(buffer, 0, num); // } // json = new JSONObject(content.toString()); // } catch (JSONException | IOException e) { // e.printStackTrace(); // } // // } // } // return json; // } // // private void cacheToMemory(final String url, final JSONObject json) { // memoryCache.put(getCacheKey(url), new SoftReference<>(json)); // } // // private void cacheToDisk(final String url, final JSONObject json) { // writeThread.execute(new Runnable() { // @Override // public void run() { // if(diskCacheEnabled) { // FileOutputStream ostream = null; // try { // ostream = new FileOutputStream(new File(diskCachePath, getCacheKey(url))); // ostream.write(json.toString().getBytes()); // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if(ostream != null) { // ostream.flush(); // ostream.close(); // } // } catch (IOException ignored) {} // } // } // } // }); // } // // private String getFilePath(String url) { // return diskCachePath + getCacheKey(url); // } // // private String getCacheKey(String url) { // if(url == null){ // throw new RuntimeException("Null url passed in"); // } else { // if(url.contains("#")) // url = url.substring(0, url.indexOf("#")); // return url.replaceAll("[.:/,%?&=]", "+").replaceAll("[+]+", "+"); // } // } // } // Path: app/src/main/java/com/ov3rk1ll/kinocast/ui/util/glide/OkHttpViewModelUrlLoader.java import android.content.Context; import com.bumptech.glide.load.data.DataFetcher; import com.bumptech.glide.load.model.GenericLoaderFactory; import com.bumptech.glide.load.model.ModelLoader; import com.bumptech.glide.load.model.ModelLoaderFactory; import com.ov3rk1ll.kinocast.utils.TheMovieDb; import java.io.InputStream; import okhttp3.Call; import okhttp3.OkHttpClient; package com.ov3rk1ll.kinocast.ui.util.glide; /** * A simple model loader for fetching media over http/https using OkHttp. */ public class OkHttpViewModelUrlLoader implements ModelLoader<ViewModelGlideRequest, InputStream> { private final Call.Factory client;
private TheMovieDb tmdbCache;
ov3rk1ll/KinoCast
app/src/main/java/com/ov3rk1ll/kinocast/data/ViewModel.java
// Path: app/src/main/java/com/ov3rk1ll/kinocast/api/mirror/Host.java // public abstract class Host { // protected int mirror; // protected String url; // // public static Class<?>[] HOSTER_LIST = { // DivxStage.class, // NowVideo.class, // SharedSx.class, // Sockshare.class, // StreamCloud.class, // Vodlocker.class, // }; // // public static Host selectById(int id){ // for (Class<?> h: HOSTER_LIST) { // try { // Host host = (Host) h.getConstructor().newInstance(); // if(host.getId() == id){ // return host; // } // } catch (InstantiationException e) { // e.printStackTrace(); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } catch (InvocationTargetException e) { // e.printStackTrace(); // } catch (NoSuchMethodException e) { // e.printStackTrace(); // } // } // return null; // } // // public Host(){ // // } // // public Host(int mirror){ // this.mirror = mirror; // } // // public boolean isEnabled(){ // return false; // } // // public abstract int getId(); // public abstract String getName(); // // public int getMirror() { // return mirror; // } // // public void setMirror(int mirror) { // this.mirror = mirror; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getVideoPath(DetailActivity.QueryPlayTask queryTask){ // return null; // } // // @Override // public String toString() { // return getName() + " #" + mirror; // } // }
import com.ov3rk1ll.kinocast.api.mirror.Host; import java.io.Serializable;
package com.ov3rk1ll.kinocast.data; public class ViewModel implements Serializable { private int seriesID; private String slug; private String title; private String image; private String summary; private float rating; private int languageResId; private String genre; private String imdbId; @SuppressWarnings("unused") private String year; private Type type; private transient Season[] seasons;
// Path: app/src/main/java/com/ov3rk1ll/kinocast/api/mirror/Host.java // public abstract class Host { // protected int mirror; // protected String url; // // public static Class<?>[] HOSTER_LIST = { // DivxStage.class, // NowVideo.class, // SharedSx.class, // Sockshare.class, // StreamCloud.class, // Vodlocker.class, // }; // // public static Host selectById(int id){ // for (Class<?> h: HOSTER_LIST) { // try { // Host host = (Host) h.getConstructor().newInstance(); // if(host.getId() == id){ // return host; // } // } catch (InstantiationException e) { // e.printStackTrace(); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } catch (InvocationTargetException e) { // e.printStackTrace(); // } catch (NoSuchMethodException e) { // e.printStackTrace(); // } // } // return null; // } // // public Host(){ // // } // // public Host(int mirror){ // this.mirror = mirror; // } // // public boolean isEnabled(){ // return false; // } // // public abstract int getId(); // public abstract String getName(); // // public int getMirror() { // return mirror; // } // // public void setMirror(int mirror) { // this.mirror = mirror; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getVideoPath(DetailActivity.QueryPlayTask queryTask){ // return null; // } // // @Override // public String toString() { // return getName() + " #" + mirror; // } // } // Path: app/src/main/java/com/ov3rk1ll/kinocast/data/ViewModel.java import com.ov3rk1ll.kinocast.api.mirror.Host; import java.io.Serializable; package com.ov3rk1ll.kinocast.data; public class ViewModel implements Serializable { private int seriesID; private String slug; private String title; private String image; private String summary; private float rating; private int languageResId; private String genre; private String imdbId; @SuppressWarnings("unused") private String year; private Type type; private transient Season[] seasons;
private transient Host[] mirrors;
ISibboI/JBitmessage
src/main/java/sibbo/bitmessage/network/protocol/GetdataMessage.java
// Path: src/main/java/sibbo/bitmessage/Options.java // public class Options extends Properties { // private static final Logger LOG = Logger.getLogger(Options.class.getName()); // // private static final Options defaults = new Options(null); // // static { // defaults.setProperty("global.version", "0.0.0"); // defaults.setProperty("global.name", "JBitmessage"); // // defaults.setProperty("protocol.maxMessageLength", 10 * 1024 * 1024); // defaults.setProperty("protocol.maxInvLength", 50_000); // defaults.setProperty("protocol.maxAddrLength", 1_000); // defaults.setProperty("protocol.services", 1); // defaults.setProperty("protocol.remoteServices", 1); // defaults.setProperty("protocol.version", 1); // TODO Change to 2 after // // implementation. // defaults.setProperty("pow.averageNonceTrialsPerByte", 320); // defaults.setProperty("pow.payloadLengthExtraBytes", 14_000); // defaults.setProperty("pow.systemLoad", 0.5f); // defaults.setProperty("pow.iterationfactor", 100); // defaults.setProperty("network.connectTimeout", 5_000); // defaults.setProperty("network.timeout", 10_000); // defaults.setProperty("network.listenPort", 8443); // defaults.setProperty("network.passiveMode.maxConnections", 8); // defaults.setProperty("network.activeMode.maxConnections", 16); // defaults.setProperty("network.activeMode.stopListenConnectionCount", 32); // defaults.setProperty("network.userAgent", // "/" + defaults.getString("global.name") + ":" + defaults.getString("global.version") + "/"); // defaults.setProperty("data.maxNodeStorageTime", 3600 * 3); // Seconds // } // // private static final Options instance = new Options(defaults); // // public static Options getInstance() { // return instance; // } // // private Options(Properties defaults) { // super(defaults); // } // // public float getFloat(String key) { // try { // return Float.valueOf(getProperty(key)); // } catch (NumberFormatException e) { // LOG.log(Level.SEVERE, "Not a float: " + getProperty(key), e); // System.exit(1); // return 0; // } // } // // public int getInt(String key) { // try { // return Integer.valueOf(getProperty(key)); // } catch (NumberFormatException e) { // LOG.log(Level.SEVERE, "Not an integer: " + getProperty(key), e); // System.exit(1); // return 0; // } // } // // public long getLong(String key) { // try { // return Long.valueOf(getProperty(key)); // } catch (NumberFormatException e) { // LOG.log(Level.SEVERE, "Not a long: " + getProperty(key), e); // System.exit(1); // return 0; // } // } // // @Override // public String getProperty(String key) { // String result = super.getProperty(key); // // if (result == null) { // throw new NullPointerException("Property not found: " + key); // } else { // return result; // } // } // // public String getString(String key) { // return getProperty(key); // } // // public Object setProperty(String key, float value) { // return setProperty(key, String.valueOf(value)); // } // // public Object setProperty(String key, int value) { // return setProperty(key, String.valueOf(value)); // } // // public Object setProperty(String key, long value) { // return setProperty(key, String.valueOf(value)); // } // }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import sibbo.bitmessage.Options;
package sibbo.bitmessage.network.protocol; /** * A message to request inventory objects. * * @author Sebastian Schmidt * @version 1.0 */ public class GetdataMessage extends P2PMessage { private static final Logger LOG = Logger.getLogger(InvMessage.class.getName()); /** The command string for this message type. */ public static final String COMMAND = "getdata"; /** The inventory vectors. */ private List<InventoryVectorMessage> inv; /** * Creates a new getdata message with the given inventory vectors. * * @param inv * The inventory vectors. */ public GetdataMessage(Collection<? extends InventoryVectorMessage> inv, MessageFactory factory) { super(factory); this.inv = new ArrayList<>(inv); } /** * {@link Message#Message(InputBuffer, MessageFactory)} */ public GetdataMessage(InputBuffer b, MessageFactory factory) throws IOException, ParsingException { super(b, factory); } @Override public String getCommand() { return COMMAND; } @Override protected void read(InputBuffer b) throws IOException, ParsingException { VariableLengthIntegerMessage vLength = getMessageFactory().parseVariableLengthIntegerMessage(b); b = b.getSubBuffer(vLength.length()); long length = vLength.getLong();
// Path: src/main/java/sibbo/bitmessage/Options.java // public class Options extends Properties { // private static final Logger LOG = Logger.getLogger(Options.class.getName()); // // private static final Options defaults = new Options(null); // // static { // defaults.setProperty("global.version", "0.0.0"); // defaults.setProperty("global.name", "JBitmessage"); // // defaults.setProperty("protocol.maxMessageLength", 10 * 1024 * 1024); // defaults.setProperty("protocol.maxInvLength", 50_000); // defaults.setProperty("protocol.maxAddrLength", 1_000); // defaults.setProperty("protocol.services", 1); // defaults.setProperty("protocol.remoteServices", 1); // defaults.setProperty("protocol.version", 1); // TODO Change to 2 after // // implementation. // defaults.setProperty("pow.averageNonceTrialsPerByte", 320); // defaults.setProperty("pow.payloadLengthExtraBytes", 14_000); // defaults.setProperty("pow.systemLoad", 0.5f); // defaults.setProperty("pow.iterationfactor", 100); // defaults.setProperty("network.connectTimeout", 5_000); // defaults.setProperty("network.timeout", 10_000); // defaults.setProperty("network.listenPort", 8443); // defaults.setProperty("network.passiveMode.maxConnections", 8); // defaults.setProperty("network.activeMode.maxConnections", 16); // defaults.setProperty("network.activeMode.stopListenConnectionCount", 32); // defaults.setProperty("network.userAgent", // "/" + defaults.getString("global.name") + ":" + defaults.getString("global.version") + "/"); // defaults.setProperty("data.maxNodeStorageTime", 3600 * 3); // Seconds // } // // private static final Options instance = new Options(defaults); // // public static Options getInstance() { // return instance; // } // // private Options(Properties defaults) { // super(defaults); // } // // public float getFloat(String key) { // try { // return Float.valueOf(getProperty(key)); // } catch (NumberFormatException e) { // LOG.log(Level.SEVERE, "Not a float: " + getProperty(key), e); // System.exit(1); // return 0; // } // } // // public int getInt(String key) { // try { // return Integer.valueOf(getProperty(key)); // } catch (NumberFormatException e) { // LOG.log(Level.SEVERE, "Not an integer: " + getProperty(key), e); // System.exit(1); // return 0; // } // } // // public long getLong(String key) { // try { // return Long.valueOf(getProperty(key)); // } catch (NumberFormatException e) { // LOG.log(Level.SEVERE, "Not a long: " + getProperty(key), e); // System.exit(1); // return 0; // } // } // // @Override // public String getProperty(String key) { // String result = super.getProperty(key); // // if (result == null) { // throw new NullPointerException("Property not found: " + key); // } else { // return result; // } // } // // public String getString(String key) { // return getProperty(key); // } // // public Object setProperty(String key, float value) { // return setProperty(key, String.valueOf(value)); // } // // public Object setProperty(String key, int value) { // return setProperty(key, String.valueOf(value)); // } // // public Object setProperty(String key, long value) { // return setProperty(key, String.valueOf(value)); // } // } // Path: src/main/java/sibbo/bitmessage/network/protocol/GetdataMessage.java import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import sibbo.bitmessage.Options; package sibbo.bitmessage.network.protocol; /** * A message to request inventory objects. * * @author Sebastian Schmidt * @version 1.0 */ public class GetdataMessage extends P2PMessage { private static final Logger LOG = Logger.getLogger(InvMessage.class.getName()); /** The command string for this message type. */ public static final String COMMAND = "getdata"; /** The inventory vectors. */ private List<InventoryVectorMessage> inv; /** * Creates a new getdata message with the given inventory vectors. * * @param inv * The inventory vectors. */ public GetdataMessage(Collection<? extends InventoryVectorMessage> inv, MessageFactory factory) { super(factory); this.inv = new ArrayList<>(inv); } /** * {@link Message#Message(InputBuffer, MessageFactory)} */ public GetdataMessage(InputBuffer b, MessageFactory factory) throws IOException, ParsingException { super(b, factory); } @Override public String getCommand() { return COMMAND; } @Override protected void read(InputBuffer b) throws IOException, ParsingException { VariableLengthIntegerMessage vLength = getMessageFactory().parseVariableLengthIntegerMessage(b); b = b.getSubBuffer(vLength.length()); long length = vLength.getLong();
if (length < 0 || length > Options.getInstance().getInt("protocol.maxInvLength")) {
ISibboI/JBitmessage
src/main/java/sibbo/bitmessage/network/protocol/InvMessage.java
// Path: src/main/java/sibbo/bitmessage/Options.java // public class Options extends Properties { // private static final Logger LOG = Logger.getLogger(Options.class.getName()); // // private static final Options defaults = new Options(null); // // static { // defaults.setProperty("global.version", "0.0.0"); // defaults.setProperty("global.name", "JBitmessage"); // // defaults.setProperty("protocol.maxMessageLength", 10 * 1024 * 1024); // defaults.setProperty("protocol.maxInvLength", 50_000); // defaults.setProperty("protocol.maxAddrLength", 1_000); // defaults.setProperty("protocol.services", 1); // defaults.setProperty("protocol.remoteServices", 1); // defaults.setProperty("protocol.version", 1); // TODO Change to 2 after // // implementation. // defaults.setProperty("pow.averageNonceTrialsPerByte", 320); // defaults.setProperty("pow.payloadLengthExtraBytes", 14_000); // defaults.setProperty("pow.systemLoad", 0.5f); // defaults.setProperty("pow.iterationfactor", 100); // defaults.setProperty("network.connectTimeout", 5_000); // defaults.setProperty("network.timeout", 10_000); // defaults.setProperty("network.listenPort", 8443); // defaults.setProperty("network.passiveMode.maxConnections", 8); // defaults.setProperty("network.activeMode.maxConnections", 16); // defaults.setProperty("network.activeMode.stopListenConnectionCount", 32); // defaults.setProperty("network.userAgent", // "/" + defaults.getString("global.name") + ":" + defaults.getString("global.version") + "/"); // defaults.setProperty("data.maxNodeStorageTime", 3600 * 3); // Seconds // } // // private static final Options instance = new Options(defaults); // // public static Options getInstance() { // return instance; // } // // private Options(Properties defaults) { // super(defaults); // } // // public float getFloat(String key) { // try { // return Float.valueOf(getProperty(key)); // } catch (NumberFormatException e) { // LOG.log(Level.SEVERE, "Not a float: " + getProperty(key), e); // System.exit(1); // return 0; // } // } // // public int getInt(String key) { // try { // return Integer.valueOf(getProperty(key)); // } catch (NumberFormatException e) { // LOG.log(Level.SEVERE, "Not an integer: " + getProperty(key), e); // System.exit(1); // return 0; // } // } // // public long getLong(String key) { // try { // return Long.valueOf(getProperty(key)); // } catch (NumberFormatException e) { // LOG.log(Level.SEVERE, "Not a long: " + getProperty(key), e); // System.exit(1); // return 0; // } // } // // @Override // public String getProperty(String key) { // String result = super.getProperty(key); // // if (result == null) { // throw new NullPointerException("Property not found: " + key); // } else { // return result; // } // } // // public String getString(String key) { // return getProperty(key); // } // // public Object setProperty(String key, float value) { // return setProperty(key, String.valueOf(value)); // } // // public Object setProperty(String key, int value) { // return setProperty(key, String.valueOf(value)); // } // // public Object setProperty(String key, long value) { // return setProperty(key, String.valueOf(value)); // } // }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import sibbo.bitmessage.Options;
package sibbo.bitmessage.network.protocol; /** * A message to advertise inventory objects. * * @author Sebastian Schmidt * @version 1.0 */ public class InvMessage extends P2PMessage { private static final Logger LOG = Logger.getLogger(InvMessage.class.getName()); /** The command string for this message type. */ public static final String COMMAND = "inv"; /** The inventory vectors. */ private List<InventoryVectorMessage> inv; /** * Creates a new inv message with the given inventory vectors. * * @param inv * The inventory vectors. */ public InvMessage(Collection<? extends InventoryVectorMessage> inv, MessageFactory factory) { super(factory); Objects.requireNonNull(inv, "inv must not be null.");
// Path: src/main/java/sibbo/bitmessage/Options.java // public class Options extends Properties { // private static final Logger LOG = Logger.getLogger(Options.class.getName()); // // private static final Options defaults = new Options(null); // // static { // defaults.setProperty("global.version", "0.0.0"); // defaults.setProperty("global.name", "JBitmessage"); // // defaults.setProperty("protocol.maxMessageLength", 10 * 1024 * 1024); // defaults.setProperty("protocol.maxInvLength", 50_000); // defaults.setProperty("protocol.maxAddrLength", 1_000); // defaults.setProperty("protocol.services", 1); // defaults.setProperty("protocol.remoteServices", 1); // defaults.setProperty("protocol.version", 1); // TODO Change to 2 after // // implementation. // defaults.setProperty("pow.averageNonceTrialsPerByte", 320); // defaults.setProperty("pow.payloadLengthExtraBytes", 14_000); // defaults.setProperty("pow.systemLoad", 0.5f); // defaults.setProperty("pow.iterationfactor", 100); // defaults.setProperty("network.connectTimeout", 5_000); // defaults.setProperty("network.timeout", 10_000); // defaults.setProperty("network.listenPort", 8443); // defaults.setProperty("network.passiveMode.maxConnections", 8); // defaults.setProperty("network.activeMode.maxConnections", 16); // defaults.setProperty("network.activeMode.stopListenConnectionCount", 32); // defaults.setProperty("network.userAgent", // "/" + defaults.getString("global.name") + ":" + defaults.getString("global.version") + "/"); // defaults.setProperty("data.maxNodeStorageTime", 3600 * 3); // Seconds // } // // private static final Options instance = new Options(defaults); // // public static Options getInstance() { // return instance; // } // // private Options(Properties defaults) { // super(defaults); // } // // public float getFloat(String key) { // try { // return Float.valueOf(getProperty(key)); // } catch (NumberFormatException e) { // LOG.log(Level.SEVERE, "Not a float: " + getProperty(key), e); // System.exit(1); // return 0; // } // } // // public int getInt(String key) { // try { // return Integer.valueOf(getProperty(key)); // } catch (NumberFormatException e) { // LOG.log(Level.SEVERE, "Not an integer: " + getProperty(key), e); // System.exit(1); // return 0; // } // } // // public long getLong(String key) { // try { // return Long.valueOf(getProperty(key)); // } catch (NumberFormatException e) { // LOG.log(Level.SEVERE, "Not a long: " + getProperty(key), e); // System.exit(1); // return 0; // } // } // // @Override // public String getProperty(String key) { // String result = super.getProperty(key); // // if (result == null) { // throw new NullPointerException("Property not found: " + key); // } else { // return result; // } // } // // public String getString(String key) { // return getProperty(key); // } // // public Object setProperty(String key, float value) { // return setProperty(key, String.valueOf(value)); // } // // public Object setProperty(String key, int value) { // return setProperty(key, String.valueOf(value)); // } // // public Object setProperty(String key, long value) { // return setProperty(key, String.valueOf(value)); // } // } // Path: src/main/java/sibbo/bitmessage/network/protocol/InvMessage.java import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import sibbo.bitmessage.Options; package sibbo.bitmessage.network.protocol; /** * A message to advertise inventory objects. * * @author Sebastian Schmidt * @version 1.0 */ public class InvMessage extends P2PMessage { private static final Logger LOG = Logger.getLogger(InvMessage.class.getName()); /** The command string for this message type. */ public static final String COMMAND = "inv"; /** The inventory vectors. */ private List<InventoryVectorMessage> inv; /** * Creates a new inv message with the given inventory vectors. * * @param inv * The inventory vectors. */ public InvMessage(Collection<? extends InventoryVectorMessage> inv, MessageFactory factory) { super(factory); Objects.requireNonNull(inv, "inv must not be null.");
if (inv.size() > Options.getInstance().getInt("protocol.maxInvLength")) {
ISibboI/JBitmessage
src/main/java/sibbo/bitmessage/network/protocol/BaseMessage.java
// Path: src/main/java/sibbo/bitmessage/crypt/Digest.java // public final class Digest { // private static final Logger LOG = Logger.getLogger(Digest.class.getName()); // // /** // * Calculates the HmacSHA256 from the given key and data. // * // * @param data // * The data. // * @param key // * The key. // * @return The HmacSHA256. // */ // public static byte[] hmacSHA256(byte[] data, byte[] key) { // try { // Mac mac = Mac.getInstance("HmacSHA256", "BC"); // mac.init(new SecretKeySpec(key, "HmacSHA256")); // return mac.doFinal(data); // } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException e) { // LOG.log(Level.SEVERE, "Could not generate HMAC.", e); // System.exit(1); // return null; // } // } // // /** // * Calculates the digest of the given key pair. // * // * @param publicSigningKey // * The public signing key. // * @param publicEncryptionKey // * The public encryption key. // * @return The digest of the given key pair. // */ // public static byte[] keyDigest(ECPublicKey publicSigningKey, ECPublicKey publicEncryptionKey) { // return ripemd160(sha512(Util.getBytes(publicSigningKey), Util.getBytes(publicEncryptionKey))); // } // // /** // * Returns the ripemd160 sum of the given data. // * // * @param data // * The data. // * @return The ripemd160 sum of the given data. // */ // public static byte[] ripemd160(byte[] data) { // MessageDigest ripemd160; // // try { // ripemd160 = MessageDigest.getInstance("ripemd160"); // // return ripemd160.digest(data); // } catch (NoSuchAlgorithmException e) { // LOG.log(Level.SEVERE, "ripemd160 not supported!", e); // System.exit(1); // return null; // } // } // // /** // * Returns the sha512 sum of {@code bytes}. // * // * @param bytes // * The input for sha512. // * @return The sha512 sum of {@code bytes}. // */ // public static byte[] sha512(byte[] data) { // return sha512(data, 64); // } // // /** // * Returns the sha512 sum of all given bytes. // * // * @param data // * The bytes // * @return The sha512 sum of all given bytes. // */ // public static byte[] sha512(byte[]... data) { // MessageDigest sha512; // // try { // sha512 = MessageDigest.getInstance("SHA-512"); // // for (byte[] bytes : data) { // sha512.update(bytes); // } // // return sha512.digest(); // } catch (NoSuchAlgorithmException e) { // LOG.log(Level.SEVERE, "SHA-512 not supported!", e); // System.exit(1); // return null; // } // } // // /** // * Returns the first {@code digestLength} bytes of the sha512 sum of // * {@code bytes}. // * // * @param bytes // * The input for sha512. // * @param digestLength // * The number of bytes to return. // * @return The first {@code digestLength} bytes of the sha512 sum of // * {@code bytes}.. // */ // public static byte[] sha512(byte[] bytes, int digestLength) { // MessageDigest sha512; // // try { // sha512 = MessageDigest.getInstance("SHA-512"); // byte[] sum = sha512.digest(bytes); // return Arrays.copyOf(sum, digestLength); // } catch (NoSuchAlgorithmException e) { // LOG.log(Level.SEVERE, "SHA-512 not supported!", e); // System.exit(1); // return null; // } // } // // /** Utility class */ // private Digest() { // } // }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import sibbo.bitmessage.crypt.Digest;
public int getLength() { return length; } public byte[] getChecksum() { return checksum; } public P2PMessage getPayload() { return payload; } public byte[] getBytes() { ByteArrayOutputStream b = new ByteArrayOutputStream(); try { b.write(magic); byte[] ascii = command.getBytes("ASCII"); for (int i = 0; i < 12; i++) { if (i < ascii.length) { b.write(ascii[i]); } else { b.write(0); } } byte[] pbytes = payload.getBytes(); length = pbytes.length;
// Path: src/main/java/sibbo/bitmessage/crypt/Digest.java // public final class Digest { // private static final Logger LOG = Logger.getLogger(Digest.class.getName()); // // /** // * Calculates the HmacSHA256 from the given key and data. // * // * @param data // * The data. // * @param key // * The key. // * @return The HmacSHA256. // */ // public static byte[] hmacSHA256(byte[] data, byte[] key) { // try { // Mac mac = Mac.getInstance("HmacSHA256", "BC"); // mac.init(new SecretKeySpec(key, "HmacSHA256")); // return mac.doFinal(data); // } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException e) { // LOG.log(Level.SEVERE, "Could not generate HMAC.", e); // System.exit(1); // return null; // } // } // // /** // * Calculates the digest of the given key pair. // * // * @param publicSigningKey // * The public signing key. // * @param publicEncryptionKey // * The public encryption key. // * @return The digest of the given key pair. // */ // public static byte[] keyDigest(ECPublicKey publicSigningKey, ECPublicKey publicEncryptionKey) { // return ripemd160(sha512(Util.getBytes(publicSigningKey), Util.getBytes(publicEncryptionKey))); // } // // /** // * Returns the ripemd160 sum of the given data. // * // * @param data // * The data. // * @return The ripemd160 sum of the given data. // */ // public static byte[] ripemd160(byte[] data) { // MessageDigest ripemd160; // // try { // ripemd160 = MessageDigest.getInstance("ripemd160"); // // return ripemd160.digest(data); // } catch (NoSuchAlgorithmException e) { // LOG.log(Level.SEVERE, "ripemd160 not supported!", e); // System.exit(1); // return null; // } // } // // /** // * Returns the sha512 sum of {@code bytes}. // * // * @param bytes // * The input for sha512. // * @return The sha512 sum of {@code bytes}. // */ // public static byte[] sha512(byte[] data) { // return sha512(data, 64); // } // // /** // * Returns the sha512 sum of all given bytes. // * // * @param data // * The bytes // * @return The sha512 sum of all given bytes. // */ // public static byte[] sha512(byte[]... data) { // MessageDigest sha512; // // try { // sha512 = MessageDigest.getInstance("SHA-512"); // // for (byte[] bytes : data) { // sha512.update(bytes); // } // // return sha512.digest(); // } catch (NoSuchAlgorithmException e) { // LOG.log(Level.SEVERE, "SHA-512 not supported!", e); // System.exit(1); // return null; // } // } // // /** // * Returns the first {@code digestLength} bytes of the sha512 sum of // * {@code bytes}. // * // * @param bytes // * The input for sha512. // * @param digestLength // * The number of bytes to return. // * @return The first {@code digestLength} bytes of the sha512 sum of // * {@code bytes}.. // */ // public static byte[] sha512(byte[] bytes, int digestLength) { // MessageDigest sha512; // // try { // sha512 = MessageDigest.getInstance("SHA-512"); // byte[] sum = sha512.digest(bytes); // return Arrays.copyOf(sum, digestLength); // } catch (NoSuchAlgorithmException e) { // LOG.log(Level.SEVERE, "SHA-512 not supported!", e); // System.exit(1); // return null; // } // } // // /** Utility class */ // private Digest() { // } // } // Path: src/main/java/sibbo/bitmessage/network/protocol/BaseMessage.java import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import sibbo.bitmessage.crypt.Digest; public int getLength() { return length; } public byte[] getChecksum() { return checksum; } public P2PMessage getPayload() { return payload; } public byte[] getBytes() { ByteArrayOutputStream b = new ByteArrayOutputStream(); try { b.write(magic); byte[] ascii = command.getBytes("ASCII"); for (int i = 0; i < 12; i++) { if (i < ascii.length) { b.write(ascii[i]); } else { b.write(0); } } byte[] pbytes = payload.getBytes(); length = pbytes.length;
checksum = Digest.sha512(pbytes, 4);
ISibboI/JBitmessage
src/main/java/sibbo/bitmessage/network/protocol/AddrMessage.java
// Path: src/main/java/sibbo/bitmessage/Options.java // public class Options extends Properties { // private static final Logger LOG = Logger.getLogger(Options.class.getName()); // // private static final Options defaults = new Options(null); // // static { // defaults.setProperty("global.version", "0.0.0"); // defaults.setProperty("global.name", "JBitmessage"); // // defaults.setProperty("protocol.maxMessageLength", 10 * 1024 * 1024); // defaults.setProperty("protocol.maxInvLength", 50_000); // defaults.setProperty("protocol.maxAddrLength", 1_000); // defaults.setProperty("protocol.services", 1); // defaults.setProperty("protocol.remoteServices", 1); // defaults.setProperty("protocol.version", 1); // TODO Change to 2 after // // implementation. // defaults.setProperty("pow.averageNonceTrialsPerByte", 320); // defaults.setProperty("pow.payloadLengthExtraBytes", 14_000); // defaults.setProperty("pow.systemLoad", 0.5f); // defaults.setProperty("pow.iterationfactor", 100); // defaults.setProperty("network.connectTimeout", 5_000); // defaults.setProperty("network.timeout", 10_000); // defaults.setProperty("network.listenPort", 8443); // defaults.setProperty("network.passiveMode.maxConnections", 8); // defaults.setProperty("network.activeMode.maxConnections", 16); // defaults.setProperty("network.activeMode.stopListenConnectionCount", 32); // defaults.setProperty("network.userAgent", // "/" + defaults.getString("global.name") + ":" + defaults.getString("global.version") + "/"); // defaults.setProperty("data.maxNodeStorageTime", 3600 * 3); // Seconds // } // // private static final Options instance = new Options(defaults); // // public static Options getInstance() { // return instance; // } // // private Options(Properties defaults) { // super(defaults); // } // // public float getFloat(String key) { // try { // return Float.valueOf(getProperty(key)); // } catch (NumberFormatException e) { // LOG.log(Level.SEVERE, "Not a float: " + getProperty(key), e); // System.exit(1); // return 0; // } // } // // public int getInt(String key) { // try { // return Integer.valueOf(getProperty(key)); // } catch (NumberFormatException e) { // LOG.log(Level.SEVERE, "Not an integer: " + getProperty(key), e); // System.exit(1); // return 0; // } // } // // public long getLong(String key) { // try { // return Long.valueOf(getProperty(key)); // } catch (NumberFormatException e) { // LOG.log(Level.SEVERE, "Not a long: " + getProperty(key), e); // System.exit(1); // return 0; // } // } // // @Override // public String getProperty(String key) { // String result = super.getProperty(key); // // if (result == null) { // throw new NullPointerException("Property not found: " + key); // } else { // return result; // } // } // // public String getString(String key) { // return getProperty(key); // } // // public Object setProperty(String key, float value) { // return setProperty(key, String.valueOf(value)); // } // // public Object setProperty(String key, int value) { // return setProperty(key, String.valueOf(value)); // } // // public Object setProperty(String key, long value) { // return setProperty(key, String.valueOf(value)); // } // }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import sibbo.bitmessage.Options;
package sibbo.bitmessage.network.protocol; /** * A message to inform a node about my known nodes. * * @author Sebastian Schmidt * @version 1.0 * */ public class AddrMessage extends P2PMessage { private static final Logger LOG = Logger.getLogger(AddrMessage.class.getName()); /** The command string for this message type. */ public static final String COMMAND = "addr"; /** The list of addresses. */ private List<NetworkAddressMessage> addresses; /** * Creates a new add message. * * @param addresses * The address list. */ public AddrMessage(Collection<? extends NetworkAddressMessage> addresses, MessageFactory factory) { super(factory); Objects.requireNonNull(addresses, "addresses must not be null.");
// Path: src/main/java/sibbo/bitmessage/Options.java // public class Options extends Properties { // private static final Logger LOG = Logger.getLogger(Options.class.getName()); // // private static final Options defaults = new Options(null); // // static { // defaults.setProperty("global.version", "0.0.0"); // defaults.setProperty("global.name", "JBitmessage"); // // defaults.setProperty("protocol.maxMessageLength", 10 * 1024 * 1024); // defaults.setProperty("protocol.maxInvLength", 50_000); // defaults.setProperty("protocol.maxAddrLength", 1_000); // defaults.setProperty("protocol.services", 1); // defaults.setProperty("protocol.remoteServices", 1); // defaults.setProperty("protocol.version", 1); // TODO Change to 2 after // // implementation. // defaults.setProperty("pow.averageNonceTrialsPerByte", 320); // defaults.setProperty("pow.payloadLengthExtraBytes", 14_000); // defaults.setProperty("pow.systemLoad", 0.5f); // defaults.setProperty("pow.iterationfactor", 100); // defaults.setProperty("network.connectTimeout", 5_000); // defaults.setProperty("network.timeout", 10_000); // defaults.setProperty("network.listenPort", 8443); // defaults.setProperty("network.passiveMode.maxConnections", 8); // defaults.setProperty("network.activeMode.maxConnections", 16); // defaults.setProperty("network.activeMode.stopListenConnectionCount", 32); // defaults.setProperty("network.userAgent", // "/" + defaults.getString("global.name") + ":" + defaults.getString("global.version") + "/"); // defaults.setProperty("data.maxNodeStorageTime", 3600 * 3); // Seconds // } // // private static final Options instance = new Options(defaults); // // public static Options getInstance() { // return instance; // } // // private Options(Properties defaults) { // super(defaults); // } // // public float getFloat(String key) { // try { // return Float.valueOf(getProperty(key)); // } catch (NumberFormatException e) { // LOG.log(Level.SEVERE, "Not a float: " + getProperty(key), e); // System.exit(1); // return 0; // } // } // // public int getInt(String key) { // try { // return Integer.valueOf(getProperty(key)); // } catch (NumberFormatException e) { // LOG.log(Level.SEVERE, "Not an integer: " + getProperty(key), e); // System.exit(1); // return 0; // } // } // // public long getLong(String key) { // try { // return Long.valueOf(getProperty(key)); // } catch (NumberFormatException e) { // LOG.log(Level.SEVERE, "Not a long: " + getProperty(key), e); // System.exit(1); // return 0; // } // } // // @Override // public String getProperty(String key) { // String result = super.getProperty(key); // // if (result == null) { // throw new NullPointerException("Property not found: " + key); // } else { // return result; // } // } // // public String getString(String key) { // return getProperty(key); // } // // public Object setProperty(String key, float value) { // return setProperty(key, String.valueOf(value)); // } // // public Object setProperty(String key, int value) { // return setProperty(key, String.valueOf(value)); // } // // public Object setProperty(String key, long value) { // return setProperty(key, String.valueOf(value)); // } // } // Path: src/main/java/sibbo/bitmessage/network/protocol/AddrMessage.java import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import sibbo.bitmessage.Options; package sibbo.bitmessage.network.protocol; /** * A message to inform a node about my known nodes. * * @author Sebastian Schmidt * @version 1.0 * */ public class AddrMessage extends P2PMessage { private static final Logger LOG = Logger.getLogger(AddrMessage.class.getName()); /** The command string for this message type. */ public static final String COMMAND = "addr"; /** The list of addresses. */ private List<NetworkAddressMessage> addresses; /** * Creates a new add message. * * @param addresses * The address list. */ public AddrMessage(Collection<? extends NetworkAddressMessage> addresses, MessageFactory factory) { super(factory); Objects.requireNonNull(addresses, "addresses must not be null.");
if (addresses.size() > Options.getInstance().getInt("protocol.maxAddrLength")) {
julian-urbano/MelodyShape
src/jurbano/melodyshape/ranking/Result.java
// Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // }
import jurbano.melodyshape.model.Melody;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.ranking; /** * A structure holding the similarity score for a particular document and query, * for ranking and printing purposes. * * @author Julián Urbano * @see Melody */ public class Result {
// Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // } // Path: src/jurbano/melodyshape/ranking/Result.java import jurbano.melodyshape.model.Melody; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.ranking; /** * A structure holding the similarity score for a particular document and query, * for ranking and printing purposes. * * @author Julián Urbano * @see Melody */ public class Result {
protected Melody melody;
julian-urbano/MelodyShape
src/jurbano/melodyshape/comparison/NGramMelodyComparer.java
// Path: src/jurbano/melodyshape/comparison/alignment/MelodyAligner.java // public interface MelodyAligner // { // /** // * Gets the name of this {@code MelodyAligner}. // * // * @return the name of this melody aligner. // */ // public String getName(); // // /** // * Computes an alignment score between two sequences of {@link NGram}s. // * <p> // * The alignment score is proportional to the similarity between the // * sequences, that is {@code align(s1, s2) > align(s1, s3)} means that // * sequence {@code s2} is more similar to {@code s1} than {@code s3} is. // * // * @param s1 // * the first sequence of n-grams. // * @param s2 // * the second sequence of n-grams. // * @return the alignment score. // */ // public double align(ArrayList<NGram> s1, ArrayList<NGram> s2); // } // // Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // }
import jurbano.melodyshape.model.Melody; import java.util.ArrayList; import jurbano.melodyshape.comparison.alignment.MelodyAligner;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison; /** * A function that computes a similarity score between two {@link Melody} * objects by applying an alignment algorithm upon the sequence of n-grams for * each melody. * * @author Julián Urbano * @see Melody * @see MelodyAligner */ public class NGramMelodyComparer implements MelodyComparer { protected int nGramLength;
// Path: src/jurbano/melodyshape/comparison/alignment/MelodyAligner.java // public interface MelodyAligner // { // /** // * Gets the name of this {@code MelodyAligner}. // * // * @return the name of this melody aligner. // */ // public String getName(); // // /** // * Computes an alignment score between two sequences of {@link NGram}s. // * <p> // * The alignment score is proportional to the similarity between the // * sequences, that is {@code align(s1, s2) > align(s1, s3)} means that // * sequence {@code s2} is more similar to {@code s1} than {@code s3} is. // * // * @param s1 // * the first sequence of n-grams. // * @param s2 // * the second sequence of n-grams. // * @return the alignment score. // */ // public double align(ArrayList<NGram> s1, ArrayList<NGram> s2); // } // // Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // } // Path: src/jurbano/melodyshape/comparison/NGramMelodyComparer.java import jurbano.melodyshape.model.Melody; import java.util.ArrayList; import jurbano.melodyshape.comparison.alignment.MelodyAligner; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison; /** * A function that computes a similarity score between two {@link Melody} * objects by applying an alignment algorithm upon the sequence of n-grams for * each melody. * * @author Julián Urbano * @see Melody * @see MelodyAligner */ public class NGramMelodyComparer implements MelodyComparer { protected int nGramLength;
protected MelodyAligner aligner;
julian-urbano/MelodyShape
src/jurbano/melodyshape/comparison/NGramMelodyComparer.java
// Path: src/jurbano/melodyshape/comparison/alignment/MelodyAligner.java // public interface MelodyAligner // { // /** // * Gets the name of this {@code MelodyAligner}. // * // * @return the name of this melody aligner. // */ // public String getName(); // // /** // * Computes an alignment score between two sequences of {@link NGram}s. // * <p> // * The alignment score is proportional to the similarity between the // * sequences, that is {@code align(s1, s2) > align(s1, s3)} means that // * sequence {@code s2} is more similar to {@code s1} than {@code s3} is. // * // * @param s1 // * the first sequence of n-grams. // * @param s2 // * the second sequence of n-grams. // * @return the alignment score. // */ // public double align(ArrayList<NGram> s1, ArrayList<NGram> s2); // } // // Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // }
import jurbano.melodyshape.model.Melody; import java.util.ArrayList; import jurbano.melodyshape.comparison.alignment.MelodyAligner;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison; /** * A function that computes a similarity score between two {@link Melody} * objects by applying an alignment algorithm upon the sequence of n-grams for * each melody. * * @author Julián Urbano * @see Melody * @see MelodyAligner */ public class NGramMelodyComparer implements MelodyComparer { protected int nGramLength; protected MelodyAligner aligner; /** * Constructs a new {@code NGramMelodyComparer}. * * @param nGramLength * the n-gram length, that is, number of {@code Note}s. * @param aligner * the alignment algorithm to use. */ public NGramMelodyComparer(int nGramLength, MelodyAligner aligner) { this.nGramLength = nGramLength; this.aligner = aligner; } /** * {@inheritDoc} */ @Override
// Path: src/jurbano/melodyshape/comparison/alignment/MelodyAligner.java // public interface MelodyAligner // { // /** // * Gets the name of this {@code MelodyAligner}. // * // * @return the name of this melody aligner. // */ // public String getName(); // // /** // * Computes an alignment score between two sequences of {@link NGram}s. // * <p> // * The alignment score is proportional to the similarity between the // * sequences, that is {@code align(s1, s2) > align(s1, s3)} means that // * sequence {@code s2} is more similar to {@code s1} than {@code s3} is. // * // * @param s1 // * the first sequence of n-grams. // * @param s2 // * the second sequence of n-grams. // * @return the alignment score. // */ // public double align(ArrayList<NGram> s1, ArrayList<NGram> s2); // } // // Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // } // Path: src/jurbano/melodyshape/comparison/NGramMelodyComparer.java import jurbano.melodyshape.model.Melody; import java.util.ArrayList; import jurbano.melodyshape.comparison.alignment.MelodyAligner; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison; /** * A function that computes a similarity score between two {@link Melody} * objects by applying an alignment algorithm upon the sequence of n-grams for * each melody. * * @author Julián Urbano * @see Melody * @see MelodyAligner */ public class NGramMelodyComparer implements MelodyComparer { protected int nGramLength; protected MelodyAligner aligner; /** * Constructs a new {@code NGramMelodyComparer}. * * @param nGramLength * the n-gram length, that is, number of {@code Note}s. * @param aligner * the alignment algorithm to use. */ public NGramMelodyComparer(int nGramLength, MelodyAligner aligner) { this.nGramLength = nGramLength; this.aligner = aligner; } /** * {@inheritDoc} */ @Override
public double compare(Melody m1, Melody m2) {
julian-urbano/MelodyShape
src/jurbano/melodyshape/comparison/alignment/GlobalAligner.java
// Path: src/jurbano/melodyshape/comparison/NGram.java // @SuppressWarnings("serial") // public class NGram extends ArrayList<Note> // { // /** // * Gets a null n-gram of this object. A null n-gram contains the same notes // * but with all notes set to the pitch of this n-gram's first note. // * // * @return the null n-gram. // */ // public NGram getNullSpan() { // NGram s = new NGram(); // for (Note n : this) // s.add(new Note(this.get(0).getPitch(), n.getOnset(), n.getDuration(), n.getRestFraction())); // return s; // } // // /** // * Gets the sequence of {@code n}-grams, each containing {@code n} // * {@link Note} objects, from the {@link Melody} specified. // * // * @param m // * the melody. // * @param n // * the length of the n-grams. // * @return the sequence of {@code n}-grams. // */ // public static ArrayList<NGram> getNGrams(Melody m, int n) { // ArrayList<NGram> list = new ArrayList<NGram>(); // // for (int i = 0; i <= m.size() - n; i++) { // NGram gram = new NGram(); // for (int j = 0; j < n; j++) // gram.add(m.get(i + j)); // list.add(gram); // } // // return list; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // String res = ""; // for (Note n : this) // res += "{" + n.getPitch() + "," + n.getDuration() + "," + n.getRestFraction() + "}"; // return res; // } // } // // Path: src/jurbano/melodyshape/comparison/NGramComparer.java // public interface NGramComparer // { // /** // * Gets the name of this {@code NGramComparer}. // * // * @return the name of this n-gram comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two n-grams. // * <p> // * The similarity score is proportional to the melodic similarity between // * the notes in each n-gram, that is // * {@code compare(n1, n2) > compare(n1, n3)} means that n-gram {@code n2} is // * more similar to {@code n1} than {@code n3} is. // * // * @param g1 // * the first n-gram to compare. // * @param g2 // * the second n-gram to compare. // * @return the similarity score. // */ // public double compare(NGram g1, NGram g2); // // /** // * Gets an identifier for an {@link NGram} object according to this // * {@link NGramComparer}. This method is intended to identify different // * n-grams that are considered as the same by this {@code NGramComparer} and // * thus speed up computations and tune similarity scores in different // * algorithms. // * <p> // * For instance, if this {@code NGramComparer} only considers the pitch // * dimension of melodies, no information about time should appear in an // * {@link NGram}'s identifier. // * // * @param g // * the n-gram to compute the identifier for. // * @return the identifier. // */ // public String getNGramId(NGram g); // }
import jurbano.melodyshape.comparison.NGramComparer; import java.util.ArrayList; import jurbano.melodyshape.comparison.NGram;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison.alignment; /** * An implementation of the Needleman-Wunsch alignment algorithm for sequences of {@link NGram}s. * * @author Julián Urbano * @see NGram * @see NGramComparer */ public class GlobalAligner implements MelodyAligner {
// Path: src/jurbano/melodyshape/comparison/NGram.java // @SuppressWarnings("serial") // public class NGram extends ArrayList<Note> // { // /** // * Gets a null n-gram of this object. A null n-gram contains the same notes // * but with all notes set to the pitch of this n-gram's first note. // * // * @return the null n-gram. // */ // public NGram getNullSpan() { // NGram s = new NGram(); // for (Note n : this) // s.add(new Note(this.get(0).getPitch(), n.getOnset(), n.getDuration(), n.getRestFraction())); // return s; // } // // /** // * Gets the sequence of {@code n}-grams, each containing {@code n} // * {@link Note} objects, from the {@link Melody} specified. // * // * @param m // * the melody. // * @param n // * the length of the n-grams. // * @return the sequence of {@code n}-grams. // */ // public static ArrayList<NGram> getNGrams(Melody m, int n) { // ArrayList<NGram> list = new ArrayList<NGram>(); // // for (int i = 0; i <= m.size() - n; i++) { // NGram gram = new NGram(); // for (int j = 0; j < n; j++) // gram.add(m.get(i + j)); // list.add(gram); // } // // return list; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // String res = ""; // for (Note n : this) // res += "{" + n.getPitch() + "," + n.getDuration() + "," + n.getRestFraction() + "}"; // return res; // } // } // // Path: src/jurbano/melodyshape/comparison/NGramComparer.java // public interface NGramComparer // { // /** // * Gets the name of this {@code NGramComparer}. // * // * @return the name of this n-gram comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two n-grams. // * <p> // * The similarity score is proportional to the melodic similarity between // * the notes in each n-gram, that is // * {@code compare(n1, n2) > compare(n1, n3)} means that n-gram {@code n2} is // * more similar to {@code n1} than {@code n3} is. // * // * @param g1 // * the first n-gram to compare. // * @param g2 // * the second n-gram to compare. // * @return the similarity score. // */ // public double compare(NGram g1, NGram g2); // // /** // * Gets an identifier for an {@link NGram} object according to this // * {@link NGramComparer}. This method is intended to identify different // * n-grams that are considered as the same by this {@code NGramComparer} and // * thus speed up computations and tune similarity scores in different // * algorithms. // * <p> // * For instance, if this {@code NGramComparer} only considers the pitch // * dimension of melodies, no information about time should appear in an // * {@link NGram}'s identifier. // * // * @param g // * the n-gram to compute the identifier for. // * @return the identifier. // */ // public String getNGramId(NGram g); // } // Path: src/jurbano/melodyshape/comparison/alignment/GlobalAligner.java import jurbano.melodyshape.comparison.NGramComparer; import java.util.ArrayList; import jurbano.melodyshape.comparison.NGram; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison.alignment; /** * An implementation of the Needleman-Wunsch alignment algorithm for sequences of {@link NGram}s. * * @author Julián Urbano * @see NGram * @see NGramComparer */ public class GlobalAligner implements MelodyAligner {
protected NGramComparer comparer;
julian-urbano/MelodyShape
src/jurbano/melodyshape/comparison/alignment/GlobalAligner.java
// Path: src/jurbano/melodyshape/comparison/NGram.java // @SuppressWarnings("serial") // public class NGram extends ArrayList<Note> // { // /** // * Gets a null n-gram of this object. A null n-gram contains the same notes // * but with all notes set to the pitch of this n-gram's first note. // * // * @return the null n-gram. // */ // public NGram getNullSpan() { // NGram s = new NGram(); // for (Note n : this) // s.add(new Note(this.get(0).getPitch(), n.getOnset(), n.getDuration(), n.getRestFraction())); // return s; // } // // /** // * Gets the sequence of {@code n}-grams, each containing {@code n} // * {@link Note} objects, from the {@link Melody} specified. // * // * @param m // * the melody. // * @param n // * the length of the n-grams. // * @return the sequence of {@code n}-grams. // */ // public static ArrayList<NGram> getNGrams(Melody m, int n) { // ArrayList<NGram> list = new ArrayList<NGram>(); // // for (int i = 0; i <= m.size() - n; i++) { // NGram gram = new NGram(); // for (int j = 0; j < n; j++) // gram.add(m.get(i + j)); // list.add(gram); // } // // return list; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // String res = ""; // for (Note n : this) // res += "{" + n.getPitch() + "," + n.getDuration() + "," + n.getRestFraction() + "}"; // return res; // } // } // // Path: src/jurbano/melodyshape/comparison/NGramComparer.java // public interface NGramComparer // { // /** // * Gets the name of this {@code NGramComparer}. // * // * @return the name of this n-gram comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two n-grams. // * <p> // * The similarity score is proportional to the melodic similarity between // * the notes in each n-gram, that is // * {@code compare(n1, n2) > compare(n1, n3)} means that n-gram {@code n2} is // * more similar to {@code n1} than {@code n3} is. // * // * @param g1 // * the first n-gram to compare. // * @param g2 // * the second n-gram to compare. // * @return the similarity score. // */ // public double compare(NGram g1, NGram g2); // // /** // * Gets an identifier for an {@link NGram} object according to this // * {@link NGramComparer}. This method is intended to identify different // * n-grams that are considered as the same by this {@code NGramComparer} and // * thus speed up computations and tune similarity scores in different // * algorithms. // * <p> // * For instance, if this {@code NGramComparer} only considers the pitch // * dimension of melodies, no information about time should appear in an // * {@link NGram}'s identifier. // * // * @param g // * the n-gram to compute the identifier for. // * @return the identifier. // */ // public String getNGramId(NGram g); // }
import jurbano.melodyshape.comparison.NGramComparer; import java.util.ArrayList; import jurbano.melodyshape.comparison.NGram;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison.alignment; /** * An implementation of the Needleman-Wunsch alignment algorithm for sequences of {@link NGram}s. * * @author Julián Urbano * @see NGram * @see NGramComparer */ public class GlobalAligner implements MelodyAligner { protected NGramComparer comparer; /** * Constructs a new {@code GlobalAligner} with the specified * {@link NGramComparer}. * * @param comparer * the n-gram comparer to use. */ public GlobalAligner(NGramComparer comparer) { this.comparer = comparer; } /** * {@inheritDoc} * * @return the {@link String} {@code "Global(comparer)"}, where * {@code comparer} is the name of the underlying * {@link NGramComparer}. */ @Override public String getName() { return "Global("+this.comparer.getName()+")"; } /** * {@inheritDoc} */ @Override
// Path: src/jurbano/melodyshape/comparison/NGram.java // @SuppressWarnings("serial") // public class NGram extends ArrayList<Note> // { // /** // * Gets a null n-gram of this object. A null n-gram contains the same notes // * but with all notes set to the pitch of this n-gram's first note. // * // * @return the null n-gram. // */ // public NGram getNullSpan() { // NGram s = new NGram(); // for (Note n : this) // s.add(new Note(this.get(0).getPitch(), n.getOnset(), n.getDuration(), n.getRestFraction())); // return s; // } // // /** // * Gets the sequence of {@code n}-grams, each containing {@code n} // * {@link Note} objects, from the {@link Melody} specified. // * // * @param m // * the melody. // * @param n // * the length of the n-grams. // * @return the sequence of {@code n}-grams. // */ // public static ArrayList<NGram> getNGrams(Melody m, int n) { // ArrayList<NGram> list = new ArrayList<NGram>(); // // for (int i = 0; i <= m.size() - n; i++) { // NGram gram = new NGram(); // for (int j = 0; j < n; j++) // gram.add(m.get(i + j)); // list.add(gram); // } // // return list; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // String res = ""; // for (Note n : this) // res += "{" + n.getPitch() + "," + n.getDuration() + "," + n.getRestFraction() + "}"; // return res; // } // } // // Path: src/jurbano/melodyshape/comparison/NGramComparer.java // public interface NGramComparer // { // /** // * Gets the name of this {@code NGramComparer}. // * // * @return the name of this n-gram comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two n-grams. // * <p> // * The similarity score is proportional to the melodic similarity between // * the notes in each n-gram, that is // * {@code compare(n1, n2) > compare(n1, n3)} means that n-gram {@code n2} is // * more similar to {@code n1} than {@code n3} is. // * // * @param g1 // * the first n-gram to compare. // * @param g2 // * the second n-gram to compare. // * @return the similarity score. // */ // public double compare(NGram g1, NGram g2); // // /** // * Gets an identifier for an {@link NGram} object according to this // * {@link NGramComparer}. This method is intended to identify different // * n-grams that are considered as the same by this {@code NGramComparer} and // * thus speed up computations and tune similarity scores in different // * algorithms. // * <p> // * For instance, if this {@code NGramComparer} only considers the pitch // * dimension of melodies, no information about time should appear in an // * {@link NGram}'s identifier. // * // * @param g // * the n-gram to compute the identifier for. // * @return the identifier. // */ // public String getNGramId(NGram g); // } // Path: src/jurbano/melodyshape/comparison/alignment/GlobalAligner.java import jurbano.melodyshape.comparison.NGramComparer; import java.util.ArrayList; import jurbano.melodyshape.comparison.NGram; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison.alignment; /** * An implementation of the Needleman-Wunsch alignment algorithm for sequences of {@link NGram}s. * * @author Julián Urbano * @see NGram * @see NGramComparer */ public class GlobalAligner implements MelodyAligner { protected NGramComparer comparer; /** * Constructs a new {@code GlobalAligner} with the specified * {@link NGramComparer}. * * @param comparer * the n-gram comparer to use. */ public GlobalAligner(NGramComparer comparer) { this.comparer = comparer; } /** * {@inheritDoc} * * @return the {@link String} {@code "Global(comparer)"}, where * {@code comparer} is the name of the underlying * {@link NGramComparer}. */ @Override public String getName() { return "Global("+this.comparer.getName()+")"; } /** * {@inheritDoc} */ @Override
public double align(ArrayList<NGram> s1, ArrayList<NGram> s2) {
julian-urbano/MelodyShape
src/jurbano/melodyshape/comparison/NGram.java
// Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // } // // Path: src/jurbano/melodyshape/model/Note.java // public class Note // { // protected long duration; // protected long onset; // protected byte pitch; // protected double restFraction; // // /** // * Constructs a new {@code Note}. // * // * @param pitch // * the pitch of the note. // * @param onset // * the onset time of the note. // * @param duration // * the duration of the note. // * @param restFraction // * the fraction of the note's duration that corresponds do rests. // */ // public Note(byte pitch, long onset, long duration, double restFraction) { // this.pitch = pitch; // this.onset = onset; // this.duration = duration; // this.restFraction = restFraction; // } // // /** // * Gets the duration of the note. // * // * @return the duration of the note. // */ // public long getDuration() { // return this.duration; // } // // /** // * Gets the onset time of the note. // * // * @return the onset time of the note. // */ // public long getOnset() { // return this.onset; // } // // /** // * Gets the pitch of the note. // * // * @return the pitch of the note. // */ // public byte getPitch() { // return this.pitch; // } // // /** // * Gets the fraction of the note's duration that corresponds to rests. // * // * @return the rest fraction. // */ // public double getRestFraction() { // return this.restFraction; // } // // @Override // public String toString() { // return "Note [@" + this.onset + ": pitch=" + this.pitch + ", duration=" + this.duration + ", rest=" + this.restFraction + "]"; // } // // }
import java.util.ArrayList; import jurbano.melodyshape.model.Melody; import jurbano.melodyshape.model.Note;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison; /** * An n-gram of notes, that is, a sequence of n consecutive {@link Note} * objects. * * @author Julián Urbano * @see Note */ @SuppressWarnings("serial") public class NGram extends ArrayList<Note> { /** * Gets a null n-gram of this object. A null n-gram contains the same notes * but with all notes set to the pitch of this n-gram's first note. * * @return the null n-gram. */ public NGram getNullSpan() { NGram s = new NGram(); for (Note n : this) s.add(new Note(this.get(0).getPitch(), n.getOnset(), n.getDuration(), n.getRestFraction())); return s; } /** * Gets the sequence of {@code n}-grams, each containing {@code n} * {@link Note} objects, from the {@link Melody} specified. * * @param m * the melody. * @param n * the length of the n-grams. * @return the sequence of {@code n}-grams. */
// Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // } // // Path: src/jurbano/melodyshape/model/Note.java // public class Note // { // protected long duration; // protected long onset; // protected byte pitch; // protected double restFraction; // // /** // * Constructs a new {@code Note}. // * // * @param pitch // * the pitch of the note. // * @param onset // * the onset time of the note. // * @param duration // * the duration of the note. // * @param restFraction // * the fraction of the note's duration that corresponds do rests. // */ // public Note(byte pitch, long onset, long duration, double restFraction) { // this.pitch = pitch; // this.onset = onset; // this.duration = duration; // this.restFraction = restFraction; // } // // /** // * Gets the duration of the note. // * // * @return the duration of the note. // */ // public long getDuration() { // return this.duration; // } // // /** // * Gets the onset time of the note. // * // * @return the onset time of the note. // */ // public long getOnset() { // return this.onset; // } // // /** // * Gets the pitch of the note. // * // * @return the pitch of the note. // */ // public byte getPitch() { // return this.pitch; // } // // /** // * Gets the fraction of the note's duration that corresponds to rests. // * // * @return the rest fraction. // */ // public double getRestFraction() { // return this.restFraction; // } // // @Override // public String toString() { // return "Note [@" + this.onset + ": pitch=" + this.pitch + ", duration=" + this.duration + ", rest=" + this.restFraction + "]"; // } // // } // Path: src/jurbano/melodyshape/comparison/NGram.java import java.util.ArrayList; import jurbano.melodyshape.model.Melody; import jurbano.melodyshape.model.Note; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison; /** * An n-gram of notes, that is, a sequence of n consecutive {@link Note} * objects. * * @author Julián Urbano * @see Note */ @SuppressWarnings("serial") public class NGram extends ArrayList<Note> { /** * Gets a null n-gram of this object. A null n-gram contains the same notes * but with all notes set to the pitch of this n-gram's first note. * * @return the null n-gram. */ public NGram getNullSpan() { NGram s = new NGram(); for (Note n : this) s.add(new Note(this.get(0).getPitch(), n.getOnset(), n.getDuration(), n.getRestFraction())); return s; } /** * Gets the sequence of {@code n}-grams, each containing {@code n} * {@link Note} objects, from the {@link Melody} specified. * * @param m * the melody. * @param n * the length of the n-grams. * @return the sequence of {@code n}-grams. */
public static ArrayList<NGram> getNGrams(Melody m, int n) {
julian-urbano/MelodyShape
src/jurbano/melodyshape/ranking/SimpleResultRanker.java
// Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // }
import jurbano.melodyshape.model.Melody; import java.util.Arrays; import java.util.Comparator;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.ranking; /** * A simple ranking function that sorts by decreasing similarity score, then by * increasing difference in length with the query, and then by melody * identifier. * * @author Julián Urbano * @see ResultRanker */ public class SimpleResultRanker implements ResultRanker { /** * {@inheritDoc} * * return the {@link String} {@code "Simple"}. */ @Override public String getName() { return "Simple"; } /** * {@inheritDoc} */ @Override
// Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // } // Path: src/jurbano/melodyshape/ranking/SimpleResultRanker.java import jurbano.melodyshape.model.Melody; import java.util.Arrays; import java.util.Comparator; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.ranking; /** * A simple ranking function that sorts by decreasing similarity score, then by * increasing difference in length with the query, and then by melody * identifier. * * @author Julián Urbano * @see ResultRanker */ public class SimpleResultRanker implements ResultRanker { /** * {@inheritDoc} * * return the {@link String} {@code "Simple"}. */ @Override public String getName() { return "Simple"; } /** * {@inheritDoc} */ @Override
public void rank(final Melody query, Result[] results, int k) {
julian-urbano/MelodyShape
src/jurbano/melodyshape/ui/UIObserver.java
// Path: src/jurbano/melodyshape/comparison/MelodyComparer.java // public interface MelodyComparer // { // /** // * Gets the name of this {@code MelodyComparer} // * // * @return the name of the melody comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two melodies. // * <p> // * The similarity score is proportional to the melodic similarity between // * the melodies, that is {@code compare(m1, m2) > compare(m1, m3)} means // * that melody {@code m2} is more similar to {@code m1} than {@code m3} is. // * // * @param m1 // * the first melody to compare. // * @param m2 // * the second melody to compare. // * @return the similarity score. // */ // public double compare(Melody m1, Melody m2); // } // // Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // } // // Path: src/jurbano/melodyshape/ranking/ResultRanker.java // public interface ResultRanker // { // /** // * Gets the name of this {@code ResultRanker}. // * // * @return the name of this result ranker. // */ // public String getName(); // // /** // * Ranks the top {@code k} {@link Result}s for the specified query // * {@link Melody}. Results are ranked in decreasing order of similarity to // * the query. // * // * @param query // * the query that originated the results. // * @param results // * the unranked list of results. // * @param k // * the cutoff. // */ // public void rank(Melody query, Result[] results, int k); // }
import jurbano.melodyshape.comparison.MelodyComparer; import jurbano.melodyshape.model.Melody; import jurbano.melodyshape.ranking.ResultRanker;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.ui; /** * Controls the execution of an algorithm with a user interface. * * @author Julián Urbano * @see ConsoleUIObserver */ public interface UIObserver { /** * Starts execution of the algorithm. */ public void start(); /** * Used to notify this {@code UIObserver} of the progress in executing a * {@link MelodyComparer} with a particular query. * * @param query * the query running. * @param numQuery * the number of query running. * @param totalQueries * the total number of queries to run. * @param progress * a number indicating the execution progress from 0 (just * started) to 1 (completed). */
// Path: src/jurbano/melodyshape/comparison/MelodyComparer.java // public interface MelodyComparer // { // /** // * Gets the name of this {@code MelodyComparer} // * // * @return the name of the melody comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two melodies. // * <p> // * The similarity score is proportional to the melodic similarity between // * the melodies, that is {@code compare(m1, m2) > compare(m1, m3)} means // * that melody {@code m2} is more similar to {@code m1} than {@code m3} is. // * // * @param m1 // * the first melody to compare. // * @param m2 // * the second melody to compare. // * @return the similarity score. // */ // public double compare(Melody m1, Melody m2); // } // // Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // } // // Path: src/jurbano/melodyshape/ranking/ResultRanker.java // public interface ResultRanker // { // /** // * Gets the name of this {@code ResultRanker}. // * // * @return the name of this result ranker. // */ // public String getName(); // // /** // * Ranks the top {@code k} {@link Result}s for the specified query // * {@link Melody}. Results are ranked in decreasing order of similarity to // * the query. // * // * @param query // * the query that originated the results. // * @param results // * the unranked list of results. // * @param k // * the cutoff. // */ // public void rank(Melody query, Result[] results, int k); // } // Path: src/jurbano/melodyshape/ui/UIObserver.java import jurbano.melodyshape.comparison.MelodyComparer; import jurbano.melodyshape.model.Melody; import jurbano.melodyshape.ranking.ResultRanker; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.ui; /** * Controls the execution of an algorithm with a user interface. * * @author Julián Urbano * @see ConsoleUIObserver */ public interface UIObserver { /** * Starts execution of the algorithm. */ public void start(); /** * Used to notify this {@code UIObserver} of the progress in executing a * {@link MelodyComparer} with a particular query. * * @param query * the query running. * @param numQuery * the number of query running. * @param totalQueries * the total number of queries to run. * @param progress * a number indicating the execution progress from 0 (just * started) to 1 (completed). */
public void updateProgressComparer(Melody query, int numQuery, int totalQueries, double progress);
julian-urbano/MelodyShape
src/jurbano/melodyshape/comparison/alignment/HybridAligner.java
// Path: src/jurbano/melodyshape/comparison/NGram.java // @SuppressWarnings("serial") // public class NGram extends ArrayList<Note> // { // /** // * Gets a null n-gram of this object. A null n-gram contains the same notes // * but with all notes set to the pitch of this n-gram's first note. // * // * @return the null n-gram. // */ // public NGram getNullSpan() { // NGram s = new NGram(); // for (Note n : this) // s.add(new Note(this.get(0).getPitch(), n.getOnset(), n.getDuration(), n.getRestFraction())); // return s; // } // // /** // * Gets the sequence of {@code n}-grams, each containing {@code n} // * {@link Note} objects, from the {@link Melody} specified. // * // * @param m // * the melody. // * @param n // * the length of the n-grams. // * @return the sequence of {@code n}-grams. // */ // public static ArrayList<NGram> getNGrams(Melody m, int n) { // ArrayList<NGram> list = new ArrayList<NGram>(); // // for (int i = 0; i <= m.size() - n; i++) { // NGram gram = new NGram(); // for (int j = 0; j < n; j++) // gram.add(m.get(i + j)); // list.add(gram); // } // // return list; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // String res = ""; // for (Note n : this) // res += "{" + n.getPitch() + "," + n.getDuration() + "," + n.getRestFraction() + "}"; // return res; // } // } // // Path: src/jurbano/melodyshape/comparison/NGramComparer.java // public interface NGramComparer // { // /** // * Gets the name of this {@code NGramComparer}. // * // * @return the name of this n-gram comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two n-grams. // * <p> // * The similarity score is proportional to the melodic similarity between // * the notes in each n-gram, that is // * {@code compare(n1, n2) > compare(n1, n3)} means that n-gram {@code n2} is // * more similar to {@code n1} than {@code n3} is. // * // * @param g1 // * the first n-gram to compare. // * @param g2 // * the second n-gram to compare. // * @return the similarity score. // */ // public double compare(NGram g1, NGram g2); // // /** // * Gets an identifier for an {@link NGram} object according to this // * {@link NGramComparer}. This method is intended to identify different // * n-grams that are considered as the same by this {@code NGramComparer} and // * thus speed up computations and tune similarity scores in different // * algorithms. // * <p> // * For instance, if this {@code NGramComparer} only considers the pitch // * dimension of melodies, no information about time should appear in an // * {@link NGram}'s identifier. // * // * @param g // * the n-gram to compute the identifier for. // * @return the identifier. // */ // public String getNGramId(NGram g); // }
import jurbano.melodyshape.comparison.NGramComparer; import java.util.ArrayList; import jurbano.melodyshape.comparison.NGram;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison.alignment; /** * An implementation of a hybrid alignment algorithm for sequences of * {@link NGram}s. * <p> * Like a global alignment algorithm, it penalizes changes at the beginning of * sequences, but the final alignment score is the maximum intermediate score * found in the alignment table. Thus, it does not penalize changes at the end * of sequences. * * @author Julián Urbano * @see NGram * @see NGramComparer */ public class HybridAligner implements MelodyAligner {
// Path: src/jurbano/melodyshape/comparison/NGram.java // @SuppressWarnings("serial") // public class NGram extends ArrayList<Note> // { // /** // * Gets a null n-gram of this object. A null n-gram contains the same notes // * but with all notes set to the pitch of this n-gram's first note. // * // * @return the null n-gram. // */ // public NGram getNullSpan() { // NGram s = new NGram(); // for (Note n : this) // s.add(new Note(this.get(0).getPitch(), n.getOnset(), n.getDuration(), n.getRestFraction())); // return s; // } // // /** // * Gets the sequence of {@code n}-grams, each containing {@code n} // * {@link Note} objects, from the {@link Melody} specified. // * // * @param m // * the melody. // * @param n // * the length of the n-grams. // * @return the sequence of {@code n}-grams. // */ // public static ArrayList<NGram> getNGrams(Melody m, int n) { // ArrayList<NGram> list = new ArrayList<NGram>(); // // for (int i = 0; i <= m.size() - n; i++) { // NGram gram = new NGram(); // for (int j = 0; j < n; j++) // gram.add(m.get(i + j)); // list.add(gram); // } // // return list; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // String res = ""; // for (Note n : this) // res += "{" + n.getPitch() + "," + n.getDuration() + "," + n.getRestFraction() + "}"; // return res; // } // } // // Path: src/jurbano/melodyshape/comparison/NGramComparer.java // public interface NGramComparer // { // /** // * Gets the name of this {@code NGramComparer}. // * // * @return the name of this n-gram comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two n-grams. // * <p> // * The similarity score is proportional to the melodic similarity between // * the notes in each n-gram, that is // * {@code compare(n1, n2) > compare(n1, n3)} means that n-gram {@code n2} is // * more similar to {@code n1} than {@code n3} is. // * // * @param g1 // * the first n-gram to compare. // * @param g2 // * the second n-gram to compare. // * @return the similarity score. // */ // public double compare(NGram g1, NGram g2); // // /** // * Gets an identifier for an {@link NGram} object according to this // * {@link NGramComparer}. This method is intended to identify different // * n-grams that are considered as the same by this {@code NGramComparer} and // * thus speed up computations and tune similarity scores in different // * algorithms. // * <p> // * For instance, if this {@code NGramComparer} only considers the pitch // * dimension of melodies, no information about time should appear in an // * {@link NGram}'s identifier. // * // * @param g // * the n-gram to compute the identifier for. // * @return the identifier. // */ // public String getNGramId(NGram g); // } // Path: src/jurbano/melodyshape/comparison/alignment/HybridAligner.java import jurbano.melodyshape.comparison.NGramComparer; import java.util.ArrayList; import jurbano.melodyshape.comparison.NGram; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison.alignment; /** * An implementation of a hybrid alignment algorithm for sequences of * {@link NGram}s. * <p> * Like a global alignment algorithm, it penalizes changes at the beginning of * sequences, but the final alignment score is the maximum intermediate score * found in the alignment table. Thus, it does not penalize changes at the end * of sequences. * * @author Julián Urbano * @see NGram * @see NGramComparer */ public class HybridAligner implements MelodyAligner {
protected NGramComparer comparer;
julian-urbano/MelodyShape
src/jurbano/melodyshape/comparison/alignment/HybridAligner.java
// Path: src/jurbano/melodyshape/comparison/NGram.java // @SuppressWarnings("serial") // public class NGram extends ArrayList<Note> // { // /** // * Gets a null n-gram of this object. A null n-gram contains the same notes // * but with all notes set to the pitch of this n-gram's first note. // * // * @return the null n-gram. // */ // public NGram getNullSpan() { // NGram s = new NGram(); // for (Note n : this) // s.add(new Note(this.get(0).getPitch(), n.getOnset(), n.getDuration(), n.getRestFraction())); // return s; // } // // /** // * Gets the sequence of {@code n}-grams, each containing {@code n} // * {@link Note} objects, from the {@link Melody} specified. // * // * @param m // * the melody. // * @param n // * the length of the n-grams. // * @return the sequence of {@code n}-grams. // */ // public static ArrayList<NGram> getNGrams(Melody m, int n) { // ArrayList<NGram> list = new ArrayList<NGram>(); // // for (int i = 0; i <= m.size() - n; i++) { // NGram gram = new NGram(); // for (int j = 0; j < n; j++) // gram.add(m.get(i + j)); // list.add(gram); // } // // return list; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // String res = ""; // for (Note n : this) // res += "{" + n.getPitch() + "," + n.getDuration() + "," + n.getRestFraction() + "}"; // return res; // } // } // // Path: src/jurbano/melodyshape/comparison/NGramComparer.java // public interface NGramComparer // { // /** // * Gets the name of this {@code NGramComparer}. // * // * @return the name of this n-gram comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two n-grams. // * <p> // * The similarity score is proportional to the melodic similarity between // * the notes in each n-gram, that is // * {@code compare(n1, n2) > compare(n1, n3)} means that n-gram {@code n2} is // * more similar to {@code n1} than {@code n3} is. // * // * @param g1 // * the first n-gram to compare. // * @param g2 // * the second n-gram to compare. // * @return the similarity score. // */ // public double compare(NGram g1, NGram g2); // // /** // * Gets an identifier for an {@link NGram} object according to this // * {@link NGramComparer}. This method is intended to identify different // * n-grams that are considered as the same by this {@code NGramComparer} and // * thus speed up computations and tune similarity scores in different // * algorithms. // * <p> // * For instance, if this {@code NGramComparer} only considers the pitch // * dimension of melodies, no information about time should appear in an // * {@link NGram}'s identifier. // * // * @param g // * the n-gram to compute the identifier for. // * @return the identifier. // */ // public String getNGramId(NGram g); // }
import jurbano.melodyshape.comparison.NGramComparer; import java.util.ArrayList; import jurbano.melodyshape.comparison.NGram;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison.alignment; /** * An implementation of a hybrid alignment algorithm for sequences of * {@link NGram}s. * <p> * Like a global alignment algorithm, it penalizes changes at the beginning of * sequences, but the final alignment score is the maximum intermediate score * found in the alignment table. Thus, it does not penalize changes at the end * of sequences. * * @author Julián Urbano * @see NGram * @see NGramComparer */ public class HybridAligner implements MelodyAligner { protected NGramComparer comparer; /** * Constructs a new {@code HybridAligner} with the specified * {@link NGramComparer}. * * @param comparer * the n-gram comparer to use. */ public HybridAligner(NGramComparer comparer) { this.comparer = comparer; } /** * {@inheritDoc} * * @return the {@link String} {@code "Hybrid(comparer)"}, where * {@code comparer} is the name of the underlying * {@link NGramComparer}. */ @Override public String getName() { return "Hybrid("+this.comparer.getName()+")"; } /** * {@inheritDoc} */ @Override
// Path: src/jurbano/melodyshape/comparison/NGram.java // @SuppressWarnings("serial") // public class NGram extends ArrayList<Note> // { // /** // * Gets a null n-gram of this object. A null n-gram contains the same notes // * but with all notes set to the pitch of this n-gram's first note. // * // * @return the null n-gram. // */ // public NGram getNullSpan() { // NGram s = new NGram(); // for (Note n : this) // s.add(new Note(this.get(0).getPitch(), n.getOnset(), n.getDuration(), n.getRestFraction())); // return s; // } // // /** // * Gets the sequence of {@code n}-grams, each containing {@code n} // * {@link Note} objects, from the {@link Melody} specified. // * // * @param m // * the melody. // * @param n // * the length of the n-grams. // * @return the sequence of {@code n}-grams. // */ // public static ArrayList<NGram> getNGrams(Melody m, int n) { // ArrayList<NGram> list = new ArrayList<NGram>(); // // for (int i = 0; i <= m.size() - n; i++) { // NGram gram = new NGram(); // for (int j = 0; j < n; j++) // gram.add(m.get(i + j)); // list.add(gram); // } // // return list; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // String res = ""; // for (Note n : this) // res += "{" + n.getPitch() + "," + n.getDuration() + "," + n.getRestFraction() + "}"; // return res; // } // } // // Path: src/jurbano/melodyshape/comparison/NGramComparer.java // public interface NGramComparer // { // /** // * Gets the name of this {@code NGramComparer}. // * // * @return the name of this n-gram comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two n-grams. // * <p> // * The similarity score is proportional to the melodic similarity between // * the notes in each n-gram, that is // * {@code compare(n1, n2) > compare(n1, n3)} means that n-gram {@code n2} is // * more similar to {@code n1} than {@code n3} is. // * // * @param g1 // * the first n-gram to compare. // * @param g2 // * the second n-gram to compare. // * @return the similarity score. // */ // public double compare(NGram g1, NGram g2); // // /** // * Gets an identifier for an {@link NGram} object according to this // * {@link NGramComparer}. This method is intended to identify different // * n-grams that are considered as the same by this {@code NGramComparer} and // * thus speed up computations and tune similarity scores in different // * algorithms. // * <p> // * For instance, if this {@code NGramComparer} only considers the pitch // * dimension of melodies, no information about time should appear in an // * {@link NGram}'s identifier. // * // * @param g // * the n-gram to compute the identifier for. // * @return the identifier. // */ // public String getNGramId(NGram g); // } // Path: src/jurbano/melodyshape/comparison/alignment/HybridAligner.java import jurbano.melodyshape.comparison.NGramComparer; import java.util.ArrayList; import jurbano.melodyshape.comparison.NGram; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison.alignment; /** * An implementation of a hybrid alignment algorithm for sequences of * {@link NGram}s. * <p> * Like a global alignment algorithm, it penalizes changes at the beginning of * sequences, but the final alignment score is the maximum intermediate score * found in the alignment table. Thus, it does not penalize changes at the end * of sequences. * * @author Julián Urbano * @see NGram * @see NGramComparer */ public class HybridAligner implements MelodyAligner { protected NGramComparer comparer; /** * Constructs a new {@code HybridAligner} with the specified * {@link NGramComparer}. * * @param comparer * the n-gram comparer to use. */ public HybridAligner(NGramComparer comparer) { this.comparer = comparer; } /** * {@inheritDoc} * * @return the {@link String} {@code "Hybrid(comparer)"}, where * {@code comparer} is the name of the underlying * {@link NGramComparer}. */ @Override public String getName() { return "Hybrid("+this.comparer.getName()+")"; } /** * {@inheritDoc} */ @Override
public double align(ArrayList<NGram> s1, ArrayList<NGram> s2) {
julian-urbano/MelodyShape
src/jurbano/melodyshape/comparison/bspline/BSplinePitchNGramComparer.java
// Path: src/jurbano/melodyshape/comparison/NGram.java // @SuppressWarnings("serial") // public class NGram extends ArrayList<Note> // { // /** // * Gets a null n-gram of this object. A null n-gram contains the same notes // * but with all notes set to the pitch of this n-gram's first note. // * // * @return the null n-gram. // */ // public NGram getNullSpan() { // NGram s = new NGram(); // for (Note n : this) // s.add(new Note(this.get(0).getPitch(), n.getOnset(), n.getDuration(), n.getRestFraction())); // return s; // } // // /** // * Gets the sequence of {@code n}-grams, each containing {@code n} // * {@link Note} objects, from the {@link Melody} specified. // * // * @param m // * the melody. // * @param n // * the length of the n-grams. // * @return the sequence of {@code n}-grams. // */ // public static ArrayList<NGram> getNGrams(Melody m, int n) { // ArrayList<NGram> list = new ArrayList<NGram>(); // // for (int i = 0; i <= m.size() - n; i++) { // NGram gram = new NGram(); // for (int j = 0; j < n; j++) // gram.add(m.get(i + j)); // list.add(gram); // } // // return list; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // String res = ""; // for (Note n : this) // res += "{" + n.getPitch() + "," + n.getDuration() + "," + n.getRestFraction() + "}"; // return res; // } // } // // Path: src/jurbano/melodyshape/comparison/NGramComparer.java // public interface NGramComparer // { // /** // * Gets the name of this {@code NGramComparer}. // * // * @return the name of this n-gram comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two n-grams. // * <p> // * The similarity score is proportional to the melodic similarity between // * the notes in each n-gram, that is // * {@code compare(n1, n2) > compare(n1, n3)} means that n-gram {@code n2} is // * more similar to {@code n1} than {@code n3} is. // * // * @param g1 // * the first n-gram to compare. // * @param g2 // * the second n-gram to compare. // * @return the similarity score. // */ // public double compare(NGram g1, NGram g2); // // /** // * Gets an identifier for an {@link NGram} object according to this // * {@link NGramComparer}. This method is intended to identify different // * n-grams that are considered as the same by this {@code NGramComparer} and // * thus speed up computations and tune similarity scores in different // * algorithms. // * <p> // * For instance, if this {@code NGramComparer} only considers the pitch // * dimension of melodies, no information about time should appear in an // * {@link NGram}'s identifier. // * // * @param g // * the n-gram to compute the identifier for. // * @return the identifier. // */ // public String getNGramId(NGram g); // }
import jurbano.melodyshape.comparison.NGramComparer; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import java.util.ArrayList; import jurbano.melodyshape.comparison.NGram;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison.bspline; /** * A similarity function between two {@link NGram} objects that interpolates * pitch sequences using a Uniform B-Spline and then computes the area between * the first derivatives of the two splines. * * @author Julián Urbano * @see BSplineTimeNGramComparer * @see UniformBSpline * @see NGramComparer */ public class BSplinePitchNGramComparer implements NGramComparer { /** * {@inheritDoc} * * @return the {@link String} {@code "BSplinePitch"}. */ @Override public String getName() { return "BSplinePitch"; } /** * {@inheritDoc} * * @return 0 if both {@link NGram}s are equivalent or the area between the * first derivatives of their corresponding Uniform B-Splines. */ @Override
// Path: src/jurbano/melodyshape/comparison/NGram.java // @SuppressWarnings("serial") // public class NGram extends ArrayList<Note> // { // /** // * Gets a null n-gram of this object. A null n-gram contains the same notes // * but with all notes set to the pitch of this n-gram's first note. // * // * @return the null n-gram. // */ // public NGram getNullSpan() { // NGram s = new NGram(); // for (Note n : this) // s.add(new Note(this.get(0).getPitch(), n.getOnset(), n.getDuration(), n.getRestFraction())); // return s; // } // // /** // * Gets the sequence of {@code n}-grams, each containing {@code n} // * {@link Note} objects, from the {@link Melody} specified. // * // * @param m // * the melody. // * @param n // * the length of the n-grams. // * @return the sequence of {@code n}-grams. // */ // public static ArrayList<NGram> getNGrams(Melody m, int n) { // ArrayList<NGram> list = new ArrayList<NGram>(); // // for (int i = 0; i <= m.size() - n; i++) { // NGram gram = new NGram(); // for (int j = 0; j < n; j++) // gram.add(m.get(i + j)); // list.add(gram); // } // // return list; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // String res = ""; // for (Note n : this) // res += "{" + n.getPitch() + "," + n.getDuration() + "," + n.getRestFraction() + "}"; // return res; // } // } // // Path: src/jurbano/melodyshape/comparison/NGramComparer.java // public interface NGramComparer // { // /** // * Gets the name of this {@code NGramComparer}. // * // * @return the name of this n-gram comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two n-grams. // * <p> // * The similarity score is proportional to the melodic similarity between // * the notes in each n-gram, that is // * {@code compare(n1, n2) > compare(n1, n3)} means that n-gram {@code n2} is // * more similar to {@code n1} than {@code n3} is. // * // * @param g1 // * the first n-gram to compare. // * @param g2 // * the second n-gram to compare. // * @return the similarity score. // */ // public double compare(NGram g1, NGram g2); // // /** // * Gets an identifier for an {@link NGram} object according to this // * {@link NGramComparer}. This method is intended to identify different // * n-grams that are considered as the same by this {@code NGramComparer} and // * thus speed up computations and tune similarity scores in different // * algorithms. // * <p> // * For instance, if this {@code NGramComparer} only considers the pitch // * dimension of melodies, no information about time should appear in an // * {@link NGram}'s identifier. // * // * @param g // * the n-gram to compute the identifier for. // * @return the identifier. // */ // public String getNGramId(NGram g); // } // Path: src/jurbano/melodyshape/comparison/bspline/BSplinePitchNGramComparer.java import jurbano.melodyshape.comparison.NGramComparer; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import java.util.ArrayList; import jurbano.melodyshape.comparison.NGram; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison.bspline; /** * A similarity function between two {@link NGram} objects that interpolates * pitch sequences using a Uniform B-Spline and then computes the area between * the first derivatives of the two splines. * * @author Julián Urbano * @see BSplineTimeNGramComparer * @see UniformBSpline * @see NGramComparer */ public class BSplinePitchNGramComparer implements NGramComparer { /** * {@inheritDoc} * * @return the {@link String} {@code "BSplinePitch"}. */ @Override public String getName() { return "BSplinePitch"; } /** * {@inheritDoc} * * @return 0 if both {@link NGram}s are equivalent or the area between the * first derivatives of their corresponding Uniform B-Splines. */ @Override
public double compare(NGram g1, NGram g2) {
julian-urbano/MelodyShape
src/jurbano/melodyshape/comparison/FrequencyNGramComparer.java
// Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // } // // Path: src/jurbano/melodyshape/model/MelodyCollection.java // public interface MelodyCollection extends Iterable<Melody> // { // /** // * Gets the name of the collection. // * // * @return the name of the collection. // */ // public String getName(); // // /** // * Gets the {@link Melody} with the specified ID or {@code null} if there is // * no {@link Melody} with that ID. // * // * @param id // * the ID of the melody to get. // * @return the melody with the specified ID. // */ // public Melody get(String id); // // /** // * Gets the number of {@link Melody} objects in the collection. // * // * @return the number of melodies. // */ // public int size(); // }
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import jurbano.melodyshape.model.Melody; import jurbano.melodyshape.model.MelodyCollection;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison; /** * A similarity function between two {@link NGram} objects that uses a second * {@link NGramComparer} for mismatches and the frequency of n-grams in the * collection for insertions, deletions and matches. * * @author Julián Urbano * @see NGram * @see NGramComparer */ public class FrequencyNGramComparer implements NGramComparer { protected HashMap<String, Long> nGramCounts; protected long nGramCountSum; protected NGramComparer mismatchComparer; /** * {@inheritDoc} * * @return the {@link String} {@code "Freq(comparer)"}, where * {@code comparer} is the name of the underlying * {@link NGramComparer}. */ @Override public String getName() { return "Freq(" + this.mismatchComparer.getName() + ")"; } /** * {@inheritDoc} */ @Override public String getNGramId(NGram g) { return this.mismatchComparer.getNGramId(g); } /** * Constructs a new {@code FrequencyNGramComparer} for the specified * {@link MelodyCollection} and using the specified * {@link NGramMelodyComparer}. The frequency of all n-grams in the * collection are computed here. * * @param coll * the collection of melodies. * @param nGramLength * the length of the n-grams to compute. * @param mismatchComparer * the n-gram comparer for mismatches. */
// Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // } // // Path: src/jurbano/melodyshape/model/MelodyCollection.java // public interface MelodyCollection extends Iterable<Melody> // { // /** // * Gets the name of the collection. // * // * @return the name of the collection. // */ // public String getName(); // // /** // * Gets the {@link Melody} with the specified ID or {@code null} if there is // * no {@link Melody} with that ID. // * // * @param id // * the ID of the melody to get. // * @return the melody with the specified ID. // */ // public Melody get(String id); // // /** // * Gets the number of {@link Melody} objects in the collection. // * // * @return the number of melodies. // */ // public int size(); // } // Path: src/jurbano/melodyshape/comparison/FrequencyNGramComparer.java import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import jurbano.melodyshape.model.Melody; import jurbano.melodyshape.model.MelodyCollection; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison; /** * A similarity function between two {@link NGram} objects that uses a second * {@link NGramComparer} for mismatches and the frequency of n-grams in the * collection for insertions, deletions and matches. * * @author Julián Urbano * @see NGram * @see NGramComparer */ public class FrequencyNGramComparer implements NGramComparer { protected HashMap<String, Long> nGramCounts; protected long nGramCountSum; protected NGramComparer mismatchComparer; /** * {@inheritDoc} * * @return the {@link String} {@code "Freq(comparer)"}, where * {@code comparer} is the name of the underlying * {@link NGramComparer}. */ @Override public String getName() { return "Freq(" + this.mismatchComparer.getName() + ")"; } /** * {@inheritDoc} */ @Override public String getNGramId(NGram g) { return this.mismatchComparer.getNGramId(g); } /** * Constructs a new {@code FrequencyNGramComparer} for the specified * {@link MelodyCollection} and using the specified * {@link NGramMelodyComparer}. The frequency of all n-grams in the * collection are computed here. * * @param coll * the collection of melodies. * @param nGramLength * the length of the n-grams to compute. * @param mismatchComparer * the n-gram comparer for mismatches. */
public FrequencyNGramComparer(MelodyCollection coll, int nGramLength, NGramComparer mismatchComparer) {
julian-urbano/MelodyShape
src/jurbano/melodyshape/comparison/FrequencyNGramComparer.java
// Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // } // // Path: src/jurbano/melodyshape/model/MelodyCollection.java // public interface MelodyCollection extends Iterable<Melody> // { // /** // * Gets the name of the collection. // * // * @return the name of the collection. // */ // public String getName(); // // /** // * Gets the {@link Melody} with the specified ID or {@code null} if there is // * no {@link Melody} with that ID. // * // * @param id // * the ID of the melody to get. // * @return the melody with the specified ID. // */ // public Melody get(String id); // // /** // * Gets the number of {@link Melody} objects in the collection. // * // * @return the number of melodies. // */ // public int size(); // }
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import jurbano.melodyshape.model.Melody; import jurbano.melodyshape.model.MelodyCollection;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison; /** * A similarity function between two {@link NGram} objects that uses a second * {@link NGramComparer} for mismatches and the frequency of n-grams in the * collection for insertions, deletions and matches. * * @author Julián Urbano * @see NGram * @see NGramComparer */ public class FrequencyNGramComparer implements NGramComparer { protected HashMap<String, Long> nGramCounts; protected long nGramCountSum; protected NGramComparer mismatchComparer; /** * {@inheritDoc} * * @return the {@link String} {@code "Freq(comparer)"}, where * {@code comparer} is the name of the underlying * {@link NGramComparer}. */ @Override public String getName() { return "Freq(" + this.mismatchComparer.getName() + ")"; } /** * {@inheritDoc} */ @Override public String getNGramId(NGram g) { return this.mismatchComparer.getNGramId(g); } /** * Constructs a new {@code FrequencyNGramComparer} for the specified * {@link MelodyCollection} and using the specified * {@link NGramMelodyComparer}. The frequency of all n-grams in the * collection are computed here. * * @param coll * the collection of melodies. * @param nGramLength * the length of the n-grams to compute. * @param mismatchComparer * the n-gram comparer for mismatches. */ public FrequencyNGramComparer(MelodyCollection coll, int nGramLength, NGramComparer mismatchComparer) { this.mismatchComparer = mismatchComparer; this.nGramCounts = new HashMap<String, Long>(); this.nGramCountSum = 0;
// Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // } // // Path: src/jurbano/melodyshape/model/MelodyCollection.java // public interface MelodyCollection extends Iterable<Melody> // { // /** // * Gets the name of the collection. // * // * @return the name of the collection. // */ // public String getName(); // // /** // * Gets the {@link Melody} with the specified ID or {@code null} if there is // * no {@link Melody} with that ID. // * // * @param id // * the ID of the melody to get. // * @return the melody with the specified ID. // */ // public Melody get(String id); // // /** // * Gets the number of {@link Melody} objects in the collection. // * // * @return the number of melodies. // */ // public int size(); // } // Path: src/jurbano/melodyshape/comparison/FrequencyNGramComparer.java import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import jurbano.melodyshape.model.Melody; import jurbano.melodyshape.model.MelodyCollection; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison; /** * A similarity function between two {@link NGram} objects that uses a second * {@link NGramComparer} for mismatches and the frequency of n-grams in the * collection for insertions, deletions and matches. * * @author Julián Urbano * @see NGram * @see NGramComparer */ public class FrequencyNGramComparer implements NGramComparer { protected HashMap<String, Long> nGramCounts; protected long nGramCountSum; protected NGramComparer mismatchComparer; /** * {@inheritDoc} * * @return the {@link String} {@code "Freq(comparer)"}, where * {@code comparer} is the name of the underlying * {@link NGramComparer}. */ @Override public String getName() { return "Freq(" + this.mismatchComparer.getName() + ")"; } /** * {@inheritDoc} */ @Override public String getNGramId(NGram g) { return this.mismatchComparer.getNGramId(g); } /** * Constructs a new {@code FrequencyNGramComparer} for the specified * {@link MelodyCollection} and using the specified * {@link NGramMelodyComparer}. The frequency of all n-grams in the * collection are computed here. * * @param coll * the collection of melodies. * @param nGramLength * the length of the n-grams to compute. * @param mismatchComparer * the n-gram comparer for mismatches. */ public FrequencyNGramComparer(MelodyCollection coll, int nGramLength, NGramComparer mismatchComparer) { this.mismatchComparer = mismatchComparer; this.nGramCounts = new HashMap<String, Long>(); this.nGramCountSum = 0;
for (Melody m : coll) {
julian-urbano/MelodyShape
src/jurbano/melodyshape/ranking/UntieResultRanker.java
// Path: src/jurbano/melodyshape/comparison/MelodyComparer.java // public interface MelodyComparer // { // /** // * Gets the name of this {@code MelodyComparer} // * // * @return the name of the melody comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two melodies. // * <p> // * The similarity score is proportional to the melodic similarity between // * the melodies, that is {@code compare(m1, m2) > compare(m1, m3)} means // * that melody {@code m2} is more similar to {@code m1} than {@code m3} is. // * // * @param m1 // * the first melody to compare. // * @param m2 // * the second melody to compare. // * @return the similarity score. // */ // public double compare(Melody m1, Melody m2); // } // // Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // }
import java.util.Arrays; import java.util.Comparator; import jurbano.melodyshape.comparison.MelodyComparer; import jurbano.melodyshape.model.Melody;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.ranking; /** * A ranking function that sorts by decreasing similarity score, then by * decreasing similarity according to a second {@link MelodyComparer}, then by * increasing difference in length with the query, and then by melody * identifier. * * @author Julián Urbano * @see ResultRanker */ public class UntieResultRanker implements ResultRanker {
// Path: src/jurbano/melodyshape/comparison/MelodyComparer.java // public interface MelodyComparer // { // /** // * Gets the name of this {@code MelodyComparer} // * // * @return the name of the melody comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two melodies. // * <p> // * The similarity score is proportional to the melodic similarity between // * the melodies, that is {@code compare(m1, m2) > compare(m1, m3)} means // * that melody {@code m2} is more similar to {@code m1} than {@code m3} is. // * // * @param m1 // * the first melody to compare. // * @param m2 // * the second melody to compare. // * @return the similarity score. // */ // public double compare(Melody m1, Melody m2); // } // // Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // } // Path: src/jurbano/melodyshape/ranking/UntieResultRanker.java import java.util.Arrays; import java.util.Comparator; import jurbano.melodyshape.comparison.MelodyComparer; import jurbano.melodyshape.model.Melody; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.ranking; /** * A ranking function that sorts by decreasing similarity score, then by * decreasing similarity according to a second {@link MelodyComparer}, then by * increasing difference in length with the query, and then by melody * identifier. * * @author Julián Urbano * @see ResultRanker */ public class UntieResultRanker implements ResultRanker {
protected MelodyComparer comparer;
julian-urbano/MelodyShape
src/jurbano/melodyshape/ranking/UntieResultRanker.java
// Path: src/jurbano/melodyshape/comparison/MelodyComparer.java // public interface MelodyComparer // { // /** // * Gets the name of this {@code MelodyComparer} // * // * @return the name of the melody comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two melodies. // * <p> // * The similarity score is proportional to the melodic similarity between // * the melodies, that is {@code compare(m1, m2) > compare(m1, m3)} means // * that melody {@code m2} is more similar to {@code m1} than {@code m3} is. // * // * @param m1 // * the first melody to compare. // * @param m2 // * the second melody to compare. // * @return the similarity score. // */ // public double compare(Melody m1, Melody m2); // } // // Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // }
import java.util.Arrays; import java.util.Comparator; import jurbano.melodyshape.comparison.MelodyComparer; import jurbano.melodyshape.model.Melody;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.ranking; /** * A ranking function that sorts by decreasing similarity score, then by * decreasing similarity according to a second {@link MelodyComparer}, then by * increasing difference in length with the query, and then by melody * identifier. * * @author Julián Urbano * @see ResultRanker */ public class UntieResultRanker implements ResultRanker { protected MelodyComparer comparer; /** * Constructs a new {@code UntieResultRanker} with the specified * {@link MelodyComparer}. * * @param comparer * the n-gram comparer to use. */ public UntieResultRanker(MelodyComparer comparer) { this.comparer = comparer; } /** * {@inheritDoc} */ @Override
// Path: src/jurbano/melodyshape/comparison/MelodyComparer.java // public interface MelodyComparer // { // /** // * Gets the name of this {@code MelodyComparer} // * // * @return the name of the melody comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two melodies. // * <p> // * The similarity score is proportional to the melodic similarity between // * the melodies, that is {@code compare(m1, m2) > compare(m1, m3)} means // * that melody {@code m2} is more similar to {@code m1} than {@code m3} is. // * // * @param m1 // * the first melody to compare. // * @param m2 // * the second melody to compare. // * @return the similarity score. // */ // public double compare(Melody m1, Melody m2); // } // // Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // } // Path: src/jurbano/melodyshape/ranking/UntieResultRanker.java import java.util.Arrays; import java.util.Comparator; import jurbano.melodyshape.comparison.MelodyComparer; import jurbano.melodyshape.model.Melody; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.ranking; /** * A ranking function that sorts by decreasing similarity score, then by * decreasing similarity according to a second {@link MelodyComparer}, then by * increasing difference in length with the query, and then by melody * identifier. * * @author Julián Urbano * @see ResultRanker */ public class UntieResultRanker implements ResultRanker { protected MelodyComparer comparer; /** * Constructs a new {@code UntieResultRanker} with the specified * {@link MelodyComparer}. * * @param comparer * the n-gram comparer to use. */ public UntieResultRanker(MelodyComparer comparer) { this.comparer = comparer; } /** * {@inheritDoc} */ @Override
public void rank(final Melody query, Result[] results, int k) {
julian-urbano/MelodyShape
src/jurbano/melodyshape/comparison/bspline/BSplineTimeNGramComparer.java
// Path: src/jurbano/melodyshape/comparison/NGram.java // @SuppressWarnings("serial") // public class NGram extends ArrayList<Note> // { // /** // * Gets a null n-gram of this object. A null n-gram contains the same notes // * but with all notes set to the pitch of this n-gram's first note. // * // * @return the null n-gram. // */ // public NGram getNullSpan() { // NGram s = new NGram(); // for (Note n : this) // s.add(new Note(this.get(0).getPitch(), n.getOnset(), n.getDuration(), n.getRestFraction())); // return s; // } // // /** // * Gets the sequence of {@code n}-grams, each containing {@code n} // * {@link Note} objects, from the {@link Melody} specified. // * // * @param m // * the melody. // * @param n // * the length of the n-grams. // * @return the sequence of {@code n}-grams. // */ // public static ArrayList<NGram> getNGrams(Melody m, int n) { // ArrayList<NGram> list = new ArrayList<NGram>(); // // for (int i = 0; i <= m.size() - n; i++) { // NGram gram = new NGram(); // for (int j = 0; j < n; j++) // gram.add(m.get(i + j)); // list.add(gram); // } // // return list; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // String res = ""; // for (Note n : this) // res += "{" + n.getPitch() + "," + n.getDuration() + "," + n.getRestFraction() + "}"; // return res; // } // } // // Path: src/jurbano/melodyshape/comparison/NGramComparer.java // public interface NGramComparer // { // /** // * Gets the name of this {@code NGramComparer}. // * // * @return the name of this n-gram comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two n-grams. // * <p> // * The similarity score is proportional to the melodic similarity between // * the notes in each n-gram, that is // * {@code compare(n1, n2) > compare(n1, n3)} means that n-gram {@code n2} is // * more similar to {@code n1} than {@code n3} is. // * // * @param g1 // * the first n-gram to compare. // * @param g2 // * the second n-gram to compare. // * @return the similarity score. // */ // public double compare(NGram g1, NGram g2); // // /** // * Gets an identifier for an {@link NGram} object according to this // * {@link NGramComparer}. This method is intended to identify different // * n-grams that are considered as the same by this {@code NGramComparer} and // * thus speed up computations and tune similarity scores in different // * algorithms. // * <p> // * For instance, if this {@code NGramComparer} only considers the pitch // * dimension of melodies, no information about time should appear in an // * {@link NGram}'s identifier. // * // * @param g // * the n-gram to compute the identifier for. // * @return the identifier. // */ // public String getNGramId(NGram g); // }
import java.text.DecimalFormat; import java.util.ArrayList; import jurbano.melodyshape.comparison.NGram; import jurbano.melodyshape.comparison.NGramComparer; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison.bspline; /** * A similarity function between two {@link NGram} objects that interpolates * time interval sequences using a Uniform B-Spline and then computes the area * between the first derivatives of the two splines. * * @author Julián Urbano * @see BSplineTimeNGramComparer * @see UniformBSpline * @see NGramComparer */ public class BSplineTimeNGramComparer implements NGramComparer { protected final DecimalFormat format = new DecimalFormat("#.###"); /** * {@inheritDoc} * * @return the {@link String} {@code "BSplineTime"}. */ @Override public String getName() { return "BSplineTime"; } /** * {@inheritDoc} * * @return 0 if both {@link NGram}s are equivalent or the area between the * first derivatives of their corresponding Uniform B-Splines. */ @Override
// Path: src/jurbano/melodyshape/comparison/NGram.java // @SuppressWarnings("serial") // public class NGram extends ArrayList<Note> // { // /** // * Gets a null n-gram of this object. A null n-gram contains the same notes // * but with all notes set to the pitch of this n-gram's first note. // * // * @return the null n-gram. // */ // public NGram getNullSpan() { // NGram s = new NGram(); // for (Note n : this) // s.add(new Note(this.get(0).getPitch(), n.getOnset(), n.getDuration(), n.getRestFraction())); // return s; // } // // /** // * Gets the sequence of {@code n}-grams, each containing {@code n} // * {@link Note} objects, from the {@link Melody} specified. // * // * @param m // * the melody. // * @param n // * the length of the n-grams. // * @return the sequence of {@code n}-grams. // */ // public static ArrayList<NGram> getNGrams(Melody m, int n) { // ArrayList<NGram> list = new ArrayList<NGram>(); // // for (int i = 0; i <= m.size() - n; i++) { // NGram gram = new NGram(); // for (int j = 0; j < n; j++) // gram.add(m.get(i + j)); // list.add(gram); // } // // return list; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // String res = ""; // for (Note n : this) // res += "{" + n.getPitch() + "," + n.getDuration() + "," + n.getRestFraction() + "}"; // return res; // } // } // // Path: src/jurbano/melodyshape/comparison/NGramComparer.java // public interface NGramComparer // { // /** // * Gets the name of this {@code NGramComparer}. // * // * @return the name of this n-gram comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two n-grams. // * <p> // * The similarity score is proportional to the melodic similarity between // * the notes in each n-gram, that is // * {@code compare(n1, n2) > compare(n1, n3)} means that n-gram {@code n2} is // * more similar to {@code n1} than {@code n3} is. // * // * @param g1 // * the first n-gram to compare. // * @param g2 // * the second n-gram to compare. // * @return the similarity score. // */ // public double compare(NGram g1, NGram g2); // // /** // * Gets an identifier for an {@link NGram} object according to this // * {@link NGramComparer}. This method is intended to identify different // * n-grams that are considered as the same by this {@code NGramComparer} and // * thus speed up computations and tune similarity scores in different // * algorithms. // * <p> // * For instance, if this {@code NGramComparer} only considers the pitch // * dimension of melodies, no information about time should appear in an // * {@link NGram}'s identifier. // * // * @param g // * the n-gram to compute the identifier for. // * @return the identifier. // */ // public String getNGramId(NGram g); // } // Path: src/jurbano/melodyshape/comparison/bspline/BSplineTimeNGramComparer.java import java.text.DecimalFormat; import java.util.ArrayList; import jurbano.melodyshape.comparison.NGram; import jurbano.melodyshape.comparison.NGramComparer; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison.bspline; /** * A similarity function between two {@link NGram} objects that interpolates * time interval sequences using a Uniform B-Spline and then computes the area * between the first derivatives of the two splines. * * @author Julián Urbano * @see BSplineTimeNGramComparer * @see UniformBSpline * @see NGramComparer */ public class BSplineTimeNGramComparer implements NGramComparer { protected final DecimalFormat format = new DecimalFormat("#.###"); /** * {@inheritDoc} * * @return the {@link String} {@code "BSplineTime"}. */ @Override public String getName() { return "BSplineTime"; } /** * {@inheritDoc} * * @return 0 if both {@link NGram}s are equivalent or the area between the * first derivatives of their corresponding Uniform B-Splines. */ @Override
public double compare(NGram g1, NGram g2) {
julian-urbano/MelodyShape
src/jurbano/melodyshape/comparison/MelodyComparer.java
// Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // }
import jurbano.melodyshape.model.Melody;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison; /** * Represents a function that computes a similarity score between two * {@link Melody} objects. * * @author Julián Urbano * @see Melody */ public interface MelodyComparer { /** * Gets the name of this {@code MelodyComparer} * * @return the name of the melody comparer. */ public String getName(); /** * Computes a similarity score between two melodies. * <p> * The similarity score is proportional to the melodic similarity between * the melodies, that is {@code compare(m1, m2) > compare(m1, m3)} means * that melody {@code m2} is more similar to {@code m1} than {@code m3} is. * * @param m1 * the first melody to compare. * @param m2 * the second melody to compare. * @return the similarity score. */
// Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // } // Path: src/jurbano/melodyshape/comparison/MelodyComparer.java import jurbano.melodyshape.model.Melody; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison; /** * Represents a function that computes a similarity score between two * {@link Melody} objects. * * @author Julián Urbano * @see Melody */ public interface MelodyComparer { /** * Gets the name of this {@code MelodyComparer} * * @return the name of the melody comparer. */ public String getName(); /** * Computes a similarity score between two melodies. * <p> * The similarity score is proportional to the melodic similarity between * the melodies, that is {@code compare(m1, m2) > compare(m1, m3)} means * that melody {@code m2} is more similar to {@code m1} than {@code m3} is. * * @param m1 * the first melody to compare. * @param m2 * the second melody to compare. * @return the similarity score. */
public double compare(Melody m1, Melody m2);
julian-urbano/MelodyShape
src/jurbano/melodyshape/comparison/EqualPitchNGramComparer.java
// Path: src/jurbano/melodyshape/model/Note.java // public class Note // { // protected long duration; // protected long onset; // protected byte pitch; // protected double restFraction; // // /** // * Constructs a new {@code Note}. // * // * @param pitch // * the pitch of the note. // * @param onset // * the onset time of the note. // * @param duration // * the duration of the note. // * @param restFraction // * the fraction of the note's duration that corresponds do rests. // */ // public Note(byte pitch, long onset, long duration, double restFraction) { // this.pitch = pitch; // this.onset = onset; // this.duration = duration; // this.restFraction = restFraction; // } // // /** // * Gets the duration of the note. // * // * @return the duration of the note. // */ // public long getDuration() { // return this.duration; // } // // /** // * Gets the onset time of the note. // * // * @return the onset time of the note. // */ // public long getOnset() { // return this.onset; // } // // /** // * Gets the pitch of the note. // * // * @return the pitch of the note. // */ // public byte getPitch() { // return this.pitch; // } // // /** // * Gets the fraction of the note's duration that corresponds to rests. // * // * @return the rest fraction. // */ // public double getRestFraction() { // return this.restFraction; // } // // @Override // public String toString() { // return "Note [@" + this.onset + ": pitch=" + this.pitch + ", duration=" + this.duration + ", rest=" + this.restFraction + "]"; // } // // }
import jurbano.melodyshape.model.Note;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison; /** * A similarity function between two {@link NGram} objects that only considers * absolute pitch values. The similarity is binary: either the two n-grams have * the exact same pitch sequence or not. * * @author Julián Urbano * @see NGram * @see NGramComparer */ public class EqualPitchNGramComparer implements NGramComparer { /** * {@inheritDoc} * * @return the {@link String} {@code "Eq"}. */ @Override public String getName() { return "Eq"; } /** * {@inheritDoc} * * @return -1 if either n-gram is {@code null}, -1 if the i-th {@link Note} * in {@code n1} has a different pitch in {@code n2}, or 1 if both * pitch sequences are the same. */ public double compare(NGram n1, NGram n2) { if (n1 == null || n2 == null) return -1; for (int i = 0; i < n1.size(); i++) if (n1.get(i).getPitch() != n2.get(i).getPitch()) return -1; return 1; } /** * {@inheritDoc} * * @return a {@link String} with the format <code>{p1, p2, ..., pn}</code>, * where {@code pi} corresponds to the pitch of the i-th note inside * the n-gram. The {@link String} {@code "null"} is returned if the * n-gram is {@code null}. */ @Override public String getNGramId(NGram g) { if (g == null) return "null"; String res = "{";
// Path: src/jurbano/melodyshape/model/Note.java // public class Note // { // protected long duration; // protected long onset; // protected byte pitch; // protected double restFraction; // // /** // * Constructs a new {@code Note}. // * // * @param pitch // * the pitch of the note. // * @param onset // * the onset time of the note. // * @param duration // * the duration of the note. // * @param restFraction // * the fraction of the note's duration that corresponds do rests. // */ // public Note(byte pitch, long onset, long duration, double restFraction) { // this.pitch = pitch; // this.onset = onset; // this.duration = duration; // this.restFraction = restFraction; // } // // /** // * Gets the duration of the note. // * // * @return the duration of the note. // */ // public long getDuration() { // return this.duration; // } // // /** // * Gets the onset time of the note. // * // * @return the onset time of the note. // */ // public long getOnset() { // return this.onset; // } // // /** // * Gets the pitch of the note. // * // * @return the pitch of the note. // */ // public byte getPitch() { // return this.pitch; // } // // /** // * Gets the fraction of the note's duration that corresponds to rests. // * // * @return the rest fraction. // */ // public double getRestFraction() { // return this.restFraction; // } // // @Override // public String toString() { // return "Note [@" + this.onset + ": pitch=" + this.pitch + ", duration=" + this.duration + ", rest=" + this.restFraction + "]"; // } // // } // Path: src/jurbano/melodyshape/comparison/EqualPitchNGramComparer.java import jurbano.melodyshape.model.Note; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison; /** * A similarity function between two {@link NGram} objects that only considers * absolute pitch values. The similarity is binary: either the two n-grams have * the exact same pitch sequence or not. * * @author Julián Urbano * @see NGram * @see NGramComparer */ public class EqualPitchNGramComparer implements NGramComparer { /** * {@inheritDoc} * * @return the {@link String} {@code "Eq"}. */ @Override public String getName() { return "Eq"; } /** * {@inheritDoc} * * @return -1 if either n-gram is {@code null}, -1 if the i-th {@link Note} * in {@code n1} has a different pitch in {@code n2}, or 1 if both * pitch sequences are the same. */ public double compare(NGram n1, NGram n2) { if (n1 == null || n2 == null) return -1; for (int i = 0; i < n1.size(); i++) if (n1.get(i).getPitch() != n2.get(i).getPitch()) return -1; return 1; } /** * {@inheritDoc} * * @return a {@link String} with the format <code>{p1, p2, ..., pn}</code>, * where {@code pi} corresponds to the pitch of the i-th note inside * the n-gram. The {@link String} {@code "null"} is returned if the * n-gram is {@code null}. */ @Override public String getNGramId(NGram g) { if (g == null) return "null"; String res = "{";
for (Note n : g)
julian-urbano/MelodyShape
src/jurbano/melodyshape/comparison/alignment/LocalAligner.java
// Path: src/jurbano/melodyshape/comparison/NGram.java // @SuppressWarnings("serial") // public class NGram extends ArrayList<Note> // { // /** // * Gets a null n-gram of this object. A null n-gram contains the same notes // * but with all notes set to the pitch of this n-gram's first note. // * // * @return the null n-gram. // */ // public NGram getNullSpan() { // NGram s = new NGram(); // for (Note n : this) // s.add(new Note(this.get(0).getPitch(), n.getOnset(), n.getDuration(), n.getRestFraction())); // return s; // } // // /** // * Gets the sequence of {@code n}-grams, each containing {@code n} // * {@link Note} objects, from the {@link Melody} specified. // * // * @param m // * the melody. // * @param n // * the length of the n-grams. // * @return the sequence of {@code n}-grams. // */ // public static ArrayList<NGram> getNGrams(Melody m, int n) { // ArrayList<NGram> list = new ArrayList<NGram>(); // // for (int i = 0; i <= m.size() - n; i++) { // NGram gram = new NGram(); // for (int j = 0; j < n; j++) // gram.add(m.get(i + j)); // list.add(gram); // } // // return list; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // String res = ""; // for (Note n : this) // res += "{" + n.getPitch() + "," + n.getDuration() + "," + n.getRestFraction() + "}"; // return res; // } // } // // Path: src/jurbano/melodyshape/comparison/NGramComparer.java // public interface NGramComparer // { // /** // * Gets the name of this {@code NGramComparer}. // * // * @return the name of this n-gram comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two n-grams. // * <p> // * The similarity score is proportional to the melodic similarity between // * the notes in each n-gram, that is // * {@code compare(n1, n2) > compare(n1, n3)} means that n-gram {@code n2} is // * more similar to {@code n1} than {@code n3} is. // * // * @param g1 // * the first n-gram to compare. // * @param g2 // * the second n-gram to compare. // * @return the similarity score. // */ // public double compare(NGram g1, NGram g2); // // /** // * Gets an identifier for an {@link NGram} object according to this // * {@link NGramComparer}. This method is intended to identify different // * n-grams that are considered as the same by this {@code NGramComparer} and // * thus speed up computations and tune similarity scores in different // * algorithms. // * <p> // * For instance, if this {@code NGramComparer} only considers the pitch // * dimension of melodies, no information about time should appear in an // * {@link NGram}'s identifier. // * // * @param g // * the n-gram to compute the identifier for. // * @return the identifier. // */ // public String getNGramId(NGram g); // }
import jurbano.melodyshape.comparison.NGramComparer; import java.util.ArrayList; import jurbano.melodyshape.comparison.NGram;
// Copyright (C) 2013, 2015-2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison.alignment; /** * An implementation of the Smith-Waterman alignment algorithm for sequences of {@link NGram}s. * * @author Julián Urbano * @see NGram * @see NGramComparer */ public class LocalAligner implements MelodyAligner {
// Path: src/jurbano/melodyshape/comparison/NGram.java // @SuppressWarnings("serial") // public class NGram extends ArrayList<Note> // { // /** // * Gets a null n-gram of this object. A null n-gram contains the same notes // * but with all notes set to the pitch of this n-gram's first note. // * // * @return the null n-gram. // */ // public NGram getNullSpan() { // NGram s = new NGram(); // for (Note n : this) // s.add(new Note(this.get(0).getPitch(), n.getOnset(), n.getDuration(), n.getRestFraction())); // return s; // } // // /** // * Gets the sequence of {@code n}-grams, each containing {@code n} // * {@link Note} objects, from the {@link Melody} specified. // * // * @param m // * the melody. // * @param n // * the length of the n-grams. // * @return the sequence of {@code n}-grams. // */ // public static ArrayList<NGram> getNGrams(Melody m, int n) { // ArrayList<NGram> list = new ArrayList<NGram>(); // // for (int i = 0; i <= m.size() - n; i++) { // NGram gram = new NGram(); // for (int j = 0; j < n; j++) // gram.add(m.get(i + j)); // list.add(gram); // } // // return list; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // String res = ""; // for (Note n : this) // res += "{" + n.getPitch() + "," + n.getDuration() + "," + n.getRestFraction() + "}"; // return res; // } // } // // Path: src/jurbano/melodyshape/comparison/NGramComparer.java // public interface NGramComparer // { // /** // * Gets the name of this {@code NGramComparer}. // * // * @return the name of this n-gram comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two n-grams. // * <p> // * The similarity score is proportional to the melodic similarity between // * the notes in each n-gram, that is // * {@code compare(n1, n2) > compare(n1, n3)} means that n-gram {@code n2} is // * more similar to {@code n1} than {@code n3} is. // * // * @param g1 // * the first n-gram to compare. // * @param g2 // * the second n-gram to compare. // * @return the similarity score. // */ // public double compare(NGram g1, NGram g2); // // /** // * Gets an identifier for an {@link NGram} object according to this // * {@link NGramComparer}. This method is intended to identify different // * n-grams that are considered as the same by this {@code NGramComparer} and // * thus speed up computations and tune similarity scores in different // * algorithms. // * <p> // * For instance, if this {@code NGramComparer} only considers the pitch // * dimension of melodies, no information about time should appear in an // * {@link NGram}'s identifier. // * // * @param g // * the n-gram to compute the identifier for. // * @return the identifier. // */ // public String getNGramId(NGram g); // } // Path: src/jurbano/melodyshape/comparison/alignment/LocalAligner.java import jurbano.melodyshape.comparison.NGramComparer; import java.util.ArrayList; import jurbano.melodyshape.comparison.NGram; // Copyright (C) 2013, 2015-2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison.alignment; /** * An implementation of the Smith-Waterman alignment algorithm for sequences of {@link NGram}s. * * @author Julián Urbano * @see NGram * @see NGramComparer */ public class LocalAligner implements MelodyAligner {
protected NGramComparer comparer;
julian-urbano/MelodyShape
src/jurbano/melodyshape/comparison/alignment/LocalAligner.java
// Path: src/jurbano/melodyshape/comparison/NGram.java // @SuppressWarnings("serial") // public class NGram extends ArrayList<Note> // { // /** // * Gets a null n-gram of this object. A null n-gram contains the same notes // * but with all notes set to the pitch of this n-gram's first note. // * // * @return the null n-gram. // */ // public NGram getNullSpan() { // NGram s = new NGram(); // for (Note n : this) // s.add(new Note(this.get(0).getPitch(), n.getOnset(), n.getDuration(), n.getRestFraction())); // return s; // } // // /** // * Gets the sequence of {@code n}-grams, each containing {@code n} // * {@link Note} objects, from the {@link Melody} specified. // * // * @param m // * the melody. // * @param n // * the length of the n-grams. // * @return the sequence of {@code n}-grams. // */ // public static ArrayList<NGram> getNGrams(Melody m, int n) { // ArrayList<NGram> list = new ArrayList<NGram>(); // // for (int i = 0; i <= m.size() - n; i++) { // NGram gram = new NGram(); // for (int j = 0; j < n; j++) // gram.add(m.get(i + j)); // list.add(gram); // } // // return list; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // String res = ""; // for (Note n : this) // res += "{" + n.getPitch() + "," + n.getDuration() + "," + n.getRestFraction() + "}"; // return res; // } // } // // Path: src/jurbano/melodyshape/comparison/NGramComparer.java // public interface NGramComparer // { // /** // * Gets the name of this {@code NGramComparer}. // * // * @return the name of this n-gram comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two n-grams. // * <p> // * The similarity score is proportional to the melodic similarity between // * the notes in each n-gram, that is // * {@code compare(n1, n2) > compare(n1, n3)} means that n-gram {@code n2} is // * more similar to {@code n1} than {@code n3} is. // * // * @param g1 // * the first n-gram to compare. // * @param g2 // * the second n-gram to compare. // * @return the similarity score. // */ // public double compare(NGram g1, NGram g2); // // /** // * Gets an identifier for an {@link NGram} object according to this // * {@link NGramComparer}. This method is intended to identify different // * n-grams that are considered as the same by this {@code NGramComparer} and // * thus speed up computations and tune similarity scores in different // * algorithms. // * <p> // * For instance, if this {@code NGramComparer} only considers the pitch // * dimension of melodies, no information about time should appear in an // * {@link NGram}'s identifier. // * // * @param g // * the n-gram to compute the identifier for. // * @return the identifier. // */ // public String getNGramId(NGram g); // }
import jurbano.melodyshape.comparison.NGramComparer; import java.util.ArrayList; import jurbano.melodyshape.comparison.NGram;
// Copyright (C) 2013, 2015-2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison.alignment; /** * An implementation of the Smith-Waterman alignment algorithm for sequences of {@link NGram}s. * * @author Julián Urbano * @see NGram * @see NGramComparer */ public class LocalAligner implements MelodyAligner { protected NGramComparer comparer; /** * Constructs a new {@code LocalAligner} with the specified {@link NGramComparer}. * * @param comparer the n-gram comparer to use. */ public LocalAligner(NGramComparer comparer) { this.comparer = comparer; } /** * {@inheritDoc} * * @return the {@link String} {@code "Local(comparer)"}, where * {@code comparer} is the name of the underlying * {@link NGramComparer}. */ @Override public String getName() { return "Local("+this.comparer.getName()+")"; } /** * {@inheritDoc} */ @Override
// Path: src/jurbano/melodyshape/comparison/NGram.java // @SuppressWarnings("serial") // public class NGram extends ArrayList<Note> // { // /** // * Gets a null n-gram of this object. A null n-gram contains the same notes // * but with all notes set to the pitch of this n-gram's first note. // * // * @return the null n-gram. // */ // public NGram getNullSpan() { // NGram s = new NGram(); // for (Note n : this) // s.add(new Note(this.get(0).getPitch(), n.getOnset(), n.getDuration(), n.getRestFraction())); // return s; // } // // /** // * Gets the sequence of {@code n}-grams, each containing {@code n} // * {@link Note} objects, from the {@link Melody} specified. // * // * @param m // * the melody. // * @param n // * the length of the n-grams. // * @return the sequence of {@code n}-grams. // */ // public static ArrayList<NGram> getNGrams(Melody m, int n) { // ArrayList<NGram> list = new ArrayList<NGram>(); // // for (int i = 0; i <= m.size() - n; i++) { // NGram gram = new NGram(); // for (int j = 0; j < n; j++) // gram.add(m.get(i + j)); // list.add(gram); // } // // return list; // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // String res = ""; // for (Note n : this) // res += "{" + n.getPitch() + "," + n.getDuration() + "," + n.getRestFraction() + "}"; // return res; // } // } // // Path: src/jurbano/melodyshape/comparison/NGramComparer.java // public interface NGramComparer // { // /** // * Gets the name of this {@code NGramComparer}. // * // * @return the name of this n-gram comparer. // */ // public String getName(); // // /** // * Computes a similarity score between two n-grams. // * <p> // * The similarity score is proportional to the melodic similarity between // * the notes in each n-gram, that is // * {@code compare(n1, n2) > compare(n1, n3)} means that n-gram {@code n2} is // * more similar to {@code n1} than {@code n3} is. // * // * @param g1 // * the first n-gram to compare. // * @param g2 // * the second n-gram to compare. // * @return the similarity score. // */ // public double compare(NGram g1, NGram g2); // // /** // * Gets an identifier for an {@link NGram} object according to this // * {@link NGramComparer}. This method is intended to identify different // * n-grams that are considered as the same by this {@code NGramComparer} and // * thus speed up computations and tune similarity scores in different // * algorithms. // * <p> // * For instance, if this {@code NGramComparer} only considers the pitch // * dimension of melodies, no information about time should appear in an // * {@link NGram}'s identifier. // * // * @param g // * the n-gram to compute the identifier for. // * @return the identifier. // */ // public String getNGramId(NGram g); // } // Path: src/jurbano/melodyshape/comparison/alignment/LocalAligner.java import jurbano.melodyshape.comparison.NGramComparer; import java.util.ArrayList; import jurbano.melodyshape.comparison.NGram; // Copyright (C) 2013, 2015-2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.comparison.alignment; /** * An implementation of the Smith-Waterman alignment algorithm for sequences of {@link NGram}s. * * @author Julián Urbano * @see NGram * @see NGramComparer */ public class LocalAligner implements MelodyAligner { protected NGramComparer comparer; /** * Constructs a new {@code LocalAligner} with the specified {@link NGramComparer}. * * @param comparer the n-gram comparer to use. */ public LocalAligner(NGramComparer comparer) { this.comparer = comparer; } /** * {@inheritDoc} * * @return the {@link String} {@code "Local(comparer)"}, where * {@code comparer} is the name of the underlying * {@link NGramComparer}. */ @Override public String getName() { return "Local("+this.comparer.getName()+")"; } /** * {@inheritDoc} */ @Override
public double align(ArrayList<NGram> s1, ArrayList<NGram> s2) {
julian-urbano/MelodyShape
src/jurbano/melodyshape/ranking/ResultRanker.java
// Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // }
import jurbano.melodyshape.model.Melody;
// Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.ranking; /** * An algorithm to rank the similarity scores for a given query according to * different criteria. * * @author Julián Urbano * @see Result * @see Melody */ public interface ResultRanker { /** * Gets the name of this {@code ResultRanker}. * * @return the name of this result ranker. */ public String getName(); /** * Ranks the top {@code k} {@link Result}s for the specified query * {@link Melody}. Results are ranked in decreasing order of similarity to * the query. * * @param query * the query that originated the results. * @param results * the unranked list of results. * @param k * the cutoff. */
// Path: src/jurbano/melodyshape/model/Melody.java // @SuppressWarnings("serial") // public class Melody extends ArrayList<Note> // { // protected String id; // // /** // * Gets the unique ID of the melody. // * // * @return the ID of the melody. // */ // public String getId() { // return this.id; // } // // /** // * Constructs a new and empty {@code Melody} object. // * // * @param id // * the unique ID of the melody. // */ // public Melody(String id) { // this.id = id; // } // // @Override // public String toString() { // return "Melody [id=" + id + ", size=" + this.size() + "]"; // } // } // Path: src/jurbano/melodyshape/ranking/ResultRanker.java import jurbano.melodyshape.model.Melody; // Copyright (C) 2013, 2016 Julián Urbano <urbano.julian@gmail.com> // Distributed under the terms of the MIT License. package jurbano.melodyshape.ranking; /** * An algorithm to rank the similarity scores for a given query according to * different criteria. * * @author Julián Urbano * @see Result * @see Melody */ public interface ResultRanker { /** * Gets the name of this {@code ResultRanker}. * * @return the name of this result ranker. */ public String getName(); /** * Ranks the top {@code k} {@link Result}s for the specified query * {@link Melody}. Results are ranked in decreasing order of similarity to * the query. * * @param query * the query that originated the results. * @param results * the unranked list of results. * @param k * the cutoff. */
public void rank(Melody query, Result[] results, int k);
apradanas/prismoji-android
app/src/main/java/com/apradanas/prismojisample/SampleApplication.java
// Path: prismoji/src/main/java/com/apradanas/prismoji/PrismojiManager.java // public final class PrismojiManager { // private static final PrismojiManager INSTANCE = new PrismojiManager(); // // private final EmojiTree emojiTree = new EmojiTree(); // private EmojiCategory[] categories; // // private PrismojiManager() { // // No instances apart from singleton. // } // // public static PrismojiManager getInstance() { // return INSTANCE; // } // // /** // * Installs the given PrismojiProvider. // * // * NOTE: That only one can be present at any time. // * // * @param provider the provider that should be installed. // */ // public static void install(@NonNull final PrismojiProvider provider) { // INSTANCE.categories = checkNotNull(provider.getCategories(), "categories == null"); // INSTANCE.emojiTree.clear(); // // //noinspection ForLoopReplaceableByForEach // for (int i = 0; i < INSTANCE.categories.length; i++) { // final Emoji[] emojis = checkNotNull(INSTANCE.categories[i].getEmojis(), "emojies == null"); // // //noinspection ForLoopReplaceableByForEach // for (int j = 0; j < emojis.length; j++) { // INSTANCE.emojiTree.add(emojis[j]); // } // } // } // // EmojiCategory[] getCategories() { // verifyInstalled(); // return categories; // NOPMD // } // // @Nullable // Emoji findEmoji(@NonNull final CharSequence candiate) { // verifyInstalled(); // return emojiTree.findEmoji(candiate); // } // // public void verifyInstalled() { // if (categories == null) { // throw new IllegalStateException("Please install an PrismojiProvider through the PrismojiManager.install() method first."); // } // } // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/one/PrismojiOneProvider.java // public final class PrismojiOneProvider implements PrismojiProvider { // @Override // @NonNull // public EmojiCategory[] getCategories() { // return new EmojiCategory[]{ // new PeopleCategory(), // new NatureCategory(), // new FoodsCategory(), // new ActivityCategory(), // new TravelCategory(), // new ObjectsCategory(), // new SymbolsCategory(), // new FlagsCategory() // }; // } // }
import android.app.Application; import com.apradanas.prismoji.PrismojiManager; import com.apradanas.prismoji.one.PrismojiOneProvider;
package com.apradanas.prismojisample; /** * Created by apradanas. */ public class SampleApplication extends Application { @Override public void onCreate() { super.onCreate();
// Path: prismoji/src/main/java/com/apradanas/prismoji/PrismojiManager.java // public final class PrismojiManager { // private static final PrismojiManager INSTANCE = new PrismojiManager(); // // private final EmojiTree emojiTree = new EmojiTree(); // private EmojiCategory[] categories; // // private PrismojiManager() { // // No instances apart from singleton. // } // // public static PrismojiManager getInstance() { // return INSTANCE; // } // // /** // * Installs the given PrismojiProvider. // * // * NOTE: That only one can be present at any time. // * // * @param provider the provider that should be installed. // */ // public static void install(@NonNull final PrismojiProvider provider) { // INSTANCE.categories = checkNotNull(provider.getCategories(), "categories == null"); // INSTANCE.emojiTree.clear(); // // //noinspection ForLoopReplaceableByForEach // for (int i = 0; i < INSTANCE.categories.length; i++) { // final Emoji[] emojis = checkNotNull(INSTANCE.categories[i].getEmojis(), "emojies == null"); // // //noinspection ForLoopReplaceableByForEach // for (int j = 0; j < emojis.length; j++) { // INSTANCE.emojiTree.add(emojis[j]); // } // } // } // // EmojiCategory[] getCategories() { // verifyInstalled(); // return categories; // NOPMD // } // // @Nullable // Emoji findEmoji(@NonNull final CharSequence candiate) { // verifyInstalled(); // return emojiTree.findEmoji(candiate); // } // // public void verifyInstalled() { // if (categories == null) { // throw new IllegalStateException("Please install an PrismojiProvider through the PrismojiManager.install() method first."); // } // } // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/one/PrismojiOneProvider.java // public final class PrismojiOneProvider implements PrismojiProvider { // @Override // @NonNull // public EmojiCategory[] getCategories() { // return new EmojiCategory[]{ // new PeopleCategory(), // new NatureCategory(), // new FoodsCategory(), // new ActivityCategory(), // new TravelCategory(), // new ObjectsCategory(), // new SymbolsCategory(), // new FlagsCategory() // }; // } // } // Path: app/src/main/java/com/apradanas/prismojisample/SampleApplication.java import android.app.Application; import com.apradanas.prismoji.PrismojiManager; import com.apradanas.prismoji.one.PrismojiOneProvider; package com.apradanas.prismojisample; /** * Created by apradanas. */ public class SampleApplication extends Application { @Override public void onCreate() { super.onCreate();
PrismojiManager.install(new PrismojiOneProvider());
apradanas/prismoji-android
app/src/main/java/com/apradanas/prismojisample/SampleApplication.java
// Path: prismoji/src/main/java/com/apradanas/prismoji/PrismojiManager.java // public final class PrismojiManager { // private static final PrismojiManager INSTANCE = new PrismojiManager(); // // private final EmojiTree emojiTree = new EmojiTree(); // private EmojiCategory[] categories; // // private PrismojiManager() { // // No instances apart from singleton. // } // // public static PrismojiManager getInstance() { // return INSTANCE; // } // // /** // * Installs the given PrismojiProvider. // * // * NOTE: That only one can be present at any time. // * // * @param provider the provider that should be installed. // */ // public static void install(@NonNull final PrismojiProvider provider) { // INSTANCE.categories = checkNotNull(provider.getCategories(), "categories == null"); // INSTANCE.emojiTree.clear(); // // //noinspection ForLoopReplaceableByForEach // for (int i = 0; i < INSTANCE.categories.length; i++) { // final Emoji[] emojis = checkNotNull(INSTANCE.categories[i].getEmojis(), "emojies == null"); // // //noinspection ForLoopReplaceableByForEach // for (int j = 0; j < emojis.length; j++) { // INSTANCE.emojiTree.add(emojis[j]); // } // } // } // // EmojiCategory[] getCategories() { // verifyInstalled(); // return categories; // NOPMD // } // // @Nullable // Emoji findEmoji(@NonNull final CharSequence candiate) { // verifyInstalled(); // return emojiTree.findEmoji(candiate); // } // // public void verifyInstalled() { // if (categories == null) { // throw new IllegalStateException("Please install an PrismojiProvider through the PrismojiManager.install() method first."); // } // } // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/one/PrismojiOneProvider.java // public final class PrismojiOneProvider implements PrismojiProvider { // @Override // @NonNull // public EmojiCategory[] getCategories() { // return new EmojiCategory[]{ // new PeopleCategory(), // new NatureCategory(), // new FoodsCategory(), // new ActivityCategory(), // new TravelCategory(), // new ObjectsCategory(), // new SymbolsCategory(), // new FlagsCategory() // }; // } // }
import android.app.Application; import com.apradanas.prismoji.PrismojiManager; import com.apradanas.prismoji.one.PrismojiOneProvider;
package com.apradanas.prismojisample; /** * Created by apradanas. */ public class SampleApplication extends Application { @Override public void onCreate() { super.onCreate();
// Path: prismoji/src/main/java/com/apradanas/prismoji/PrismojiManager.java // public final class PrismojiManager { // private static final PrismojiManager INSTANCE = new PrismojiManager(); // // private final EmojiTree emojiTree = new EmojiTree(); // private EmojiCategory[] categories; // // private PrismojiManager() { // // No instances apart from singleton. // } // // public static PrismojiManager getInstance() { // return INSTANCE; // } // // /** // * Installs the given PrismojiProvider. // * // * NOTE: That only one can be present at any time. // * // * @param provider the provider that should be installed. // */ // public static void install(@NonNull final PrismojiProvider provider) { // INSTANCE.categories = checkNotNull(provider.getCategories(), "categories == null"); // INSTANCE.emojiTree.clear(); // // //noinspection ForLoopReplaceableByForEach // for (int i = 0; i < INSTANCE.categories.length; i++) { // final Emoji[] emojis = checkNotNull(INSTANCE.categories[i].getEmojis(), "emojies == null"); // // //noinspection ForLoopReplaceableByForEach // for (int j = 0; j < emojis.length; j++) { // INSTANCE.emojiTree.add(emojis[j]); // } // } // } // // EmojiCategory[] getCategories() { // verifyInstalled(); // return categories; // NOPMD // } // // @Nullable // Emoji findEmoji(@NonNull final CharSequence candiate) { // verifyInstalled(); // return emojiTree.findEmoji(candiate); // } // // public void verifyInstalled() { // if (categories == null) { // throw new IllegalStateException("Please install an PrismojiProvider through the PrismojiManager.install() method first."); // } // } // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/one/PrismojiOneProvider.java // public final class PrismojiOneProvider implements PrismojiProvider { // @Override // @NonNull // public EmojiCategory[] getCategories() { // return new EmojiCategory[]{ // new PeopleCategory(), // new NatureCategory(), // new FoodsCategory(), // new ActivityCategory(), // new TravelCategory(), // new ObjectsCategory(), // new SymbolsCategory(), // new FlagsCategory() // }; // } // } // Path: app/src/main/java/com/apradanas/prismojisample/SampleApplication.java import android.app.Application; import com.apradanas.prismoji.PrismojiManager; import com.apradanas.prismoji.one.PrismojiOneProvider; package com.apradanas.prismojisample; /** * Created by apradanas. */ public class SampleApplication extends Application { @Override public void onCreate() { super.onCreate();
PrismojiManager.install(new PrismojiOneProvider());
apradanas/prismoji-android
prismoji/src/main/java/com/apradanas/prismoji/RecentEmoji.java
// Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/Emoji.java // public final class Emoji implements Serializable { // private static final long serialVersionUID = 3L; // // @NonNull // private final String unicode; // @DrawableRes // private final int resource; // @NonNull // private List<Emoji> variants; // @SuppressWarnings("PMD.ImmutableField") // @Nullable // private Emoji base; // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource) { // this(codePoints, resource, new Emoji[0]); // } // // public Emoji(final int codePoint, @DrawableRes final int resource) { // this(codePoint, resource, new Emoji[0]); // } // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource, final Emoji... variants) { // this.unicode = new String(codePoints, 0, codePoints.length); // this.resource = resource; // this.variants = Arrays.asList(variants); // // for (final Emoji variant : variants) { // variant.base = this; // } // } // // public Emoji(final int codePoint, @DrawableRes final int resource, final Emoji... variants) { // this(new int[]{codePoint}, resource, variants); // } // // @NonNull // public String getUnicode() { // return unicode; // } // // @DrawableRes // public int getResource() { // return resource; // } // // @NonNull // public List<Emoji> getVariants() { // return new ArrayList<>(variants); // } // // @NonNull // public Emoji getBase() { // Emoji result = this; // // while (result.base != null) { // result = result.base; // } // // return result; // } // // public int getLength() { // return unicode.length(); // } // // public boolean hasVariants() { // return !variants.isEmpty(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // final Emoji emoji = (Emoji) o; // // return resource == emoji.resource // && unicode.equals(emoji.unicode) // && variants.equals(emoji.variants); // } // // @Override // public int hashCode() { // int result = unicode.hashCode(); // result = 31 * result + resource; // result = 31 * result + variants.hashCode(); // return result; // } // }
import android.support.annotation.NonNull; import com.apradanas.prismoji.emoji.Emoji; import java.util.Collection;
package com.apradanas.prismoji; /** * Interface for providing some custom implementation for recent emojis * * @since 0.2.0 */ public interface RecentEmoji { /** * returns recent emojis. Could be loaded from a database, shared preferences or just hard * coded.<br> * This method will be called more than one time hence it is recommended to hold a collection of * recent emojis * * @since 0.2.0 */ @NonNull
// Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/Emoji.java // public final class Emoji implements Serializable { // private static final long serialVersionUID = 3L; // // @NonNull // private final String unicode; // @DrawableRes // private final int resource; // @NonNull // private List<Emoji> variants; // @SuppressWarnings("PMD.ImmutableField") // @Nullable // private Emoji base; // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource) { // this(codePoints, resource, new Emoji[0]); // } // // public Emoji(final int codePoint, @DrawableRes final int resource) { // this(codePoint, resource, new Emoji[0]); // } // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource, final Emoji... variants) { // this.unicode = new String(codePoints, 0, codePoints.length); // this.resource = resource; // this.variants = Arrays.asList(variants); // // for (final Emoji variant : variants) { // variant.base = this; // } // } // // public Emoji(final int codePoint, @DrawableRes final int resource, final Emoji... variants) { // this(new int[]{codePoint}, resource, variants); // } // // @NonNull // public String getUnicode() { // return unicode; // } // // @DrawableRes // public int getResource() { // return resource; // } // // @NonNull // public List<Emoji> getVariants() { // return new ArrayList<>(variants); // } // // @NonNull // public Emoji getBase() { // Emoji result = this; // // while (result.base != null) { // result = result.base; // } // // return result; // } // // public int getLength() { // return unicode.length(); // } // // public boolean hasVariants() { // return !variants.isEmpty(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // final Emoji emoji = (Emoji) o; // // return resource == emoji.resource // && unicode.equals(emoji.unicode) // && variants.equals(emoji.variants); // } // // @Override // public int hashCode() { // int result = unicode.hashCode(); // result = 31 * result + resource; // result = 31 * result + variants.hashCode(); // return result; // } // } // Path: prismoji/src/main/java/com/apradanas/prismoji/RecentEmoji.java import android.support.annotation.NonNull; import com.apradanas.prismoji.emoji.Emoji; import java.util.Collection; package com.apradanas.prismoji; /** * Interface for providing some custom implementation for recent emojis * * @since 0.2.0 */ public interface RecentEmoji { /** * returns recent emojis. Could be loaded from a database, shared preferences or just hard * coded.<br> * This method will be called more than one time hence it is recommended to hold a collection of * recent emojis * * @since 0.2.0 */ @NonNull
Collection<Emoji> getRecentEmojis();
apradanas/prismoji-android
prismoji/src/main/java/com/apradanas/prismoji/RecentPrismojiGridView.java
// Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/Emoji.java // public final class Emoji implements Serializable { // private static final long serialVersionUID = 3L; // // @NonNull // private final String unicode; // @DrawableRes // private final int resource; // @NonNull // private List<Emoji> variants; // @SuppressWarnings("PMD.ImmutableField") // @Nullable // private Emoji base; // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource) { // this(codePoints, resource, new Emoji[0]); // } // // public Emoji(final int codePoint, @DrawableRes final int resource) { // this(codePoint, resource, new Emoji[0]); // } // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource, final Emoji... variants) { // this.unicode = new String(codePoints, 0, codePoints.length); // this.resource = resource; // this.variants = Arrays.asList(variants); // // for (final Emoji variant : variants) { // variant.base = this; // } // } // // public Emoji(final int codePoint, @DrawableRes final int resource, final Emoji... variants) { // this(new int[]{codePoint}, resource, variants); // } // // @NonNull // public String getUnicode() { // return unicode; // } // // @DrawableRes // public int getResource() { // return resource; // } // // @NonNull // public List<Emoji> getVariants() { // return new ArrayList<>(variants); // } // // @NonNull // public Emoji getBase() { // Emoji result = this; // // while (result.base != null) { // result = result.base; // } // // return result; // } // // public int getLength() { // return unicode.length(); // } // // public boolean hasVariants() { // return !variants.isEmpty(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // final Emoji emoji = (Emoji) o; // // return resource == emoji.resource // && unicode.equals(emoji.unicode) // && variants.equals(emoji.variants); // } // // @Override // public int hashCode() { // int result = unicode.hashCode(); // result = 31 * result + resource; // result = 31 * result + variants.hashCode(); // return result; // } // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/listeners/OnEmojiClickedListener.java // public interface OnEmojiClickedListener { // void onEmojiClicked(final Emoji emoji); // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/listeners/OnEmojiLongClickedListener.java // public interface OnEmojiLongClickedListener { // void onEmojiLongClicked(final View view, final Emoji emoji); // }
import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.apradanas.prismoji.emoji.Emoji; import com.apradanas.prismoji.listeners.OnEmojiClickedListener; import com.apradanas.prismoji.listeners.OnEmojiLongClickedListener; import java.util.Collection;
package com.apradanas.prismoji; final class RecentPrismojiGridView extends PrismojiGridView { private RecentEmoji recentEmojis; RecentPrismojiGridView(@NonNull final Context context) { super(context); }
// Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/Emoji.java // public final class Emoji implements Serializable { // private static final long serialVersionUID = 3L; // // @NonNull // private final String unicode; // @DrawableRes // private final int resource; // @NonNull // private List<Emoji> variants; // @SuppressWarnings("PMD.ImmutableField") // @Nullable // private Emoji base; // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource) { // this(codePoints, resource, new Emoji[0]); // } // // public Emoji(final int codePoint, @DrawableRes final int resource) { // this(codePoint, resource, new Emoji[0]); // } // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource, final Emoji... variants) { // this.unicode = new String(codePoints, 0, codePoints.length); // this.resource = resource; // this.variants = Arrays.asList(variants); // // for (final Emoji variant : variants) { // variant.base = this; // } // } // // public Emoji(final int codePoint, @DrawableRes final int resource, final Emoji... variants) { // this(new int[]{codePoint}, resource, variants); // } // // @NonNull // public String getUnicode() { // return unicode; // } // // @DrawableRes // public int getResource() { // return resource; // } // // @NonNull // public List<Emoji> getVariants() { // return new ArrayList<>(variants); // } // // @NonNull // public Emoji getBase() { // Emoji result = this; // // while (result.base != null) { // result = result.base; // } // // return result; // } // // public int getLength() { // return unicode.length(); // } // // public boolean hasVariants() { // return !variants.isEmpty(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // final Emoji emoji = (Emoji) o; // // return resource == emoji.resource // && unicode.equals(emoji.unicode) // && variants.equals(emoji.variants); // } // // @Override // public int hashCode() { // int result = unicode.hashCode(); // result = 31 * result + resource; // result = 31 * result + variants.hashCode(); // return result; // } // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/listeners/OnEmojiClickedListener.java // public interface OnEmojiClickedListener { // void onEmojiClicked(final Emoji emoji); // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/listeners/OnEmojiLongClickedListener.java // public interface OnEmojiLongClickedListener { // void onEmojiLongClicked(final View view, final Emoji emoji); // } // Path: prismoji/src/main/java/com/apradanas/prismoji/RecentPrismojiGridView.java import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.apradanas.prismoji.emoji.Emoji; import com.apradanas.prismoji.listeners.OnEmojiClickedListener; import com.apradanas.prismoji.listeners.OnEmojiLongClickedListener; import java.util.Collection; package com.apradanas.prismoji; final class RecentPrismojiGridView extends PrismojiGridView { private RecentEmoji recentEmojis; RecentPrismojiGridView(@NonNull final Context context) { super(context); }
public RecentPrismojiGridView init(@Nullable final OnEmojiClickedListener onEmojiClickedListener,
apradanas/prismoji-android
prismoji/src/main/java/com/apradanas/prismoji/RecentPrismojiGridView.java
// Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/Emoji.java // public final class Emoji implements Serializable { // private static final long serialVersionUID = 3L; // // @NonNull // private final String unicode; // @DrawableRes // private final int resource; // @NonNull // private List<Emoji> variants; // @SuppressWarnings("PMD.ImmutableField") // @Nullable // private Emoji base; // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource) { // this(codePoints, resource, new Emoji[0]); // } // // public Emoji(final int codePoint, @DrawableRes final int resource) { // this(codePoint, resource, new Emoji[0]); // } // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource, final Emoji... variants) { // this.unicode = new String(codePoints, 0, codePoints.length); // this.resource = resource; // this.variants = Arrays.asList(variants); // // for (final Emoji variant : variants) { // variant.base = this; // } // } // // public Emoji(final int codePoint, @DrawableRes final int resource, final Emoji... variants) { // this(new int[]{codePoint}, resource, variants); // } // // @NonNull // public String getUnicode() { // return unicode; // } // // @DrawableRes // public int getResource() { // return resource; // } // // @NonNull // public List<Emoji> getVariants() { // return new ArrayList<>(variants); // } // // @NonNull // public Emoji getBase() { // Emoji result = this; // // while (result.base != null) { // result = result.base; // } // // return result; // } // // public int getLength() { // return unicode.length(); // } // // public boolean hasVariants() { // return !variants.isEmpty(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // final Emoji emoji = (Emoji) o; // // return resource == emoji.resource // && unicode.equals(emoji.unicode) // && variants.equals(emoji.variants); // } // // @Override // public int hashCode() { // int result = unicode.hashCode(); // result = 31 * result + resource; // result = 31 * result + variants.hashCode(); // return result; // } // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/listeners/OnEmojiClickedListener.java // public interface OnEmojiClickedListener { // void onEmojiClicked(final Emoji emoji); // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/listeners/OnEmojiLongClickedListener.java // public interface OnEmojiLongClickedListener { // void onEmojiLongClicked(final View view, final Emoji emoji); // }
import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.apradanas.prismoji.emoji.Emoji; import com.apradanas.prismoji.listeners.OnEmojiClickedListener; import com.apradanas.prismoji.listeners.OnEmojiLongClickedListener; import java.util.Collection;
package com.apradanas.prismoji; final class RecentPrismojiGridView extends PrismojiGridView { private RecentEmoji recentEmojis; RecentPrismojiGridView(@NonNull final Context context) { super(context); } public RecentPrismojiGridView init(@Nullable final OnEmojiClickedListener onEmojiClickedListener,
// Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/Emoji.java // public final class Emoji implements Serializable { // private static final long serialVersionUID = 3L; // // @NonNull // private final String unicode; // @DrawableRes // private final int resource; // @NonNull // private List<Emoji> variants; // @SuppressWarnings("PMD.ImmutableField") // @Nullable // private Emoji base; // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource) { // this(codePoints, resource, new Emoji[0]); // } // // public Emoji(final int codePoint, @DrawableRes final int resource) { // this(codePoint, resource, new Emoji[0]); // } // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource, final Emoji... variants) { // this.unicode = new String(codePoints, 0, codePoints.length); // this.resource = resource; // this.variants = Arrays.asList(variants); // // for (final Emoji variant : variants) { // variant.base = this; // } // } // // public Emoji(final int codePoint, @DrawableRes final int resource, final Emoji... variants) { // this(new int[]{codePoint}, resource, variants); // } // // @NonNull // public String getUnicode() { // return unicode; // } // // @DrawableRes // public int getResource() { // return resource; // } // // @NonNull // public List<Emoji> getVariants() { // return new ArrayList<>(variants); // } // // @NonNull // public Emoji getBase() { // Emoji result = this; // // while (result.base != null) { // result = result.base; // } // // return result; // } // // public int getLength() { // return unicode.length(); // } // // public boolean hasVariants() { // return !variants.isEmpty(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // final Emoji emoji = (Emoji) o; // // return resource == emoji.resource // && unicode.equals(emoji.unicode) // && variants.equals(emoji.variants); // } // // @Override // public int hashCode() { // int result = unicode.hashCode(); // result = 31 * result + resource; // result = 31 * result + variants.hashCode(); // return result; // } // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/listeners/OnEmojiClickedListener.java // public interface OnEmojiClickedListener { // void onEmojiClicked(final Emoji emoji); // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/listeners/OnEmojiLongClickedListener.java // public interface OnEmojiLongClickedListener { // void onEmojiLongClicked(final View view, final Emoji emoji); // } // Path: prismoji/src/main/java/com/apradanas/prismoji/RecentPrismojiGridView.java import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.apradanas.prismoji.emoji.Emoji; import com.apradanas.prismoji.listeners.OnEmojiClickedListener; import com.apradanas.prismoji.listeners.OnEmojiLongClickedListener; import java.util.Collection; package com.apradanas.prismoji; final class RecentPrismojiGridView extends PrismojiGridView { private RecentEmoji recentEmojis; RecentPrismojiGridView(@NonNull final Context context) { super(context); } public RecentPrismojiGridView init(@Nullable final OnEmojiClickedListener onEmojiClickedListener,
@Nullable final OnEmojiLongClickedListener onEmojiLongClickedListener,
apradanas/prismoji-android
prismoji/src/main/java/com/apradanas/prismoji/RecentPrismojiGridView.java
// Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/Emoji.java // public final class Emoji implements Serializable { // private static final long serialVersionUID = 3L; // // @NonNull // private final String unicode; // @DrawableRes // private final int resource; // @NonNull // private List<Emoji> variants; // @SuppressWarnings("PMD.ImmutableField") // @Nullable // private Emoji base; // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource) { // this(codePoints, resource, new Emoji[0]); // } // // public Emoji(final int codePoint, @DrawableRes final int resource) { // this(codePoint, resource, new Emoji[0]); // } // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource, final Emoji... variants) { // this.unicode = new String(codePoints, 0, codePoints.length); // this.resource = resource; // this.variants = Arrays.asList(variants); // // for (final Emoji variant : variants) { // variant.base = this; // } // } // // public Emoji(final int codePoint, @DrawableRes final int resource, final Emoji... variants) { // this(new int[]{codePoint}, resource, variants); // } // // @NonNull // public String getUnicode() { // return unicode; // } // // @DrawableRes // public int getResource() { // return resource; // } // // @NonNull // public List<Emoji> getVariants() { // return new ArrayList<>(variants); // } // // @NonNull // public Emoji getBase() { // Emoji result = this; // // while (result.base != null) { // result = result.base; // } // // return result; // } // // public int getLength() { // return unicode.length(); // } // // public boolean hasVariants() { // return !variants.isEmpty(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // final Emoji emoji = (Emoji) o; // // return resource == emoji.resource // && unicode.equals(emoji.unicode) // && variants.equals(emoji.variants); // } // // @Override // public int hashCode() { // int result = unicode.hashCode(); // result = 31 * result + resource; // result = 31 * result + variants.hashCode(); // return result; // } // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/listeners/OnEmojiClickedListener.java // public interface OnEmojiClickedListener { // void onEmojiClicked(final Emoji emoji); // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/listeners/OnEmojiLongClickedListener.java // public interface OnEmojiLongClickedListener { // void onEmojiLongClicked(final View view, final Emoji emoji); // }
import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.apradanas.prismoji.emoji.Emoji; import com.apradanas.prismoji.listeners.OnEmojiClickedListener; import com.apradanas.prismoji.listeners.OnEmojiLongClickedListener; import java.util.Collection;
package com.apradanas.prismoji; final class RecentPrismojiGridView extends PrismojiGridView { private RecentEmoji recentEmojis; RecentPrismojiGridView(@NonNull final Context context) { super(context); } public RecentPrismojiGridView init(@Nullable final OnEmojiClickedListener onEmojiClickedListener, @Nullable final OnEmojiLongClickedListener onEmojiLongClickedListener, @NonNull final RecentEmoji recentEmoji) { recentEmojis = recentEmoji;
// Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/Emoji.java // public final class Emoji implements Serializable { // private static final long serialVersionUID = 3L; // // @NonNull // private final String unicode; // @DrawableRes // private final int resource; // @NonNull // private List<Emoji> variants; // @SuppressWarnings("PMD.ImmutableField") // @Nullable // private Emoji base; // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource) { // this(codePoints, resource, new Emoji[0]); // } // // public Emoji(final int codePoint, @DrawableRes final int resource) { // this(codePoint, resource, new Emoji[0]); // } // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource, final Emoji... variants) { // this.unicode = new String(codePoints, 0, codePoints.length); // this.resource = resource; // this.variants = Arrays.asList(variants); // // for (final Emoji variant : variants) { // variant.base = this; // } // } // // public Emoji(final int codePoint, @DrawableRes final int resource, final Emoji... variants) { // this(new int[]{codePoint}, resource, variants); // } // // @NonNull // public String getUnicode() { // return unicode; // } // // @DrawableRes // public int getResource() { // return resource; // } // // @NonNull // public List<Emoji> getVariants() { // return new ArrayList<>(variants); // } // // @NonNull // public Emoji getBase() { // Emoji result = this; // // while (result.base != null) { // result = result.base; // } // // return result; // } // // public int getLength() { // return unicode.length(); // } // // public boolean hasVariants() { // return !variants.isEmpty(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // final Emoji emoji = (Emoji) o; // // return resource == emoji.resource // && unicode.equals(emoji.unicode) // && variants.equals(emoji.variants); // } // // @Override // public int hashCode() { // int result = unicode.hashCode(); // result = 31 * result + resource; // result = 31 * result + variants.hashCode(); // return result; // } // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/listeners/OnEmojiClickedListener.java // public interface OnEmojiClickedListener { // void onEmojiClicked(final Emoji emoji); // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/listeners/OnEmojiLongClickedListener.java // public interface OnEmojiLongClickedListener { // void onEmojiLongClicked(final View view, final Emoji emoji); // } // Path: prismoji/src/main/java/com/apradanas/prismoji/RecentPrismojiGridView.java import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.apradanas.prismoji.emoji.Emoji; import com.apradanas.prismoji.listeners.OnEmojiClickedListener; import com.apradanas.prismoji.listeners.OnEmojiLongClickedListener; import java.util.Collection; package com.apradanas.prismoji; final class RecentPrismojiGridView extends PrismojiGridView { private RecentEmoji recentEmojis; RecentPrismojiGridView(@NonNull final Context context) { super(context); } public RecentPrismojiGridView init(@Nullable final OnEmojiClickedListener onEmojiClickedListener, @Nullable final OnEmojiLongClickedListener onEmojiLongClickedListener, @NonNull final RecentEmoji recentEmoji) { recentEmojis = recentEmoji;
final Collection<Emoji> emojis = recentEmojis.getRecentEmojis();
apradanas/prismoji-android
prismoji/src/main/java/com/apradanas/prismoji/one/category/NatureCategory.java
// Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/Emoji.java // public final class Emoji implements Serializable { // private static final long serialVersionUID = 3L; // // @NonNull // private final String unicode; // @DrawableRes // private final int resource; // @NonNull // private List<Emoji> variants; // @SuppressWarnings("PMD.ImmutableField") // @Nullable // private Emoji base; // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource) { // this(codePoints, resource, new Emoji[0]); // } // // public Emoji(final int codePoint, @DrawableRes final int resource) { // this(codePoint, resource, new Emoji[0]); // } // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource, final Emoji... variants) { // this.unicode = new String(codePoints, 0, codePoints.length); // this.resource = resource; // this.variants = Arrays.asList(variants); // // for (final Emoji variant : variants) { // variant.base = this; // } // } // // public Emoji(final int codePoint, @DrawableRes final int resource, final Emoji... variants) { // this(new int[]{codePoint}, resource, variants); // } // // @NonNull // public String getUnicode() { // return unicode; // } // // @DrawableRes // public int getResource() { // return resource; // } // // @NonNull // public List<Emoji> getVariants() { // return new ArrayList<>(variants); // } // // @NonNull // public Emoji getBase() { // Emoji result = this; // // while (result.base != null) { // result = result.base; // } // // return result; // } // // public int getLength() { // return unicode.length(); // } // // public boolean hasVariants() { // return !variants.isEmpty(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // final Emoji emoji = (Emoji) o; // // return resource == emoji.resource // && unicode.equals(emoji.unicode) // && variants.equals(emoji.variants); // } // // @Override // public int hashCode() { // int result = unicode.hashCode(); // result = 31 * result + resource; // result = 31 * result + variants.hashCode(); // return result; // } // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/EmojiCategory.java // public interface EmojiCategory { // /** // * returns all of the emojis it can display // * // * @since 0.4.0 // */ // @NonNull // Emoji[] getEmojis(); // // /** // * returns the icon of the category that should be displayed // * // * @since 0.4.0 // */ // @DrawableRes // int getIcon(); // }
import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import com.apradanas.prismoji.R; import com.apradanas.prismoji.emoji.Emoji; import com.apradanas.prismoji.emoji.EmojiCategory;
package com.apradanas.prismoji.one.category; @SuppressWarnings("PMD.MethodReturnsInternalArray") public final class NatureCategory implements EmojiCategory {
// Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/Emoji.java // public final class Emoji implements Serializable { // private static final long serialVersionUID = 3L; // // @NonNull // private final String unicode; // @DrawableRes // private final int resource; // @NonNull // private List<Emoji> variants; // @SuppressWarnings("PMD.ImmutableField") // @Nullable // private Emoji base; // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource) { // this(codePoints, resource, new Emoji[0]); // } // // public Emoji(final int codePoint, @DrawableRes final int resource) { // this(codePoint, resource, new Emoji[0]); // } // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource, final Emoji... variants) { // this.unicode = new String(codePoints, 0, codePoints.length); // this.resource = resource; // this.variants = Arrays.asList(variants); // // for (final Emoji variant : variants) { // variant.base = this; // } // } // // public Emoji(final int codePoint, @DrawableRes final int resource, final Emoji... variants) { // this(new int[]{codePoint}, resource, variants); // } // // @NonNull // public String getUnicode() { // return unicode; // } // // @DrawableRes // public int getResource() { // return resource; // } // // @NonNull // public List<Emoji> getVariants() { // return new ArrayList<>(variants); // } // // @NonNull // public Emoji getBase() { // Emoji result = this; // // while (result.base != null) { // result = result.base; // } // // return result; // } // // public int getLength() { // return unicode.length(); // } // // public boolean hasVariants() { // return !variants.isEmpty(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // final Emoji emoji = (Emoji) o; // // return resource == emoji.resource // && unicode.equals(emoji.unicode) // && variants.equals(emoji.variants); // } // // @Override // public int hashCode() { // int result = unicode.hashCode(); // result = 31 * result + resource; // result = 31 * result + variants.hashCode(); // return result; // } // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/EmojiCategory.java // public interface EmojiCategory { // /** // * returns all of the emojis it can display // * // * @since 0.4.0 // */ // @NonNull // Emoji[] getEmojis(); // // /** // * returns the icon of the category that should be displayed // * // * @since 0.4.0 // */ // @DrawableRes // int getIcon(); // } // Path: prismoji/src/main/java/com/apradanas/prismoji/one/category/NatureCategory.java import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import com.apradanas.prismoji.R; import com.apradanas.prismoji.emoji.Emoji; import com.apradanas.prismoji.emoji.EmojiCategory; package com.apradanas.prismoji.one.category; @SuppressWarnings("PMD.MethodReturnsInternalArray") public final class NatureCategory implements EmojiCategory {
private static final Emoji[] DATA = new Emoji[]{
apradanas/prismoji-android
prismoji/src/main/java/com/apradanas/prismoji/PrismojiPagerAdapter.java
// Path: prismoji/src/main/java/com/apradanas/prismoji/listeners/OnEmojiClickedListener.java // public interface OnEmojiClickedListener { // void onEmojiClicked(final Emoji emoji); // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/listeners/OnEmojiLongClickedListener.java // public interface OnEmojiLongClickedListener { // void onEmojiLongClicked(final View view, final Emoji emoji); // }
import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import com.apradanas.prismoji.listeners.OnEmojiClickedListener; import com.apradanas.prismoji.listeners.OnEmojiLongClickedListener;
package com.apradanas.prismoji; final class PrismojiPagerAdapter extends PagerAdapter { private final OnEmojiClickedListener listener;
// Path: prismoji/src/main/java/com/apradanas/prismoji/listeners/OnEmojiClickedListener.java // public interface OnEmojiClickedListener { // void onEmojiClicked(final Emoji emoji); // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/listeners/OnEmojiLongClickedListener.java // public interface OnEmojiLongClickedListener { // void onEmojiLongClicked(final View view, final Emoji emoji); // } // Path: prismoji/src/main/java/com/apradanas/prismoji/PrismojiPagerAdapter.java import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import com.apradanas.prismoji.listeners.OnEmojiClickedListener; import com.apradanas.prismoji.listeners.OnEmojiLongClickedListener; package com.apradanas.prismoji; final class PrismojiPagerAdapter extends PagerAdapter { private final OnEmojiClickedListener listener;
private final OnEmojiLongClickedListener longListener;
apradanas/prismoji-android
prismoji/src/main/java/com/apradanas/prismoji/PrismojiEditText.java
// Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/Emoji.java // public final class Emoji implements Serializable { // private static final long serialVersionUID = 3L; // // @NonNull // private final String unicode; // @DrawableRes // private final int resource; // @NonNull // private List<Emoji> variants; // @SuppressWarnings("PMD.ImmutableField") // @Nullable // private Emoji base; // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource) { // this(codePoints, resource, new Emoji[0]); // } // // public Emoji(final int codePoint, @DrawableRes final int resource) { // this(codePoint, resource, new Emoji[0]); // } // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource, final Emoji... variants) { // this.unicode = new String(codePoints, 0, codePoints.length); // this.resource = resource; // this.variants = Arrays.asList(variants); // // for (final Emoji variant : variants) { // variant.base = this; // } // } // // public Emoji(final int codePoint, @DrawableRes final int resource, final Emoji... variants) { // this(new int[]{codePoint}, resource, variants); // } // // @NonNull // public String getUnicode() { // return unicode; // } // // @DrawableRes // public int getResource() { // return resource; // } // // @NonNull // public List<Emoji> getVariants() { // return new ArrayList<>(variants); // } // // @NonNull // public Emoji getBase() { // Emoji result = this; // // while (result.base != null) { // result = result.base; // } // // return result; // } // // public int getLength() { // return unicode.length(); // } // // public boolean hasVariants() { // return !variants.isEmpty(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // final Emoji emoji = (Emoji) o; // // return resource == emoji.resource // && unicode.equals(emoji.unicode) // && variants.equals(emoji.variants); // } // // @Override // public int hashCode() { // int result = unicode.hashCode(); // result = 31 * result + resource; // result = 31 * result + variants.hashCode(); // return result; // } // }
import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.Nullable; import android.support.v7.widget.AppCompatEditText; import android.util.AttributeSet; import android.view.KeyEvent; import com.apradanas.prismoji.emoji.Emoji;
if (attrs == null) { emojiSize = (int) getTextSize(); } else { final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.emoji); try { emojiSize = (int) a.getDimension(R.styleable.emoji_emojiSize, getTextSize()); } finally { a.recycle(); } } setText(getText()); } @Override protected void onTextChanged(final CharSequence text, final int start, final int lengthBefore, final int lengthAfter) { PrismojiHandler.addEmojis(getContext(), getText(), emojiSize); } public void setEmojiSize(final int pixels) { emojiSize = pixels; } public void backspace() { final KeyEvent event = new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL); dispatchKeyEvent(event); }
// Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/Emoji.java // public final class Emoji implements Serializable { // private static final long serialVersionUID = 3L; // // @NonNull // private final String unicode; // @DrawableRes // private final int resource; // @NonNull // private List<Emoji> variants; // @SuppressWarnings("PMD.ImmutableField") // @Nullable // private Emoji base; // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource) { // this(codePoints, resource, new Emoji[0]); // } // // public Emoji(final int codePoint, @DrawableRes final int resource) { // this(codePoint, resource, new Emoji[0]); // } // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource, final Emoji... variants) { // this.unicode = new String(codePoints, 0, codePoints.length); // this.resource = resource; // this.variants = Arrays.asList(variants); // // for (final Emoji variant : variants) { // variant.base = this; // } // } // // public Emoji(final int codePoint, @DrawableRes final int resource, final Emoji... variants) { // this(new int[]{codePoint}, resource, variants); // } // // @NonNull // public String getUnicode() { // return unicode; // } // // @DrawableRes // public int getResource() { // return resource; // } // // @NonNull // public List<Emoji> getVariants() { // return new ArrayList<>(variants); // } // // @NonNull // public Emoji getBase() { // Emoji result = this; // // while (result.base != null) { // result = result.base; // } // // return result; // } // // public int getLength() { // return unicode.length(); // } // // public boolean hasVariants() { // return !variants.isEmpty(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // final Emoji emoji = (Emoji) o; // // return resource == emoji.resource // && unicode.equals(emoji.unicode) // && variants.equals(emoji.variants); // } // // @Override // public int hashCode() { // int result = unicode.hashCode(); // result = 31 * result + resource; // result = 31 * result + variants.hashCode(); // return result; // } // } // Path: prismoji/src/main/java/com/apradanas/prismoji/PrismojiEditText.java import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.Nullable; import android.support.v7.widget.AppCompatEditText; import android.util.AttributeSet; import android.view.KeyEvent; import com.apradanas.prismoji.emoji.Emoji; if (attrs == null) { emojiSize = (int) getTextSize(); } else { final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.emoji); try { emojiSize = (int) a.getDimension(R.styleable.emoji_emojiSize, getTextSize()); } finally { a.recycle(); } } setText(getText()); } @Override protected void onTextChanged(final CharSequence text, final int start, final int lengthBefore, final int lengthAfter) { PrismojiHandler.addEmojis(getContext(), getText(), emojiSize); } public void setEmojiSize(final int pixels) { emojiSize = pixels; } public void backspace() { final KeyEvent event = new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL); dispatchKeyEvent(event); }
public void input(final Emoji emoji) {
apradanas/prismoji-android
prismoji/src/main/java/com/apradanas/prismoji/one/category/SymbolsCategory.java
// Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/Emoji.java // public final class Emoji implements Serializable { // private static final long serialVersionUID = 3L; // // @NonNull // private final String unicode; // @DrawableRes // private final int resource; // @NonNull // private List<Emoji> variants; // @SuppressWarnings("PMD.ImmutableField") // @Nullable // private Emoji base; // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource) { // this(codePoints, resource, new Emoji[0]); // } // // public Emoji(final int codePoint, @DrawableRes final int resource) { // this(codePoint, resource, new Emoji[0]); // } // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource, final Emoji... variants) { // this.unicode = new String(codePoints, 0, codePoints.length); // this.resource = resource; // this.variants = Arrays.asList(variants); // // for (final Emoji variant : variants) { // variant.base = this; // } // } // // public Emoji(final int codePoint, @DrawableRes final int resource, final Emoji... variants) { // this(new int[]{codePoint}, resource, variants); // } // // @NonNull // public String getUnicode() { // return unicode; // } // // @DrawableRes // public int getResource() { // return resource; // } // // @NonNull // public List<Emoji> getVariants() { // return new ArrayList<>(variants); // } // // @NonNull // public Emoji getBase() { // Emoji result = this; // // while (result.base != null) { // result = result.base; // } // // return result; // } // // public int getLength() { // return unicode.length(); // } // // public boolean hasVariants() { // return !variants.isEmpty(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // final Emoji emoji = (Emoji) o; // // return resource == emoji.resource // && unicode.equals(emoji.unicode) // && variants.equals(emoji.variants); // } // // @Override // public int hashCode() { // int result = unicode.hashCode(); // result = 31 * result + resource; // result = 31 * result + variants.hashCode(); // return result; // } // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/EmojiCategory.java // public interface EmojiCategory { // /** // * returns all of the emojis it can display // * // * @since 0.4.0 // */ // @NonNull // Emoji[] getEmojis(); // // /** // * returns the icon of the category that should be displayed // * // * @since 0.4.0 // */ // @DrawableRes // int getIcon(); // }
import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import com.apradanas.prismoji.R; import com.apradanas.prismoji.emoji.Emoji; import com.apradanas.prismoji.emoji.EmojiCategory;
package com.apradanas.prismoji.one.category; @SuppressWarnings("PMD.MethodReturnsInternalArray") public final class SymbolsCategory implements EmojiCategory {
// Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/Emoji.java // public final class Emoji implements Serializable { // private static final long serialVersionUID = 3L; // // @NonNull // private final String unicode; // @DrawableRes // private final int resource; // @NonNull // private List<Emoji> variants; // @SuppressWarnings("PMD.ImmutableField") // @Nullable // private Emoji base; // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource) { // this(codePoints, resource, new Emoji[0]); // } // // public Emoji(final int codePoint, @DrawableRes final int resource) { // this(codePoint, resource, new Emoji[0]); // } // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource, final Emoji... variants) { // this.unicode = new String(codePoints, 0, codePoints.length); // this.resource = resource; // this.variants = Arrays.asList(variants); // // for (final Emoji variant : variants) { // variant.base = this; // } // } // // public Emoji(final int codePoint, @DrawableRes final int resource, final Emoji... variants) { // this(new int[]{codePoint}, resource, variants); // } // // @NonNull // public String getUnicode() { // return unicode; // } // // @DrawableRes // public int getResource() { // return resource; // } // // @NonNull // public List<Emoji> getVariants() { // return new ArrayList<>(variants); // } // // @NonNull // public Emoji getBase() { // Emoji result = this; // // while (result.base != null) { // result = result.base; // } // // return result; // } // // public int getLength() { // return unicode.length(); // } // // public boolean hasVariants() { // return !variants.isEmpty(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // final Emoji emoji = (Emoji) o; // // return resource == emoji.resource // && unicode.equals(emoji.unicode) // && variants.equals(emoji.variants); // } // // @Override // public int hashCode() { // int result = unicode.hashCode(); // result = 31 * result + resource; // result = 31 * result + variants.hashCode(); // return result; // } // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/EmojiCategory.java // public interface EmojiCategory { // /** // * returns all of the emojis it can display // * // * @since 0.4.0 // */ // @NonNull // Emoji[] getEmojis(); // // /** // * returns the icon of the category that should be displayed // * // * @since 0.4.0 // */ // @DrawableRes // int getIcon(); // } // Path: prismoji/src/main/java/com/apradanas/prismoji/one/category/SymbolsCategory.java import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import com.apradanas.prismoji.R; import com.apradanas.prismoji.emoji.Emoji; import com.apradanas.prismoji.emoji.EmojiCategory; package com.apradanas.prismoji.one.category; @SuppressWarnings("PMD.MethodReturnsInternalArray") public final class SymbolsCategory implements EmojiCategory {
private static final Emoji[] DATA = new Emoji[]{
apradanas/prismoji-android
prismoji/src/main/java/com/apradanas/prismoji/one/category/TravelCategory.java
// Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/Emoji.java // public final class Emoji implements Serializable { // private static final long serialVersionUID = 3L; // // @NonNull // private final String unicode; // @DrawableRes // private final int resource; // @NonNull // private List<Emoji> variants; // @SuppressWarnings("PMD.ImmutableField") // @Nullable // private Emoji base; // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource) { // this(codePoints, resource, new Emoji[0]); // } // // public Emoji(final int codePoint, @DrawableRes final int resource) { // this(codePoint, resource, new Emoji[0]); // } // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource, final Emoji... variants) { // this.unicode = new String(codePoints, 0, codePoints.length); // this.resource = resource; // this.variants = Arrays.asList(variants); // // for (final Emoji variant : variants) { // variant.base = this; // } // } // // public Emoji(final int codePoint, @DrawableRes final int resource, final Emoji... variants) { // this(new int[]{codePoint}, resource, variants); // } // // @NonNull // public String getUnicode() { // return unicode; // } // // @DrawableRes // public int getResource() { // return resource; // } // // @NonNull // public List<Emoji> getVariants() { // return new ArrayList<>(variants); // } // // @NonNull // public Emoji getBase() { // Emoji result = this; // // while (result.base != null) { // result = result.base; // } // // return result; // } // // public int getLength() { // return unicode.length(); // } // // public boolean hasVariants() { // return !variants.isEmpty(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // final Emoji emoji = (Emoji) o; // // return resource == emoji.resource // && unicode.equals(emoji.unicode) // && variants.equals(emoji.variants); // } // // @Override // public int hashCode() { // int result = unicode.hashCode(); // result = 31 * result + resource; // result = 31 * result + variants.hashCode(); // return result; // } // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/EmojiCategory.java // public interface EmojiCategory { // /** // * returns all of the emojis it can display // * // * @since 0.4.0 // */ // @NonNull // Emoji[] getEmojis(); // // /** // * returns the icon of the category that should be displayed // * // * @since 0.4.0 // */ // @DrawableRes // int getIcon(); // }
import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import com.apradanas.prismoji.R; import com.apradanas.prismoji.emoji.Emoji; import com.apradanas.prismoji.emoji.EmojiCategory;
package com.apradanas.prismoji.one.category; @SuppressWarnings("PMD.MethodReturnsInternalArray") public final class TravelCategory implements EmojiCategory {
// Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/Emoji.java // public final class Emoji implements Serializable { // private static final long serialVersionUID = 3L; // // @NonNull // private final String unicode; // @DrawableRes // private final int resource; // @NonNull // private List<Emoji> variants; // @SuppressWarnings("PMD.ImmutableField") // @Nullable // private Emoji base; // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource) { // this(codePoints, resource, new Emoji[0]); // } // // public Emoji(final int codePoint, @DrawableRes final int resource) { // this(codePoint, resource, new Emoji[0]); // } // // public Emoji(@NonNull final int[] codePoints, @DrawableRes final int resource, final Emoji... variants) { // this.unicode = new String(codePoints, 0, codePoints.length); // this.resource = resource; // this.variants = Arrays.asList(variants); // // for (final Emoji variant : variants) { // variant.base = this; // } // } // // public Emoji(final int codePoint, @DrawableRes final int resource, final Emoji... variants) { // this(new int[]{codePoint}, resource, variants); // } // // @NonNull // public String getUnicode() { // return unicode; // } // // @DrawableRes // public int getResource() { // return resource; // } // // @NonNull // public List<Emoji> getVariants() { // return new ArrayList<>(variants); // } // // @NonNull // public Emoji getBase() { // Emoji result = this; // // while (result.base != null) { // result = result.base; // } // // return result; // } // // public int getLength() { // return unicode.length(); // } // // public boolean hasVariants() { // return !variants.isEmpty(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) { // return true; // } // // if (o == null || getClass() != o.getClass()) { // return false; // } // // final Emoji emoji = (Emoji) o; // // return resource == emoji.resource // && unicode.equals(emoji.unicode) // && variants.equals(emoji.variants); // } // // @Override // public int hashCode() { // int result = unicode.hashCode(); // result = 31 * result + resource; // result = 31 * result + variants.hashCode(); // return result; // } // } // // Path: prismoji/src/main/java/com/apradanas/prismoji/emoji/EmojiCategory.java // public interface EmojiCategory { // /** // * returns all of the emojis it can display // * // * @since 0.4.0 // */ // @NonNull // Emoji[] getEmojis(); // // /** // * returns the icon of the category that should be displayed // * // * @since 0.4.0 // */ // @DrawableRes // int getIcon(); // } // Path: prismoji/src/main/java/com/apradanas/prismoji/one/category/TravelCategory.java import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import com.apradanas.prismoji.R; import com.apradanas.prismoji.emoji.Emoji; import com.apradanas.prismoji.emoji.EmojiCategory; package com.apradanas.prismoji.one.category; @SuppressWarnings("PMD.MethodReturnsInternalArray") public final class TravelCategory implements EmojiCategory {
private static final Emoji[] DATA = new Emoji[]{