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
asdfjkl/jerry
src/main/java/org/asdfjkl/jerryfx/lib/PgnReader.java
// Path: src/main/java/org/asdfjkl/jerryfx/gui/PgnDatabaseEntry.java // public class PgnDatabaseEntry { // // private long offset = 0; // private long index = 0; // private String event = ""; // private String site = ""; // private String date = ""; // private String round = ""; // private String white = ""; // private String black = ""; // private String result = ""; // private String eco = ""; // private boolean modifiedFlag = false; // Game modifiedGame = null; // // private boolean foundAtLeast1Tag = false; // // public long getOffset() { return offset; } // // public void setOffset(long offset) { this.offset = offset; } // // public long getIndex() { return index; } // public void setIndex(long index) { this.index = index; } // // public String getEvent() { return event; } // public void setEvent(String event) { this.event = event; } // // public String getSite() { return site; } // public void setSite(String site) { this.site = site; } // // public String getDate() { return date; } // public void setDate(String date) { this.date = date; } // // public String getRound() { return round; } // public void setRound(String round ) { this.round = round; } // // public String getWhite() { return white; } // public void setWhite(String white) { this.white = white; } // // public String getBlack() { return black; } // public void setBlack(String black) { this.black = black; } // // public String getResult() { return result; } // public void setResult(String result) { this.result = result; } // // public String getEco() { return eco; } // public void setEco(String eco) { this.eco = eco; } // // public void markValid() { // foundAtLeast1Tag = true; // } // // public void markAsModified() { modifiedFlag = true; } // public boolean wasModified() { return modifiedFlag; } // public void markAsUnmodified() { // modifiedFlag = false; // modifiedGame = null; // } // // public void setModifiedGame(Game game) { modifiedGame = game; } // public Game getModifiedGame() { return modifiedGame; } // // public boolean isValid() { // return foundAtLeast1Tag; // } // // }
import com.ibm.icu.text.CharsetDetector; import com.ibm.icu.text.CharsetMatch; import org.asdfjkl.jerryfx.gui.PgnDatabaseEntry; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.Stack;
return true; } QDataStream in(&file); // init some char array to read bytes char first100arr[100]; for(int i=0;i<100;i++) { first100arr[i] = 0x00; } char *first100 = first100arr; // prep conversion tools QTextCodec::ConverterState state; QTextCodec *codec = QTextCodec::codecForName("UTF-8"); int iterations = 40; int i=0; int l = 100; bool isUtf8 = true; while(i<iterations && l>=100) { l = in.readRawData(first100, 100); const QString text = codec->toUnicode(first100, 100, &state); if (state.invalidChars > 0) { isUtf8 = false; break; } i++; } return isUtf8; } */
// Path: src/main/java/org/asdfjkl/jerryfx/gui/PgnDatabaseEntry.java // public class PgnDatabaseEntry { // // private long offset = 0; // private long index = 0; // private String event = ""; // private String site = ""; // private String date = ""; // private String round = ""; // private String white = ""; // private String black = ""; // private String result = ""; // private String eco = ""; // private boolean modifiedFlag = false; // Game modifiedGame = null; // // private boolean foundAtLeast1Tag = false; // // public long getOffset() { return offset; } // // public void setOffset(long offset) { this.offset = offset; } // // public long getIndex() { return index; } // public void setIndex(long index) { this.index = index; } // // public String getEvent() { return event; } // public void setEvent(String event) { this.event = event; } // // public String getSite() { return site; } // public void setSite(String site) { this.site = site; } // // public String getDate() { return date; } // public void setDate(String date) { this.date = date; } // // public String getRound() { return round; } // public void setRound(String round ) { this.round = round; } // // public String getWhite() { return white; } // public void setWhite(String white) { this.white = white; } // // public String getBlack() { return black; } // public void setBlack(String black) { this.black = black; } // // public String getResult() { return result; } // public void setResult(String result) { this.result = result; } // // public String getEco() { return eco; } // public void setEco(String eco) { this.eco = eco; } // // public void markValid() { // foundAtLeast1Tag = true; // } // // public void markAsModified() { modifiedFlag = true; } // public boolean wasModified() { return modifiedFlag; } // public void markAsUnmodified() { // modifiedFlag = false; // modifiedGame = null; // } // // public void setModifiedGame(Game game) { modifiedGame = game; } // public Game getModifiedGame() { return modifiedGame; } // // public boolean isValid() { // return foundAtLeast1Tag; // } // // } // Path: src/main/java/org/asdfjkl/jerryfx/lib/PgnReader.java import com.ibm.icu.text.CharsetDetector; import com.ibm.icu.text.CharsetMatch; import org.asdfjkl.jerryfx.gui.PgnDatabaseEntry; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.Stack; return true; } QDataStream in(&file); // init some char array to read bytes char first100arr[100]; for(int i=0;i<100;i++) { first100arr[i] = 0x00; } char *first100 = first100arr; // prep conversion tools QTextCodec::ConverterState state; QTextCodec *codec = QTextCodec::codecForName("UTF-8"); int iterations = 40; int i=0; int l = 100; bool isUtf8 = true; while(i<iterations && l>=100) { l = in.readRawData(first100, 100); const QString text = codec->toUnicode(first100, 100, &state); if (state.invalidChars > 0) { isUtf8 = false; break; } i++; } return isUtf8; } */
ArrayList<PgnDatabaseEntry> scanPgnGetSTR(String filename) {
asdfjkl/jerry
src/main/java/org/asdfjkl/jerryfx/gui/BarchartWDL.java
// Path: src/main/java/org/asdfjkl/jerryfx/lib/PolyglotExtEntry.java // public class PolyglotExtEntry { // long key; // int move; // long count; // int whiteWinPerc; // int blackWinPerc; // int drawPerc; // int avgElo; // String uci; // // public long getPosCount() { return count; } // public void setPosCount(long count) { this.count = count; } // // public String getMove() { return uci; } // public void setMove(String uci) { this.uci = uci; } // // public Integer getWins() { return whiteWinPerc; } // public void setWins(Integer whiteWinPerc) { this.whiteWinPerc = whiteWinPerc; } // // public Integer getDraws() { return drawPerc; } // public void setDraws(Integer drawPerc) { this.drawPerc = drawPerc; } // // public Integer getLosses() { return blackWinPerc; } // public void setLosses(Integer blackWinPerc) { this.blackWinPerc = blackWinPerc; } // // public int getAvgELO() { return avgElo; } // public void setAvgELO(int avgElo) { this.avgElo = avgElo; } // // @Override // public String toString() { // return "" + key + " " + count + " " + move + " " + uci + " " + whiteWinPerc + " " + drawPerc + " " + blackWinPerc + " " + avgElo; // } // // // }
import javafx.geometry.Pos; import javafx.scene.control.Label; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import org.asdfjkl.jerryfx.lib.PolyglotExtEntry;
lblDraws.setAlignment(Pos.CENTER); lblLoss.setAlignment(Pos.CENTER); lblWins.setMaxWidth(Double.MAX_VALUE); lblDraws.setMaxWidth(Double.MAX_VALUE); lblLoss.setMaxWidth(Double.MAX_VALUE); addRow(0, lblWins, lblDraws, lblLoss); getColumnConstraints().addAll( colConsWins, colConsDraws, colConsloss ); } public void setTheme(int theme) { if(theme == GameModel.STYLE_LIGHT) { lblWins.setStyle("-fx-background-color : lightgreen"); lblDraws.setStyle("-fx-background-color : rosybrown"); lblLoss.setStyle("-fx-background-color : indianred"); } else { lblWins.setStyle("-fx-background-color : darkgreen"); lblDraws.setStyle("-fx-background-color : saddlebrown"); lblLoss.setStyle("-fx-background-color : darkred"); } }
// Path: src/main/java/org/asdfjkl/jerryfx/lib/PolyglotExtEntry.java // public class PolyglotExtEntry { // long key; // int move; // long count; // int whiteWinPerc; // int blackWinPerc; // int drawPerc; // int avgElo; // String uci; // // public long getPosCount() { return count; } // public void setPosCount(long count) { this.count = count; } // // public String getMove() { return uci; } // public void setMove(String uci) { this.uci = uci; } // // public Integer getWins() { return whiteWinPerc; } // public void setWins(Integer whiteWinPerc) { this.whiteWinPerc = whiteWinPerc; } // // public Integer getDraws() { return drawPerc; } // public void setDraws(Integer drawPerc) { this.drawPerc = drawPerc; } // // public Integer getLosses() { return blackWinPerc; } // public void setLosses(Integer blackWinPerc) { this.blackWinPerc = blackWinPerc; } // // public int getAvgELO() { return avgElo; } // public void setAvgELO(int avgElo) { this.avgElo = avgElo; } // // @Override // public String toString() { // return "" + key + " " + count + " " + move + " " + uci + " " + whiteWinPerc + " " + drawPerc + " " + blackWinPerc + " " + avgElo; // } // // // } // Path: src/main/java/org/asdfjkl/jerryfx/gui/BarchartWDL.java import javafx.geometry.Pos; import javafx.scene.control.Label; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import org.asdfjkl.jerryfx.lib.PolyglotExtEntry; lblDraws.setAlignment(Pos.CENTER); lblLoss.setAlignment(Pos.CENTER); lblWins.setMaxWidth(Double.MAX_VALUE); lblDraws.setMaxWidth(Double.MAX_VALUE); lblLoss.setMaxWidth(Double.MAX_VALUE); addRow(0, lblWins, lblDraws, lblLoss); getColumnConstraints().addAll( colConsWins, colConsDraws, colConsloss ); } public void setTheme(int theme) { if(theme == GameModel.STYLE_LIGHT) { lblWins.setStyle("-fx-background-color : lightgreen"); lblDraws.setStyle("-fx-background-color : rosybrown"); lblLoss.setStyle("-fx-background-color : indianred"); } else { lblWins.setStyle("-fx-background-color : darkgreen"); lblDraws.setStyle("-fx-background-color : saddlebrown"); lblLoss.setStyle("-fx-background-color : darkred"); } }
public void setWDLRatio(PolyglotExtEntry entry) {
asdfjkl/jerry
src/main/java/org/asdfjkl/jerryfx/lib/TestCases.java
// Path: src/main/java/org/asdfjkl/jerryfx/gui/PgnDatabaseEntry.java // public class PgnDatabaseEntry { // // private long offset = 0; // private long index = 0; // private String event = ""; // private String site = ""; // private String date = ""; // private String round = ""; // private String white = ""; // private String black = ""; // private String result = ""; // private String eco = ""; // private boolean modifiedFlag = false; // Game modifiedGame = null; // // private boolean foundAtLeast1Tag = false; // // public long getOffset() { return offset; } // // public void setOffset(long offset) { this.offset = offset; } // // public long getIndex() { return index; } // public void setIndex(long index) { this.index = index; } // // public String getEvent() { return event; } // public void setEvent(String event) { this.event = event; } // // public String getSite() { return site; } // public void setSite(String site) { this.site = site; } // // public String getDate() { return date; } // public void setDate(String date) { this.date = date; } // // public String getRound() { return round; } // public void setRound(String round ) { this.round = round; } // // public String getWhite() { return white; } // public void setWhite(String white) { this.white = white; } // // public String getBlack() { return black; } // public void setBlack(String black) { this.black = black; } // // public String getResult() { return result; } // public void setResult(String result) { this.result = result; } // // public String getEco() { return eco; } // public void setEco(String eco) { this.eco = eco; } // // public void markValid() { // foundAtLeast1Tag = true; // } // // public void markAsModified() { modifiedFlag = true; } // public boolean wasModified() { return modifiedFlag; } // public void markAsUnmodified() { // modifiedFlag = false; // modifiedGame = null; // } // // public void setModifiedGame(Game game) { modifiedGame = game; } // public Game getModifiedGame() { return modifiedGame; } // // public boolean isValid() { // return foundAtLeast1Tag; // } // // }
import org.asdfjkl.jerryfx.gui.PgnDatabaseEntry; import java.io.*; import java.net.URL; import java.util.ArrayList; import java.util.HashMap;
System.out.println("START"+line+"STOP"); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if(raf != null) { try { raf.close(); } catch (IOException e) { e.printStackTrace(); } } } } } public void pgnScanSTRTest() { System.out.println("TEST: scanning PGN for game STR offsets"); String kingbase = "C:/Users/user/MyFiles/workspace/test_databases/KingBaseLite2016-03-E60-E99.pgn"; String millbase = "C:/Users/user/MyFiles/workspace/test_databases/millionbase-2.22.pgn"; String middleg = "C:/Users/user/MyFiles/workspace/test_databases/middleg.pgn"; PgnReader reader = new PgnReader(); if(reader.isIsoLatin1(millbase)) { reader.setEncodingIsoLatin1(); } long startTime = System.currentTimeMillis();
// Path: src/main/java/org/asdfjkl/jerryfx/gui/PgnDatabaseEntry.java // public class PgnDatabaseEntry { // // private long offset = 0; // private long index = 0; // private String event = ""; // private String site = ""; // private String date = ""; // private String round = ""; // private String white = ""; // private String black = ""; // private String result = ""; // private String eco = ""; // private boolean modifiedFlag = false; // Game modifiedGame = null; // // private boolean foundAtLeast1Tag = false; // // public long getOffset() { return offset; } // // public void setOffset(long offset) { this.offset = offset; } // // public long getIndex() { return index; } // public void setIndex(long index) { this.index = index; } // // public String getEvent() { return event; } // public void setEvent(String event) { this.event = event; } // // public String getSite() { return site; } // public void setSite(String site) { this.site = site; } // // public String getDate() { return date; } // public void setDate(String date) { this.date = date; } // // public String getRound() { return round; } // public void setRound(String round ) { this.round = round; } // // public String getWhite() { return white; } // public void setWhite(String white) { this.white = white; } // // public String getBlack() { return black; } // public void setBlack(String black) { this.black = black; } // // public String getResult() { return result; } // public void setResult(String result) { this.result = result; } // // public String getEco() { return eco; } // public void setEco(String eco) { this.eco = eco; } // // public void markValid() { // foundAtLeast1Tag = true; // } // // public void markAsModified() { modifiedFlag = true; } // public boolean wasModified() { return modifiedFlag; } // public void markAsUnmodified() { // modifiedFlag = false; // modifiedGame = null; // } // // public void setModifiedGame(Game game) { modifiedGame = game; } // public Game getModifiedGame() { return modifiedGame; } // // public boolean isValid() { // return foundAtLeast1Tag; // } // // } // Path: src/main/java/org/asdfjkl/jerryfx/lib/TestCases.java import org.asdfjkl.jerryfx.gui.PgnDatabaseEntry; import java.io.*; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; System.out.println("START"+line+"STOP"); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if(raf != null) { try { raf.close(); } catch (IOException e) { e.printStackTrace(); } } } } } public void pgnScanSTRTest() { System.out.println("TEST: scanning PGN for game STR offsets"); String kingbase = "C:/Users/user/MyFiles/workspace/test_databases/KingBaseLite2016-03-E60-E99.pgn"; String millbase = "C:/Users/user/MyFiles/workspace/test_databases/millionbase-2.22.pgn"; String middleg = "C:/Users/user/MyFiles/workspace/test_databases/middleg.pgn"; PgnReader reader = new PgnReader(); if(reader.isIsoLatin1(millbase)) { reader.setEncodingIsoLatin1(); } long startTime = System.currentTimeMillis();
ArrayList<PgnDatabaseEntry> entries = reader.scanPgnGetSTR(millbase);
json-path/JsonPath
json-path/src/main/java/com/jayway/jsonpath/internal/path/ScanPathToken.java
// Path: json-path/src/main/java/com/jayway/jsonpath/spi/json/JsonProvider.java // public interface JsonProvider { // // static final Object UNDEFINED = new Object(); // // /** // * Parse the given json string // * @param json json string to parse // * @return Object representation of json // * @throws InvalidJsonException // */ // Object parse(String json) throws InvalidJsonException; // // /** // * Parse the given json bytes in UTF-8 encoding // * @param json json bytes to parse // * @return Object representation of json // * @throws InvalidJsonException // */ // default Object parse(byte[] json) throws InvalidJsonException { // return parse(new String(json, StandardCharsets.UTF_8)); // } // /** // * Parse the given json string // * @param jsonStream input stream to parse // * @param charset charset to use // * @return Object representation of json // * @throws InvalidJsonException // */ // Object parse(InputStream jsonStream, String charset) throws InvalidJsonException; // // /** // * Convert given json object to a json string // * @param obj object to transform // * @return json representation of object // */ // String toJson(Object obj); // // /** // * Creates a provider specific json array // * @return new array // */ // Object createArray(); // // /** // * Creates a provider specific json object // * @return new object // */ // Object createMap(); // // /** // * checks if object is an array // * // * @param obj object to check // * @return true if obj is an array // */ // boolean isArray(Object obj); // // /** // * Get the length of an json array, json object or a json string // * // * @param obj an array or object or a string // * @return the number of entries in the array or object // */ // int length(Object obj); // // /** // * Converts given array to an {@link Iterable} // * // * @param obj an array // * @return an Iterable that iterates over the entries of an array // */ // Iterable<?> toIterable(Object obj); // // // /** // * Returns the keys from the given object // * // * @param obj an object // * @return the keys for an object // */ // Collection<String> getPropertyKeys(Object obj); // // /** // * Extracts a value from an array anw unwraps provider specific data type // * // * @param obj an array // * @param idx index // * @return the entry at the given index // */ // Object getArrayIndex(Object obj, int idx); // // /** // * Extracts a value from an array // * // * @param obj an array // * @param idx index // * @param unwrap should provider specific data type be unwrapped // * @return the entry at the given index // */ // @Deprecated // Object getArrayIndex(Object obj, int idx, boolean unwrap); // // /** // * Sets a value in an array. If the array is too small, the provider is supposed to enlarge it. // * // * @param array an array // * @param idx index // * @param newValue the new value // */ // void setArrayIndex(Object array, int idx, Object newValue); // // /** // * Extracts a value from an map // * // * @param obj a map // * @param key property key // * @return the map entry or {@link com.jayway.jsonpath.spi.json.JsonProvider#UNDEFINED} for missing properties // */ // Object getMapValue(Object obj, String key); // // /** // * Sets a value in an object // * // * @param obj an object // * @param key a String key // * @param value the value to set // */ // void setProperty(Object obj, Object key, Object value); // // /** // * Removes a value in an object or array // * // * @param obj an array or an object // * @param key a String key or a numerical index to remove // */ // void removeProperty(Object obj, Object key); // // /** // * checks if object is a map (i.e. no array) // * // * @param obj object to check // * @return true if the object is a map // */ // boolean isMap(Object obj); // // /** // * Extracts a value from a wrapper object. For JSON providers that to not wrap // * values, this will usually be the object itself. // * // * @param obj a value holder object // * @return the unwrapped value. // */ // Object unwrap(Object obj); // }
import com.jayway.jsonpath.Option; import com.jayway.jsonpath.internal.PathRef; import com.jayway.jsonpath.spi.json.JsonProvider; import java.util.Collection;
Iterable<?> models = ctx.jsonProvider().toIterable(model); int idx = 0; for (Object evalModel : models) { String evalPath = currentPath + "[" + idx + "]"; next.setUpstreamArrayIndex(idx); next.evaluate(evalPath, parent, evalModel, ctx); idx++; } } } Iterable<?> models = ctx.jsonProvider().toIterable(model); int idx = 0; for (Object evalModel : models) { String evalPath = currentPath + "[" + idx + "]"; walk(pt, evalPath, PathRef.create(model, idx), evalModel, ctx, predicate); idx++; } } public static void walkObject(PathToken pt, String currentPath, PathRef parent, Object model, EvaluationContextImpl ctx, Predicate predicate) { if (predicate.matches(model)) { pt.evaluate(currentPath, parent, model, ctx); } Collection<String> properties = ctx.jsonProvider().getPropertyKeys(model); for (String property : properties) { String evalPath = currentPath + "['" + property + "']"; Object propertyModel = ctx.jsonProvider().getMapValue(model, property);
// Path: json-path/src/main/java/com/jayway/jsonpath/spi/json/JsonProvider.java // public interface JsonProvider { // // static final Object UNDEFINED = new Object(); // // /** // * Parse the given json string // * @param json json string to parse // * @return Object representation of json // * @throws InvalidJsonException // */ // Object parse(String json) throws InvalidJsonException; // // /** // * Parse the given json bytes in UTF-8 encoding // * @param json json bytes to parse // * @return Object representation of json // * @throws InvalidJsonException // */ // default Object parse(byte[] json) throws InvalidJsonException { // return parse(new String(json, StandardCharsets.UTF_8)); // } // /** // * Parse the given json string // * @param jsonStream input stream to parse // * @param charset charset to use // * @return Object representation of json // * @throws InvalidJsonException // */ // Object parse(InputStream jsonStream, String charset) throws InvalidJsonException; // // /** // * Convert given json object to a json string // * @param obj object to transform // * @return json representation of object // */ // String toJson(Object obj); // // /** // * Creates a provider specific json array // * @return new array // */ // Object createArray(); // // /** // * Creates a provider specific json object // * @return new object // */ // Object createMap(); // // /** // * checks if object is an array // * // * @param obj object to check // * @return true if obj is an array // */ // boolean isArray(Object obj); // // /** // * Get the length of an json array, json object or a json string // * // * @param obj an array or object or a string // * @return the number of entries in the array or object // */ // int length(Object obj); // // /** // * Converts given array to an {@link Iterable} // * // * @param obj an array // * @return an Iterable that iterates over the entries of an array // */ // Iterable<?> toIterable(Object obj); // // // /** // * Returns the keys from the given object // * // * @param obj an object // * @return the keys for an object // */ // Collection<String> getPropertyKeys(Object obj); // // /** // * Extracts a value from an array anw unwraps provider specific data type // * // * @param obj an array // * @param idx index // * @return the entry at the given index // */ // Object getArrayIndex(Object obj, int idx); // // /** // * Extracts a value from an array // * // * @param obj an array // * @param idx index // * @param unwrap should provider specific data type be unwrapped // * @return the entry at the given index // */ // @Deprecated // Object getArrayIndex(Object obj, int idx, boolean unwrap); // // /** // * Sets a value in an array. If the array is too small, the provider is supposed to enlarge it. // * // * @param array an array // * @param idx index // * @param newValue the new value // */ // void setArrayIndex(Object array, int idx, Object newValue); // // /** // * Extracts a value from an map // * // * @param obj a map // * @param key property key // * @return the map entry or {@link com.jayway.jsonpath.spi.json.JsonProvider#UNDEFINED} for missing properties // */ // Object getMapValue(Object obj, String key); // // /** // * Sets a value in an object // * // * @param obj an object // * @param key a String key // * @param value the value to set // */ // void setProperty(Object obj, Object key, Object value); // // /** // * Removes a value in an object or array // * // * @param obj an array or an object // * @param key a String key or a numerical index to remove // */ // void removeProperty(Object obj, Object key); // // /** // * checks if object is a map (i.e. no array) // * // * @param obj object to check // * @return true if the object is a map // */ // boolean isMap(Object obj); // // /** // * Extracts a value from a wrapper object. For JSON providers that to not wrap // * values, this will usually be the object itself. // * // * @param obj a value holder object // * @return the unwrapped value. // */ // Object unwrap(Object obj); // } // Path: json-path/src/main/java/com/jayway/jsonpath/internal/path/ScanPathToken.java import com.jayway.jsonpath.Option; import com.jayway.jsonpath.internal.PathRef; import com.jayway.jsonpath.spi.json.JsonProvider; import java.util.Collection; Iterable<?> models = ctx.jsonProvider().toIterable(model); int idx = 0; for (Object evalModel : models) { String evalPath = currentPath + "[" + idx + "]"; next.setUpstreamArrayIndex(idx); next.evaluate(evalPath, parent, evalModel, ctx); idx++; } } } Iterable<?> models = ctx.jsonProvider().toIterable(model); int idx = 0; for (Object evalModel : models) { String evalPath = currentPath + "[" + idx + "]"; walk(pt, evalPath, PathRef.create(model, idx), evalModel, ctx, predicate); idx++; } } public static void walkObject(PathToken pt, String currentPath, PathRef parent, Object model, EvaluationContextImpl ctx, Predicate predicate) { if (predicate.matches(model)) { pt.evaluate(currentPath, parent, model, ctx); } Collection<String> properties = ctx.jsonProvider().getPropertyKeys(model); for (String property : properties) { String evalPath = currentPath + "['" + property + "']"; Object propertyModel = ctx.jsonProvider().getMapValue(model, property);
if (propertyModel != JsonProvider.UNDEFINED) {
json-path/JsonPath
json-path/src/test/java/com/jayway/jsonpath/internal/function/NestedFunctionTest.java
// Path: json-path/src/test/java/com/jayway/jsonpath/Configurations.java // public class Configurations { // // public static final Configuration JSON_ORG_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JsonOrgMappingProvider()) // .jsonProvider(new JsonOrgJsonProvider()) // .build(); // // public static final Configuration GSON_CONFIGURATION = Configuration // .builder() // .mappingProvider(new GsonMappingProvider()) // .jsonProvider(new GsonJsonProvider()) // .build(); // // public static final Configuration JACKSON_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JacksonMappingProvider()) // .jsonProvider(new JacksonJsonProvider()) // .build(); // // public static final Configuration JACKSON_JSON_NODE_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JacksonMappingProvider()) // .jsonProvider(new JacksonJsonNodeJsonProvider()) // .build(); // // public static final Configuration JSON_SMART_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JsonSmartMappingProvider()) // .jsonProvider(new JsonSmartJsonProvider()) // .build(); // // public static final Configuration JAKARTA_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JakartaMappingProvider()) // .jsonProvider(new JakartaJsonProvider()) // .build(); // // public static Iterable<Configuration> configurations() { // return Arrays.asList( // JSON_SMART_CONFIGURATION // ,GSON_CONFIGURATION // ,JACKSON_CONFIGURATION // ,JACKSON_JSON_NODE_CONFIGURATION // ,JSON_ORG_CONFIGURATION // ,JAKARTA_CONFIGURATION // ); // } // // public static Iterable<Configuration> objectMappingConfigurations() { // return Arrays.asList( // GSON_CONFIGURATION // ,JACKSON_CONFIGURATION // ,JACKSON_JSON_NODE_CONFIGURATION // ,JAKARTA_CONFIGURATION // ); // } // } // // Path: json-path/src/main/java/com/jayway/jsonpath/JsonPath.java // public static ParseContext using(Configuration configuration) { // return new ParseContextImpl(configuration); // }
import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.Configurations; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.jayway.jsonpath.JsonPath.using; import static org.junit.Assert.assertTrue;
package com.jayway.jsonpath.internal.function; /** * Created by [email protected] on 12/10/15. */ @RunWith(Parameterized.class) public class NestedFunctionTest extends BaseFunctionTest { private static final Logger logger = LoggerFactory.getLogger(NumericPathFunctionTest.class);
// Path: json-path/src/test/java/com/jayway/jsonpath/Configurations.java // public class Configurations { // // public static final Configuration JSON_ORG_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JsonOrgMappingProvider()) // .jsonProvider(new JsonOrgJsonProvider()) // .build(); // // public static final Configuration GSON_CONFIGURATION = Configuration // .builder() // .mappingProvider(new GsonMappingProvider()) // .jsonProvider(new GsonJsonProvider()) // .build(); // // public static final Configuration JACKSON_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JacksonMappingProvider()) // .jsonProvider(new JacksonJsonProvider()) // .build(); // // public static final Configuration JACKSON_JSON_NODE_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JacksonMappingProvider()) // .jsonProvider(new JacksonJsonNodeJsonProvider()) // .build(); // // public static final Configuration JSON_SMART_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JsonSmartMappingProvider()) // .jsonProvider(new JsonSmartJsonProvider()) // .build(); // // public static final Configuration JAKARTA_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JakartaMappingProvider()) // .jsonProvider(new JakartaJsonProvider()) // .build(); // // public static Iterable<Configuration> configurations() { // return Arrays.asList( // JSON_SMART_CONFIGURATION // ,GSON_CONFIGURATION // ,JACKSON_CONFIGURATION // ,JACKSON_JSON_NODE_CONFIGURATION // ,JSON_ORG_CONFIGURATION // ,JAKARTA_CONFIGURATION // ); // } // // public static Iterable<Configuration> objectMappingConfigurations() { // return Arrays.asList( // GSON_CONFIGURATION // ,JACKSON_CONFIGURATION // ,JACKSON_JSON_NODE_CONFIGURATION // ,JAKARTA_CONFIGURATION // ); // } // } // // Path: json-path/src/main/java/com/jayway/jsonpath/JsonPath.java // public static ParseContext using(Configuration configuration) { // return new ParseContextImpl(configuration); // } // Path: json-path/src/test/java/com/jayway/jsonpath/internal/function/NestedFunctionTest.java import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.Configurations; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.jayway.jsonpath.JsonPath.using; import static org.junit.Assert.assertTrue; package com.jayway.jsonpath.internal.function; /** * Created by [email protected] on 12/10/15. */ @RunWith(Parameterized.class) public class NestedFunctionTest extends BaseFunctionTest { private static final Logger logger = LoggerFactory.getLogger(NumericPathFunctionTest.class);
private Configuration conf = Configurations.GSON_CONFIGURATION;
json-path/JsonPath
json-path/src/test/java/com/jayway/jsonpath/internal/function/NestedFunctionTest.java
// Path: json-path/src/test/java/com/jayway/jsonpath/Configurations.java // public class Configurations { // // public static final Configuration JSON_ORG_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JsonOrgMappingProvider()) // .jsonProvider(new JsonOrgJsonProvider()) // .build(); // // public static final Configuration GSON_CONFIGURATION = Configuration // .builder() // .mappingProvider(new GsonMappingProvider()) // .jsonProvider(new GsonJsonProvider()) // .build(); // // public static final Configuration JACKSON_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JacksonMappingProvider()) // .jsonProvider(new JacksonJsonProvider()) // .build(); // // public static final Configuration JACKSON_JSON_NODE_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JacksonMappingProvider()) // .jsonProvider(new JacksonJsonNodeJsonProvider()) // .build(); // // public static final Configuration JSON_SMART_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JsonSmartMappingProvider()) // .jsonProvider(new JsonSmartJsonProvider()) // .build(); // // public static final Configuration JAKARTA_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JakartaMappingProvider()) // .jsonProvider(new JakartaJsonProvider()) // .build(); // // public static Iterable<Configuration> configurations() { // return Arrays.asList( // JSON_SMART_CONFIGURATION // ,GSON_CONFIGURATION // ,JACKSON_CONFIGURATION // ,JACKSON_JSON_NODE_CONFIGURATION // ,JSON_ORG_CONFIGURATION // ,JAKARTA_CONFIGURATION // ); // } // // public static Iterable<Configuration> objectMappingConfigurations() { // return Arrays.asList( // GSON_CONFIGURATION // ,JACKSON_CONFIGURATION // ,JACKSON_JSON_NODE_CONFIGURATION // ,JAKARTA_CONFIGURATION // ); // } // } // // Path: json-path/src/main/java/com/jayway/jsonpath/JsonPath.java // public static ParseContext using(Configuration configuration) { // return new ParseContextImpl(configuration); // }
import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.Configurations; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.jayway.jsonpath.JsonPath.using; import static org.junit.Assert.assertTrue;
public void testStringConcat() { verifyTextFunction(conf, "$.text.concat()", "abcdef"); } @Test public void testStringAndNumberConcat() { verifyTextAndNumberFunction(conf, "$.concat($.text[0], $.numbers[0])", "a1"); } @Test public void testStringConcatWithJSONParameter() { verifyTextFunction(conf, "$.text.concat(\"-\", \"ghijk\")", "abcdef-ghijk"); } @Test public void testAppendNumber() { verifyMathFunction(conf, "$.numbers.append(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 0).avg()", 10.0); } /** * Aggregation function should ignore text values */ @Test public void testAppendTextAndNumberThenSum() { verifyMathFunction(conf, "$.numbers.append(\"0\", \"11\").sum()", 55.0); } @Test public void testErrantCloseBraceNegative() { try {
// Path: json-path/src/test/java/com/jayway/jsonpath/Configurations.java // public class Configurations { // // public static final Configuration JSON_ORG_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JsonOrgMappingProvider()) // .jsonProvider(new JsonOrgJsonProvider()) // .build(); // // public static final Configuration GSON_CONFIGURATION = Configuration // .builder() // .mappingProvider(new GsonMappingProvider()) // .jsonProvider(new GsonJsonProvider()) // .build(); // // public static final Configuration JACKSON_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JacksonMappingProvider()) // .jsonProvider(new JacksonJsonProvider()) // .build(); // // public static final Configuration JACKSON_JSON_NODE_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JacksonMappingProvider()) // .jsonProvider(new JacksonJsonNodeJsonProvider()) // .build(); // // public static final Configuration JSON_SMART_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JsonSmartMappingProvider()) // .jsonProvider(new JsonSmartJsonProvider()) // .build(); // // public static final Configuration JAKARTA_CONFIGURATION = Configuration // .builder() // .mappingProvider(new JakartaMappingProvider()) // .jsonProvider(new JakartaJsonProvider()) // .build(); // // public static Iterable<Configuration> configurations() { // return Arrays.asList( // JSON_SMART_CONFIGURATION // ,GSON_CONFIGURATION // ,JACKSON_CONFIGURATION // ,JACKSON_JSON_NODE_CONFIGURATION // ,JSON_ORG_CONFIGURATION // ,JAKARTA_CONFIGURATION // ); // } // // public static Iterable<Configuration> objectMappingConfigurations() { // return Arrays.asList( // GSON_CONFIGURATION // ,JACKSON_CONFIGURATION // ,JACKSON_JSON_NODE_CONFIGURATION // ,JAKARTA_CONFIGURATION // ); // } // } // // Path: json-path/src/main/java/com/jayway/jsonpath/JsonPath.java // public static ParseContext using(Configuration configuration) { // return new ParseContextImpl(configuration); // } // Path: json-path/src/test/java/com/jayway/jsonpath/internal/function/NestedFunctionTest.java import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.Configurations; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.jayway.jsonpath.JsonPath.using; import static org.junit.Assert.assertTrue; public void testStringConcat() { verifyTextFunction(conf, "$.text.concat()", "abcdef"); } @Test public void testStringAndNumberConcat() { verifyTextAndNumberFunction(conf, "$.concat($.text[0], $.numbers[0])", "a1"); } @Test public void testStringConcatWithJSONParameter() { verifyTextFunction(conf, "$.text.concat(\"-\", \"ghijk\")", "abcdef-ghijk"); } @Test public void testAppendNumber() { verifyMathFunction(conf, "$.numbers.append(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 0).avg()", 10.0); } /** * Aggregation function should ignore text values */ @Test public void testAppendTextAndNumberThenSum() { verifyMathFunction(conf, "$.numbers.append(\"0\", \"11\").sum()", 55.0); } @Test public void testErrantCloseBraceNegative() { try {
using(conf).parse(this.NUMBER_SERIES).read("$.numbers.append(0, 1, 2}).avg()");
json-path/JsonPath
json-path/src/test/java/com/jayway/jsonpath/InlineFilterTest.java
// Path: json-path/src/main/java/com/jayway/jsonpath/JsonPath.java // public static ParseContext using(Configuration configuration) { // return new ParseContextImpl(configuration); // }
import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.ArrayList; import java.util.List; import static com.jayway.jsonpath.JsonPath.using; import static com.jayway.jsonpath.TestUtils.assertHasNoResults; import static com.jayway.jsonpath.TestUtils.assertHasOneResult; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat;
package com.jayway.jsonpath; @RunWith(Parameterized.class) public class InlineFilterTest extends BaseTest { private static int bookCount = 4; private Configuration conf = Configurations.GSON_CONFIGURATION; public InlineFilterTest(Configuration conf) { this.conf = conf; } @Parameterized.Parameters public static Iterable<Configuration> configurations() { return Configurations.configurations(); } @Test public void root_context_can_be_referred_in_predicate() {
// Path: json-path/src/main/java/com/jayway/jsonpath/JsonPath.java // public static ParseContext using(Configuration configuration) { // return new ParseContextImpl(configuration); // } // Path: json-path/src/test/java/com/jayway/jsonpath/InlineFilterTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.ArrayList; import java.util.List; import static com.jayway.jsonpath.JsonPath.using; import static com.jayway.jsonpath.TestUtils.assertHasNoResults; import static com.jayway.jsonpath.TestUtils.assertHasOneResult; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; package com.jayway.jsonpath; @RunWith(Parameterized.class) public class InlineFilterTest extends BaseTest { private static int bookCount = 4; private Configuration conf = Configurations.GSON_CONFIGURATION; public InlineFilterTest(Configuration conf) { this.conf = conf; } @Parameterized.Parameters public static Iterable<Configuration> configurations() { return Configurations.configurations(); } @Test public void root_context_can_be_referred_in_predicate() {
List<Double> prices = using(conf).parse(JSON_DOCUMENT).read("store.book[?(@.display-price <= $.max-price)].display-price", List.class);
json-path/JsonPath
json-path/src/test/java/com/jayway/jsonpath/TestSuppressExceptions.java
// Path: json-path/src/main/java/com/jayway/jsonpath/spi/json/JacksonJsonProvider.java // public class JacksonJsonProvider extends AbstractJsonProvider { // // private static final ObjectMapper defaultObjectMapper = new ObjectMapper(); // private static final ObjectReader defaultObjectReader = defaultObjectMapper.reader().forType(Object.class); // // protected ObjectMapper objectMapper; // protected ObjectReader objectReader; // // public ObjectMapper getObjectMapper() { // return objectMapper; // } // // /** // * Initialize the JacksonProvider with the default ObjectMapper and ObjectReader // */ // public JacksonJsonProvider() { // this(defaultObjectMapper, defaultObjectReader); // } // // /** // * Initialize the JacksonProvider with a custom ObjectMapper. // * @param objectMapper the ObjectMapper to use // */ // public JacksonJsonProvider(ObjectMapper objectMapper) { // this(objectMapper, objectMapper.reader().forType(Object.class)); // } // // /** // * Initialize the JacksonProvider with a custom ObjectMapper and ObjectReader. // * @param objectMapper the ObjectMapper to use // * @param objectReader the ObjectReader to use // */ // public JacksonJsonProvider(ObjectMapper objectMapper, ObjectReader objectReader) { // this.objectMapper = objectMapper; // this.objectReader = objectReader; // } // // @Override // public Object parse(String json) throws InvalidJsonException { // try { // return objectReader.readValue(json); // } catch (IOException e) { // throw new InvalidJsonException(e, json); // } // } // // @Override // public Object parse(byte[] json) // throws InvalidJsonException { // try { // return objectReader.readValue(json); // } catch (IOException e) { // throw new InvalidJsonException(e, new String(json, StandardCharsets.UTF_8)); // } // } // // @Override // public Object parse(InputStream jsonStream, String charset) throws InvalidJsonException { // try { // return objectReader.readValue(new InputStreamReader(jsonStream, charset)); // } catch (IOException e) { // throw new InvalidJsonException(e); // } // } // // @Override // public String toJson(Object obj) { // StringWriter writer = new StringWriter(); // try { // JsonGenerator generator = objectMapper.getFactory().createGenerator(writer); // objectMapper.writeValue(generator, obj); // writer.flush(); // writer.close(); // generator.close(); // return writer.getBuffer().toString(); // } catch (IOException e) { // throw new InvalidJsonException(e); // } // } // // @Override // public List<Object> createArray() { // return new LinkedList<Object>(); // } // // @Override // public Object createMap() { // return new LinkedHashMap<String, Object>(); // } // }
import com.jayway.jsonpath.spi.json.JacksonJsonProvider; import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; import org.assertj.core.api.Assertions; import org.junit.Test; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertNull;
package com.jayway.jsonpath; public class TestSuppressExceptions { @Test public void testSuppressExceptionsIsRespected() { ParseContext parseContext = JsonPath.using(
// Path: json-path/src/main/java/com/jayway/jsonpath/spi/json/JacksonJsonProvider.java // public class JacksonJsonProvider extends AbstractJsonProvider { // // private static final ObjectMapper defaultObjectMapper = new ObjectMapper(); // private static final ObjectReader defaultObjectReader = defaultObjectMapper.reader().forType(Object.class); // // protected ObjectMapper objectMapper; // protected ObjectReader objectReader; // // public ObjectMapper getObjectMapper() { // return objectMapper; // } // // /** // * Initialize the JacksonProvider with the default ObjectMapper and ObjectReader // */ // public JacksonJsonProvider() { // this(defaultObjectMapper, defaultObjectReader); // } // // /** // * Initialize the JacksonProvider with a custom ObjectMapper. // * @param objectMapper the ObjectMapper to use // */ // public JacksonJsonProvider(ObjectMapper objectMapper) { // this(objectMapper, objectMapper.reader().forType(Object.class)); // } // // /** // * Initialize the JacksonProvider with a custom ObjectMapper and ObjectReader. // * @param objectMapper the ObjectMapper to use // * @param objectReader the ObjectReader to use // */ // public JacksonJsonProvider(ObjectMapper objectMapper, ObjectReader objectReader) { // this.objectMapper = objectMapper; // this.objectReader = objectReader; // } // // @Override // public Object parse(String json) throws InvalidJsonException { // try { // return objectReader.readValue(json); // } catch (IOException e) { // throw new InvalidJsonException(e, json); // } // } // // @Override // public Object parse(byte[] json) // throws InvalidJsonException { // try { // return objectReader.readValue(json); // } catch (IOException e) { // throw new InvalidJsonException(e, new String(json, StandardCharsets.UTF_8)); // } // } // // @Override // public Object parse(InputStream jsonStream, String charset) throws InvalidJsonException { // try { // return objectReader.readValue(new InputStreamReader(jsonStream, charset)); // } catch (IOException e) { // throw new InvalidJsonException(e); // } // } // // @Override // public String toJson(Object obj) { // StringWriter writer = new StringWriter(); // try { // JsonGenerator generator = objectMapper.getFactory().createGenerator(writer); // objectMapper.writeValue(generator, obj); // writer.flush(); // writer.close(); // generator.close(); // return writer.getBuffer().toString(); // } catch (IOException e) { // throw new InvalidJsonException(e); // } // } // // @Override // public List<Object> createArray() { // return new LinkedList<Object>(); // } // // @Override // public Object createMap() { // return new LinkedHashMap<String, Object>(); // } // } // Path: json-path/src/test/java/com/jayway/jsonpath/TestSuppressExceptions.java import com.jayway.jsonpath.spi.json.JacksonJsonProvider; import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider; import org.assertj.core.api.Assertions; import org.junit.Test; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertNull; package com.jayway.jsonpath; public class TestSuppressExceptions { @Test public void testSuppressExceptionsIsRespected() { ParseContext parseContext = JsonPath.using(
new Configuration.ConfigurationBuilder().jsonProvider(new JacksonJsonProvider())
json-path/JsonPath
json-path/src/test/java/com/jayway/jsonpath/internal/function/BaseFunctionTest.java
// Path: json-path/src/main/java/com/jayway/jsonpath/JsonPath.java // public static ParseContext using(Configuration configuration) { // return new ParseContextImpl(configuration); // }
import com.jayway.jsonpath.Configuration; import java.io.IOException; import java.util.Scanner; import static com.jayway.jsonpath.JsonPath.using; import static org.assertj.core.api.Assertions.assertThat;
package com.jayway.jsonpath.internal.function; /** * Created by mattg on 6/27/15. */ public class BaseFunctionTest { protected static final String NUMBER_SERIES = "{\"empty\": [], \"numbers\" : [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}"; protected static final String TEXT_SERIES = "{\"urls\": [\"http://api.worldbank.org/countries/all/?format=json\", \"http://api.worldbank.org/countries/all/?format=json\"], \"text\" : [ \"a\", \"b\", \"c\", \"d\", \"e\", \"f\" ]}"; protected static final String TEXT_AND_NUMBER_SERIES = "{\"text\" : [ \"a\", \"b\", \"c\", \"d\", \"e\", \"f\" ], \"numbers\" : [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}"; /** * Verify the function returns the correct result based on the input expectedValue * * @param pathExpr * The path expression to execute * * @param json * The json document (actual content) to parse * * @param expectedValue * The expected value to be returned from the test */ protected void verifyFunction(Configuration conf, String pathExpr, String json, Object expectedValue) {
// Path: json-path/src/main/java/com/jayway/jsonpath/JsonPath.java // public static ParseContext using(Configuration configuration) { // return new ParseContextImpl(configuration); // } // Path: json-path/src/test/java/com/jayway/jsonpath/internal/function/BaseFunctionTest.java import com.jayway.jsonpath.Configuration; import java.io.IOException; import java.util.Scanner; import static com.jayway.jsonpath.JsonPath.using; import static org.assertj.core.api.Assertions.assertThat; package com.jayway.jsonpath.internal.function; /** * Created by mattg on 6/27/15. */ public class BaseFunctionTest { protected static final String NUMBER_SERIES = "{\"empty\": [], \"numbers\" : [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}"; protected static final String TEXT_SERIES = "{\"urls\": [\"http://api.worldbank.org/countries/all/?format=json\", \"http://api.worldbank.org/countries/all/?format=json\"], \"text\" : [ \"a\", \"b\", \"c\", \"d\", \"e\", \"f\" ]}"; protected static final String TEXT_AND_NUMBER_SERIES = "{\"text\" : [ \"a\", \"b\", \"c\", \"d\", \"e\", \"f\" ], \"numbers\" : [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}"; /** * Verify the function returns the correct result based on the input expectedValue * * @param pathExpr * The path expression to execute * * @param json * The json document (actual content) to parse * * @param expectedValue * The expected value to be returned from the test */ protected void verifyFunction(Configuration conf, String pathExpr, String json, Object expectedValue) {
Object result = using(conf).parse(json).read(pathExpr);
json-path/JsonPath
json-path/src/main/java/com/jayway/jsonpath/internal/ParseContextImpl.java
// Path: json-path/src/main/java/com/jayway/jsonpath/ParseContext.java // public interface ParseContext { // // DocumentContext parse(String json); // // DocumentContext parse(Object json); // // DocumentContext parse(InputStream json); // // DocumentContext parse(InputStream json, String charset); // // DocumentContext parse(File json) throws IOException; // // DocumentContext parseUtf8(byte[] json); // // @Deprecated // DocumentContext parse(URL json) throws IOException; // } // // Path: json-path/src/main/java/com/jayway/jsonpath/internal/Utils.java // public static <T extends CharSequence> T notEmpty(T chars, String message) { // if (chars == null || chars.length() == 0) { // throw new IllegalArgumentException(message); // } // return chars; // } // // Path: json-path/src/main/java/com/jayway/jsonpath/internal/Utils.java // public static <T> T notNull(T object, String message) { // if (object == null) { // throw new IllegalArgumentException(message); // } // return object; // }
import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.ParseContext; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import static com.jayway.jsonpath.internal.Utils.notEmpty; import static com.jayway.jsonpath.internal.Utils.notNull;
package com.jayway.jsonpath.internal; public class ParseContextImpl implements ParseContext { private final Configuration configuration; public ParseContextImpl() { this(Configuration.defaultConfiguration()); } public ParseContextImpl(Configuration configuration) { this.configuration = configuration; } @Override public DocumentContext parse(Object json) {
// Path: json-path/src/main/java/com/jayway/jsonpath/ParseContext.java // public interface ParseContext { // // DocumentContext parse(String json); // // DocumentContext parse(Object json); // // DocumentContext parse(InputStream json); // // DocumentContext parse(InputStream json, String charset); // // DocumentContext parse(File json) throws IOException; // // DocumentContext parseUtf8(byte[] json); // // @Deprecated // DocumentContext parse(URL json) throws IOException; // } // // Path: json-path/src/main/java/com/jayway/jsonpath/internal/Utils.java // public static <T extends CharSequence> T notEmpty(T chars, String message) { // if (chars == null || chars.length() == 0) { // throw new IllegalArgumentException(message); // } // return chars; // } // // Path: json-path/src/main/java/com/jayway/jsonpath/internal/Utils.java // public static <T> T notNull(T object, String message) { // if (object == null) { // throw new IllegalArgumentException(message); // } // return object; // } // Path: json-path/src/main/java/com/jayway/jsonpath/internal/ParseContextImpl.java import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.ParseContext; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import static com.jayway.jsonpath.internal.Utils.notEmpty; import static com.jayway.jsonpath.internal.Utils.notNull; package com.jayway.jsonpath.internal; public class ParseContextImpl implements ParseContext { private final Configuration configuration; public ParseContextImpl() { this(Configuration.defaultConfiguration()); } public ParseContextImpl(Configuration configuration) { this.configuration = configuration; } @Override public DocumentContext parse(Object json) {
notNull(json, "json object can not be null");
json-path/JsonPath
json-path/src/main/java/com/jayway/jsonpath/internal/ParseContextImpl.java
// Path: json-path/src/main/java/com/jayway/jsonpath/ParseContext.java // public interface ParseContext { // // DocumentContext parse(String json); // // DocumentContext parse(Object json); // // DocumentContext parse(InputStream json); // // DocumentContext parse(InputStream json, String charset); // // DocumentContext parse(File json) throws IOException; // // DocumentContext parseUtf8(byte[] json); // // @Deprecated // DocumentContext parse(URL json) throws IOException; // } // // Path: json-path/src/main/java/com/jayway/jsonpath/internal/Utils.java // public static <T extends CharSequence> T notEmpty(T chars, String message) { // if (chars == null || chars.length() == 0) { // throw new IllegalArgumentException(message); // } // return chars; // } // // Path: json-path/src/main/java/com/jayway/jsonpath/internal/Utils.java // public static <T> T notNull(T object, String message) { // if (object == null) { // throw new IllegalArgumentException(message); // } // return object; // }
import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.ParseContext; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import static com.jayway.jsonpath.internal.Utils.notEmpty; import static com.jayway.jsonpath.internal.Utils.notNull;
package com.jayway.jsonpath.internal; public class ParseContextImpl implements ParseContext { private final Configuration configuration; public ParseContextImpl() { this(Configuration.defaultConfiguration()); } public ParseContextImpl(Configuration configuration) { this.configuration = configuration; } @Override public DocumentContext parse(Object json) { notNull(json, "json object can not be null"); return new JsonContext(json, configuration); } @Override public DocumentContext parse(String json) {
// Path: json-path/src/main/java/com/jayway/jsonpath/ParseContext.java // public interface ParseContext { // // DocumentContext parse(String json); // // DocumentContext parse(Object json); // // DocumentContext parse(InputStream json); // // DocumentContext parse(InputStream json, String charset); // // DocumentContext parse(File json) throws IOException; // // DocumentContext parseUtf8(byte[] json); // // @Deprecated // DocumentContext parse(URL json) throws IOException; // } // // Path: json-path/src/main/java/com/jayway/jsonpath/internal/Utils.java // public static <T extends CharSequence> T notEmpty(T chars, String message) { // if (chars == null || chars.length() == 0) { // throw new IllegalArgumentException(message); // } // return chars; // } // // Path: json-path/src/main/java/com/jayway/jsonpath/internal/Utils.java // public static <T> T notNull(T object, String message) { // if (object == null) { // throw new IllegalArgumentException(message); // } // return object; // } // Path: json-path/src/main/java/com/jayway/jsonpath/internal/ParseContextImpl.java import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.ParseContext; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import static com.jayway.jsonpath.internal.Utils.notEmpty; import static com.jayway.jsonpath.internal.Utils.notNull; package com.jayway.jsonpath.internal; public class ParseContextImpl implements ParseContext { private final Configuration configuration; public ParseContextImpl() { this(Configuration.defaultConfiguration()); } public ParseContextImpl(Configuration configuration) { this.configuration = configuration; } @Override public DocumentContext parse(Object json) { notNull(json, "json object can not be null"); return new JsonContext(json, configuration); } @Override public DocumentContext parse(String json) {
notEmpty(json, "json string can not be null or empty");
json-path/JsonPath
json-path/src/test/java/com/jayway/jsonpath/JakartaJsonProviderTest.java
// Path: json-path/src/main/java/com/jayway/jsonpath/JsonPath.java // public static DocumentContext parse(Object json) { // return new ParseContextImpl().parse(json); // } // // Path: json-path/src/main/java/com/jayway/jsonpath/JsonPath.java // public static ParseContext using(Configuration configuration) { // return new ParseContextImpl(configuration); // }
import jakarta.json.JsonObject; import jakarta.json.JsonString; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import static com.jayway.jsonpath.JsonPath.parse; import static com.jayway.jsonpath.JsonPath.using; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Collections.emptyMap; import static org.assertj.core.api.Assertions.assertThat;
package com.jayway.jsonpath; public class JakartaJsonProviderTest extends BaseTest { private static final Map<String, Object> EMPTY_MAP = emptyMap(); @Test public void an_object_can_be_read() {
// Path: json-path/src/main/java/com/jayway/jsonpath/JsonPath.java // public static DocumentContext parse(Object json) { // return new ParseContextImpl().parse(json); // } // // Path: json-path/src/main/java/com/jayway/jsonpath/JsonPath.java // public static ParseContext using(Configuration configuration) { // return new ParseContextImpl(configuration); // } // Path: json-path/src/test/java/com/jayway/jsonpath/JakartaJsonProviderTest.java import jakarta.json.JsonObject; import jakarta.json.JsonString; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import static com.jayway.jsonpath.JsonPath.parse; import static com.jayway.jsonpath.JsonPath.using; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Collections.emptyMap; import static org.assertj.core.api.Assertions.assertThat; package com.jayway.jsonpath; public class JakartaJsonProviderTest extends BaseTest { private static final Map<String, Object> EMPTY_MAP = emptyMap(); @Test public void an_object_can_be_read() {
JsonObject book = using(JAKARTA_JSON_CONFIGURATION)
json-path/JsonPath
json-path/src/test/java/com/jayway/jsonpath/JakartaJsonProviderTest.java
// Path: json-path/src/main/java/com/jayway/jsonpath/JsonPath.java // public static DocumentContext parse(Object json) { // return new ParseContextImpl().parse(json); // } // // Path: json-path/src/main/java/com/jayway/jsonpath/JsonPath.java // public static ParseContext using(Configuration configuration) { // return new ParseContextImpl(configuration); // }
import jakarta.json.JsonObject; import jakarta.json.JsonString; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import static com.jayway.jsonpath.JsonPath.parse; import static com.jayway.jsonpath.JsonPath.using; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Collections.emptyMap; import static org.assertj.core.api.Assertions.assertThat;
package com.jayway.jsonpath; public class JakartaJsonProviderTest extends BaseTest { private static final Map<String, Object> EMPTY_MAP = emptyMap(); @Test public void an_object_can_be_read() { JsonObject book = using(JAKARTA_JSON_CONFIGURATION)
// Path: json-path/src/main/java/com/jayway/jsonpath/JsonPath.java // public static DocumentContext parse(Object json) { // return new ParseContextImpl().parse(json); // } // // Path: json-path/src/main/java/com/jayway/jsonpath/JsonPath.java // public static ParseContext using(Configuration configuration) { // return new ParseContextImpl(configuration); // } // Path: json-path/src/test/java/com/jayway/jsonpath/JakartaJsonProviderTest.java import jakarta.json.JsonObject; import jakarta.json.JsonString; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import static com.jayway.jsonpath.JsonPath.parse; import static com.jayway.jsonpath.JsonPath.using; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Collections.emptyMap; import static org.assertj.core.api.Assertions.assertThat; package com.jayway.jsonpath; public class JakartaJsonProviderTest extends BaseTest { private static final Map<String, Object> EMPTY_MAP = emptyMap(); @Test public void an_object_can_be_read() { JsonObject book = using(JAKARTA_JSON_CONFIGURATION)
.parse(JSON_DOCUMENT)
json-path/JsonPath
json-path/src/main/java/com/jayway/jsonpath/spi/cache/CacheProvider.java
// Path: json-path/src/main/java/com/jayway/jsonpath/internal/Utils.java // public static <T> T notNull(T object, String message) { // if (object == null) { // throw new IllegalArgumentException(message); // } // return object; // }
import com.jayway.jsonpath.JsonPathException; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import static com.jayway.jsonpath.internal.Utils.notNull;
package com.jayway.jsonpath.spi.cache; public class CacheProvider { private static final AtomicReferenceFieldUpdater<CacheProvider, Cache> UPDATER = AtomicReferenceFieldUpdater.newUpdater(CacheProvider.class, Cache.class, "cache"); private static final CacheProvider instance = new CacheProvider(); private volatile Cache cache; private static class CacheHolder { static final Cache CACHE; static { Cache cache = CacheProvider.instance.cache; // the application is trying to use the cache // and if no external implementation has been registered, // we need to initialise it to the default LRUCache if (cache == null) { cache = getDefaultCache(); // on the off chance that the cache implementation was registered during // initialisation of the holder, this should be respected, so if the // default cache can't be written back, just read the user supplied value again if (!UPDATER.compareAndSet(instance, null, cache)) { cache = CacheProvider.instance.cache; } } CACHE = cache; } } public static void setCache(Cache cache){
// Path: json-path/src/main/java/com/jayway/jsonpath/internal/Utils.java // public static <T> T notNull(T object, String message) { // if (object == null) { // throw new IllegalArgumentException(message); // } // return object; // } // Path: json-path/src/main/java/com/jayway/jsonpath/spi/cache/CacheProvider.java import com.jayway.jsonpath.JsonPathException; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import static com.jayway.jsonpath.internal.Utils.notNull; package com.jayway.jsonpath.spi.cache; public class CacheProvider { private static final AtomicReferenceFieldUpdater<CacheProvider, Cache> UPDATER = AtomicReferenceFieldUpdater.newUpdater(CacheProvider.class, Cache.class, "cache"); private static final CacheProvider instance = new CacheProvider(); private volatile Cache cache; private static class CacheHolder { static final Cache CACHE; static { Cache cache = CacheProvider.instance.cache; // the application is trying to use the cache // and if no external implementation has been registered, // we need to initialise it to the default LRUCache if (cache == null) { cache = getDefaultCache(); // on the off chance that the cache implementation was registered during // initialisation of the holder, this should be respected, so if the // default cache can't be written back, just read the user supplied value again if (!UPDATER.compareAndSet(instance, null, cache)) { cache = CacheProvider.instance.cache; } } CACHE = cache; } } public static void setCache(Cache cache){
notNull(cache, "Cache may not be null");
json-path/JsonPath
json-path/src/test/java/com/jayway/jsonpath/ScientificNotationTest.java
// Path: json-path/src/main/java/com/jayway/jsonpath/JsonPath.java // public static ParseContext using(Configuration configuration) { // return new ParseContextImpl(configuration); // }
import com.google.gson.JsonArray; import org.junit.Test; import java.util.List; import static com.jayway.jsonpath.JsonPath.using; import static org.assertj.core.api.Assertions.assertThat;
package com.jayway.jsonpath; //test for issue: https://github.com/json-path/JsonPath/issues/590 public class ScientificNotationTest extends BaseTest { final String sci_rep_array = "{\"num_array\": [" + "{\"num\":1}," + "{\"num\":-1e-10}," + "{\"num\":0.1e10},"+ "{\"num\":2E-20}," + "{\"num\":-0.2E20}" + " ]}"; @Test public void testScientificNotation() {
// Path: json-path/src/main/java/com/jayway/jsonpath/JsonPath.java // public static ParseContext using(Configuration configuration) { // return new ParseContextImpl(configuration); // } // Path: json-path/src/test/java/com/jayway/jsonpath/ScientificNotationTest.java import com.google.gson.JsonArray; import org.junit.Test; import java.util.List; import static com.jayway.jsonpath.JsonPath.using; import static org.assertj.core.api.Assertions.assertThat; package com.jayway.jsonpath; //test for issue: https://github.com/json-path/JsonPath/issues/590 public class ScientificNotationTest extends BaseTest { final String sci_rep_array = "{\"num_array\": [" + "{\"num\":1}," + "{\"num\":-1e-10}," + "{\"num\":0.1e10},"+ "{\"num\":2E-20}," + "{\"num\":-0.2E20}" + " ]}"; @Test public void testScientificNotation() {
List<JsonArray> result = using(Configuration.defaultConfiguration())
json-path/JsonPath
json-path/src/main/java/com/jayway/jsonpath/internal/path/ArrayPathToken.java
// Path: json-path/src/main/java/com/jayway/jsonpath/PathNotFoundException.java // public class PathNotFoundException extends InvalidPathException { // // public PathNotFoundException() { // } // // public PathNotFoundException(String message) { // super(message); // } // // public PathNotFoundException(String message, Throwable cause) { // super(message, cause); // } // // public PathNotFoundException(Throwable cause) { // super(cause); // } // // @Override // public synchronized Throwable fillInStackTrace() { // return this; // } // }
import com.jayway.jsonpath.InvalidPathException; import com.jayway.jsonpath.Option; import com.jayway.jsonpath.PathNotFoundException; import static java.lang.String.format;
/* * Copyright 2011 the original author or authors. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jayway.jsonpath.internal.path; public abstract class ArrayPathToken extends PathToken { /** * Check if model is non-null and array. * @param currentPath * @param model * @param ctx * @return false if current evaluation call must be skipped, true otherwise * @throws PathNotFoundException if model is null and evaluation must be interrupted * @throws InvalidPathException if model is not an array and evaluation must be interrupted */ protected boolean checkArrayModel(String currentPath, Object model, EvaluationContextImpl ctx) { if (model == null){ if (!isUpstreamDefinite() || ctx.options().contains(Option.SUPPRESS_EXCEPTIONS)) { return false; } else {
// Path: json-path/src/main/java/com/jayway/jsonpath/PathNotFoundException.java // public class PathNotFoundException extends InvalidPathException { // // public PathNotFoundException() { // } // // public PathNotFoundException(String message) { // super(message); // } // // public PathNotFoundException(String message, Throwable cause) { // super(message, cause); // } // // public PathNotFoundException(Throwable cause) { // super(cause); // } // // @Override // public synchronized Throwable fillInStackTrace() { // return this; // } // } // Path: json-path/src/main/java/com/jayway/jsonpath/internal/path/ArrayPathToken.java import com.jayway.jsonpath.InvalidPathException; import com.jayway.jsonpath.Option; import com.jayway.jsonpath.PathNotFoundException; import static java.lang.String.format; /* * Copyright 2011 the original author or authors. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jayway.jsonpath.internal.path; public abstract class ArrayPathToken extends PathToken { /** * Check if model is non-null and array. * @param currentPath * @param model * @param ctx * @return false if current evaluation call must be skipped, true otherwise * @throws PathNotFoundException if model is null and evaluation must be interrupted * @throws InvalidPathException if model is not an array and evaluation must be interrupted */ protected boolean checkArrayModel(String currentPath, Object model, EvaluationContextImpl ctx) { if (model == null){ if (!isUpstreamDefinite() || ctx.options().contains(Option.SUPPRESS_EXCEPTIONS)) { return false; } else {
throw new PathNotFoundException("The path " + currentPath + " is null");
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/http/mime/BodyConverter.java
// Path: library/src/main/java/org/mariotaku/restfu/http/MultiValueMap.java // public final class MultiValueMap<V> extends MultiMap<String, V> { // // public MultiValueMap() { // this(new HashMap<String, List<V>>(), false); // } // // public MultiValueMap(Map<String, List<V>> map) { // this(map, false); // } // // public MultiValueMap(boolean ignoreCase) { // this(null, ignoreCase); // } // // public MultiValueMap(Map<String, List<V>> map, boolean ignoreCase) { // super(map, new StringEquatable(ignoreCase)); // } // // private static class StringEquatable implements Equatable<String> { // private boolean ignoreCase; // // StringEquatable(boolean ignoreCase) { // this.ignoreCase = ignoreCase; // } // // @Override // public boolean equals(String s1, String s2) { // if (s1 == null || s2 == null) { // //noinspection StringEquality // return s1 == s2; // } // if (ignoreCase) { // return s1.equalsIgnoreCase(s2); // } // return s1.equals(s2); // } // } // }
import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.http.MultiValueMap;
package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/4/19. */ public interface BodyConverter { @NotNull
// Path: library/src/main/java/org/mariotaku/restfu/http/MultiValueMap.java // public final class MultiValueMap<V> extends MultiMap<String, V> { // // public MultiValueMap() { // this(new HashMap<String, List<V>>(), false); // } // // public MultiValueMap(Map<String, List<V>> map) { // this(map, false); // } // // public MultiValueMap(boolean ignoreCase) { // this(null, ignoreCase); // } // // public MultiValueMap(Map<String, List<V>> map, boolean ignoreCase) { // super(map, new StringEquatable(ignoreCase)); // } // // private static class StringEquatable implements Equatable<String> { // private boolean ignoreCase; // // StringEquatable(boolean ignoreCase) { // this.ignoreCase = ignoreCase; // } // // @Override // public boolean equals(String s1, String s2) { // if (s1 == null || s2 == null) { // //noinspection StringEquality // return s1 == s2; // } // if (ignoreCase) { // return s1.equalsIgnoreCase(s2); // } // return s1.equals(s2); // } // } // } // Path: library/src/main/java/org/mariotaku/restfu/http/mime/BodyConverter.java import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.http.MultiValueMap; package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/4/19. */ public interface BodyConverter { @NotNull
Body convert(@NotNull MultiValueMap<Body> params, @NotNull String[] args);
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java
// Path: library/src/main/java/org/mariotaku/restfu/http/mime/Body.java // public interface Body extends Closeable { // ContentType contentType(); // // String contentEncoding(); // // long length() throws IOException; // // long writeTo(final OutputStream os) throws IOException; // // InputStream stream() throws IOException; // // void close() throws IOException; // // }
import org.mariotaku.restfu.http.mime.Body; import java.io.Closeable; import java.util.List;
/* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu.http; /** * Created by mariotaku on 15/2/7. */ public abstract class HttpResponse implements Closeable { public abstract int getStatus(); public abstract MultiValueMap<String> getHeaders();
// Path: library/src/main/java/org/mariotaku/restfu/http/mime/Body.java // public interface Body extends Closeable { // ContentType contentType(); // // String contentEncoding(); // // long length() throws IOException; // // long writeTo(final OutputStream os) throws IOException; // // InputStream stream() throws IOException; // // void close() throws IOException; // // } // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java import org.mariotaku.restfu.http.mime.Body; import java.io.Closeable; import java.util.List; /* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu.http; /** * Created by mariotaku on 15/2/7. */ public abstract class HttpResponse implements Closeable { public abstract int getStatus(); public abstract MultiValueMap<String> getHeaders();
public abstract Body getBody();
mariotaku/RestFu
sample/src/main/java/GithubExceptionFactory.java
// Path: library/src/main/java/org/mariotaku/restfu/ExceptionFactory.java // public interface ExceptionFactory<E extends Exception> { // // @NotNull // E newException(@Nullable final Throwable cause, @Nullable final HttpRequest request, // @Nullable final HttpResponse response); // // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.restfu.ExceptionFactory; import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.HttpResponse;
/** * Created by mariotaku on 16/1/17. */ public class GithubExceptionFactory implements ExceptionFactory<GithubException> { @Override @NotNull
// Path: library/src/main/java/org/mariotaku/restfu/ExceptionFactory.java // public interface ExceptionFactory<E extends Exception> { // // @NotNull // E newException(@Nullable final Throwable cause, @Nullable final HttpRequest request, // @Nullable final HttpResponse response); // // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // } // Path: sample/src/main/java/GithubExceptionFactory.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.restfu.ExceptionFactory; import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.HttpResponse; /** * Created by mariotaku on 16/1/17. */ public class GithubExceptionFactory implements ExceptionFactory<GithubException> { @Override @NotNull
public GithubException newException(@Nullable Throwable cause, @Nullable HttpRequest request, @Nullable HttpResponse response) {
mariotaku/RestFu
sample/src/main/java/GithubExceptionFactory.java
// Path: library/src/main/java/org/mariotaku/restfu/ExceptionFactory.java // public interface ExceptionFactory<E extends Exception> { // // @NotNull // E newException(@Nullable final Throwable cause, @Nullable final HttpRequest request, // @Nullable final HttpResponse response); // // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.restfu.ExceptionFactory; import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.HttpResponse;
/** * Created by mariotaku on 16/1/17. */ public class GithubExceptionFactory implements ExceptionFactory<GithubException> { @Override @NotNull
// Path: library/src/main/java/org/mariotaku/restfu/ExceptionFactory.java // public interface ExceptionFactory<E extends Exception> { // // @NotNull // E newException(@Nullable final Throwable cause, @Nullable final HttpRequest request, // @Nullable final HttpResponse response); // // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // } // Path: sample/src/main/java/GithubExceptionFactory.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.restfu.ExceptionFactory; import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.HttpResponse; /** * Created by mariotaku on 16/1/17. */ public class GithubExceptionFactory implements ExceptionFactory<GithubException> { @Override @NotNull
public GithubException newException(@Nullable Throwable cause, @Nullable HttpRequest request, @Nullable HttpResponse response) {
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/RestClient.java
// Path: library/src/main/java/org/mariotaku/restfu/http/Authorization.java // public interface Authorization { // String getHeader(@NotNull Endpoint endpoint, @NotNull RestRequest info); // // boolean hasAuthorization(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/Endpoint.java // public class Endpoint { // // @NotNull // private String url; // // @NotNull // public String getUrl() { // return url; // } // // public Endpoint(@NotNull String url) { // this.url = url; // } // // public static String constructUrl(@NotNull String endpoint, @NotNull RestRequest restRequest) { // return constructUrl(endpoint, restRequest.getPath(), restRequest.getQueries()); // } // // public String construct(String path, MultiValueMap<String> queries) { // return constructUrl(url, path, queries); // } // // public String construct(String path, String[]... queries) { // MultiValueMap<String> map = new MultiValueMap<>(); // for (String[] query : queries) { // if (query.length != 2) throw new IllegalArgumentException(); // map.add(query[0], query[1]); // } // return constructUrl(url, path, map); // } // // public boolean checkEndpoint(String that) { // return that != null && that.startsWith(url); // } // // public static String constructUrl(String endpoint, String path, MultiValueMap<String> queries) { // if (endpoint == null) throw new NullPointerException("Endpoint is null"); // final StringBuilder urlBuilder = new StringBuilder(); // if (endpoint.charAt(endpoint.length() - 1) == '/') { // urlBuilder.append(endpoint.substring(0, endpoint.length() - 1)); // } else { // urlBuilder.append(endpoint); // } // if (path != null) { // if (path.charAt(0) != '/') { // urlBuilder.append('/'); // } // urlBuilder.append(path); // } // return constructUrl(urlBuilder.toString(), queries); // } // // public static String constructUrl(String url, String[]... queries) { // MultiValueMap<String> map = new MultiValueMap<>(); // for (String[] query : queries) { // if (query.length != 2) throw new IllegalArgumentException(); // map.add(query[0], query[1]); // } // return constructUrl(url, map); // } // // public static String constructUrl(String url, MultiValueMap<String> queries) { // if (queries == null || queries.isEmpty()) return url; // final StringBuilder urlBuilder = new StringBuilder(url); // urlBuilder.append('?'); // int numAdded = RestFuUtils.append(urlBuilder, queries, Charset.forName("UTF-8")); // if (numAdded == 0) return url; // return urlBuilder.toString(); // } // // } // // Path: library/src/main/java/org/mariotaku/restfu/http/RestHttpClient.java // public interface RestHttpClient { // // @NotNull HttpCall newCall(@NotNull HttpRequest request); // // void enqueue(@NotNull HttpCall call, @NotNull HttpCallback callback); // // }
import org.mariotaku.restfu.http.Authorization; import org.mariotaku.restfu.http.Endpoint; import org.mariotaku.restfu.http.RestHttpClient;
/* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu; /** * Created by mariotaku on 15/4/19. */ public interface RestClient { Endpoint getEndpoint();
// Path: library/src/main/java/org/mariotaku/restfu/http/Authorization.java // public interface Authorization { // String getHeader(@NotNull Endpoint endpoint, @NotNull RestRequest info); // // boolean hasAuthorization(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/Endpoint.java // public class Endpoint { // // @NotNull // private String url; // // @NotNull // public String getUrl() { // return url; // } // // public Endpoint(@NotNull String url) { // this.url = url; // } // // public static String constructUrl(@NotNull String endpoint, @NotNull RestRequest restRequest) { // return constructUrl(endpoint, restRequest.getPath(), restRequest.getQueries()); // } // // public String construct(String path, MultiValueMap<String> queries) { // return constructUrl(url, path, queries); // } // // public String construct(String path, String[]... queries) { // MultiValueMap<String> map = new MultiValueMap<>(); // for (String[] query : queries) { // if (query.length != 2) throw new IllegalArgumentException(); // map.add(query[0], query[1]); // } // return constructUrl(url, path, map); // } // // public boolean checkEndpoint(String that) { // return that != null && that.startsWith(url); // } // // public static String constructUrl(String endpoint, String path, MultiValueMap<String> queries) { // if (endpoint == null) throw new NullPointerException("Endpoint is null"); // final StringBuilder urlBuilder = new StringBuilder(); // if (endpoint.charAt(endpoint.length() - 1) == '/') { // urlBuilder.append(endpoint.substring(0, endpoint.length() - 1)); // } else { // urlBuilder.append(endpoint); // } // if (path != null) { // if (path.charAt(0) != '/') { // urlBuilder.append('/'); // } // urlBuilder.append(path); // } // return constructUrl(urlBuilder.toString(), queries); // } // // public static String constructUrl(String url, String[]... queries) { // MultiValueMap<String> map = new MultiValueMap<>(); // for (String[] query : queries) { // if (query.length != 2) throw new IllegalArgumentException(); // map.add(query[0], query[1]); // } // return constructUrl(url, map); // } // // public static String constructUrl(String url, MultiValueMap<String> queries) { // if (queries == null || queries.isEmpty()) return url; // final StringBuilder urlBuilder = new StringBuilder(url); // urlBuilder.append('?'); // int numAdded = RestFuUtils.append(urlBuilder, queries, Charset.forName("UTF-8")); // if (numAdded == 0) return url; // return urlBuilder.toString(); // } // // } // // Path: library/src/main/java/org/mariotaku/restfu/http/RestHttpClient.java // public interface RestHttpClient { // // @NotNull HttpCall newCall(@NotNull HttpRequest request); // // void enqueue(@NotNull HttpCall call, @NotNull HttpCallback callback); // // } // Path: library/src/main/java/org/mariotaku/restfu/RestClient.java import org.mariotaku.restfu.http.Authorization; import org.mariotaku.restfu.http.Endpoint; import org.mariotaku.restfu.http.RestHttpClient; /* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu; /** * Created by mariotaku on 15/4/19. */ public interface RestClient { Endpoint getEndpoint();
RestHttpClient getRestClient();
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/RestClient.java
// Path: library/src/main/java/org/mariotaku/restfu/http/Authorization.java // public interface Authorization { // String getHeader(@NotNull Endpoint endpoint, @NotNull RestRequest info); // // boolean hasAuthorization(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/Endpoint.java // public class Endpoint { // // @NotNull // private String url; // // @NotNull // public String getUrl() { // return url; // } // // public Endpoint(@NotNull String url) { // this.url = url; // } // // public static String constructUrl(@NotNull String endpoint, @NotNull RestRequest restRequest) { // return constructUrl(endpoint, restRequest.getPath(), restRequest.getQueries()); // } // // public String construct(String path, MultiValueMap<String> queries) { // return constructUrl(url, path, queries); // } // // public String construct(String path, String[]... queries) { // MultiValueMap<String> map = new MultiValueMap<>(); // for (String[] query : queries) { // if (query.length != 2) throw new IllegalArgumentException(); // map.add(query[0], query[1]); // } // return constructUrl(url, path, map); // } // // public boolean checkEndpoint(String that) { // return that != null && that.startsWith(url); // } // // public static String constructUrl(String endpoint, String path, MultiValueMap<String> queries) { // if (endpoint == null) throw new NullPointerException("Endpoint is null"); // final StringBuilder urlBuilder = new StringBuilder(); // if (endpoint.charAt(endpoint.length() - 1) == '/') { // urlBuilder.append(endpoint.substring(0, endpoint.length() - 1)); // } else { // urlBuilder.append(endpoint); // } // if (path != null) { // if (path.charAt(0) != '/') { // urlBuilder.append('/'); // } // urlBuilder.append(path); // } // return constructUrl(urlBuilder.toString(), queries); // } // // public static String constructUrl(String url, String[]... queries) { // MultiValueMap<String> map = new MultiValueMap<>(); // for (String[] query : queries) { // if (query.length != 2) throw new IllegalArgumentException(); // map.add(query[0], query[1]); // } // return constructUrl(url, map); // } // // public static String constructUrl(String url, MultiValueMap<String> queries) { // if (queries == null || queries.isEmpty()) return url; // final StringBuilder urlBuilder = new StringBuilder(url); // urlBuilder.append('?'); // int numAdded = RestFuUtils.append(urlBuilder, queries, Charset.forName("UTF-8")); // if (numAdded == 0) return url; // return urlBuilder.toString(); // } // // } // // Path: library/src/main/java/org/mariotaku/restfu/http/RestHttpClient.java // public interface RestHttpClient { // // @NotNull HttpCall newCall(@NotNull HttpRequest request); // // void enqueue(@NotNull HttpCall call, @NotNull HttpCallback callback); // // }
import org.mariotaku.restfu.http.Authorization; import org.mariotaku.restfu.http.Endpoint; import org.mariotaku.restfu.http.RestHttpClient;
/* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu; /** * Created by mariotaku on 15/4/19. */ public interface RestClient { Endpoint getEndpoint(); RestHttpClient getRestClient();
// Path: library/src/main/java/org/mariotaku/restfu/http/Authorization.java // public interface Authorization { // String getHeader(@NotNull Endpoint endpoint, @NotNull RestRequest info); // // boolean hasAuthorization(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/Endpoint.java // public class Endpoint { // // @NotNull // private String url; // // @NotNull // public String getUrl() { // return url; // } // // public Endpoint(@NotNull String url) { // this.url = url; // } // // public static String constructUrl(@NotNull String endpoint, @NotNull RestRequest restRequest) { // return constructUrl(endpoint, restRequest.getPath(), restRequest.getQueries()); // } // // public String construct(String path, MultiValueMap<String> queries) { // return constructUrl(url, path, queries); // } // // public String construct(String path, String[]... queries) { // MultiValueMap<String> map = new MultiValueMap<>(); // for (String[] query : queries) { // if (query.length != 2) throw new IllegalArgumentException(); // map.add(query[0], query[1]); // } // return constructUrl(url, path, map); // } // // public boolean checkEndpoint(String that) { // return that != null && that.startsWith(url); // } // // public static String constructUrl(String endpoint, String path, MultiValueMap<String> queries) { // if (endpoint == null) throw new NullPointerException("Endpoint is null"); // final StringBuilder urlBuilder = new StringBuilder(); // if (endpoint.charAt(endpoint.length() - 1) == '/') { // urlBuilder.append(endpoint.substring(0, endpoint.length() - 1)); // } else { // urlBuilder.append(endpoint); // } // if (path != null) { // if (path.charAt(0) != '/') { // urlBuilder.append('/'); // } // urlBuilder.append(path); // } // return constructUrl(urlBuilder.toString(), queries); // } // // public static String constructUrl(String url, String[]... queries) { // MultiValueMap<String> map = new MultiValueMap<>(); // for (String[] query : queries) { // if (query.length != 2) throw new IllegalArgumentException(); // map.add(query[0], query[1]); // } // return constructUrl(url, map); // } // // public static String constructUrl(String url, MultiValueMap<String> queries) { // if (queries == null || queries.isEmpty()) return url; // final StringBuilder urlBuilder = new StringBuilder(url); // urlBuilder.append('?'); // int numAdded = RestFuUtils.append(urlBuilder, queries, Charset.forName("UTF-8")); // if (numAdded == 0) return url; // return urlBuilder.toString(); // } // // } // // Path: library/src/main/java/org/mariotaku/restfu/http/RestHttpClient.java // public interface RestHttpClient { // // @NotNull HttpCall newCall(@NotNull HttpRequest request); // // void enqueue(@NotNull HttpCall call, @NotNull HttpCallback callback); // // } // Path: library/src/main/java/org/mariotaku/restfu/RestClient.java import org.mariotaku.restfu.http.Authorization; import org.mariotaku.restfu.http.Endpoint; import org.mariotaku.restfu.http.RestHttpClient; /* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu; /** * Created by mariotaku on 15/4/19. */ public interface RestClient { Endpoint getEndpoint(); RestHttpClient getRestClient();
Authorization getAuthorization();
mariotaku/RestFu
sample/src/main/java/Github.java
// Path: library/src/main/java/org/mariotaku/restfu/callback/RawCallback.java // public interface RawCallback<E extends Exception> extends Callback<HttpResponse, E> { // // }
import org.mariotaku.restfu.annotation.method.GET; import org.mariotaku.restfu.annotation.param.Headers; import org.mariotaku.restfu.annotation.param.KeyValue; import org.mariotaku.restfu.annotation.param.Path; import org.mariotaku.restfu.annotation.param.Queries; import org.mariotaku.restfu.callback.RawCallback; import java.util.List;
/** * Created by mariotaku on 16/1/17. */ public interface Github { @GET("/repos/{owner}/{repo}/contributors") @Queries(@KeyValue(key = "test", value = "ok")) @Headers(@KeyValue(key = "X-Invalid-Character", value = "无效字符")) List<Contributor> contributors(@Path(value = "owner") String owner, @Path(value = "repo") String repo) throws GithubException; @GET("/repos/{owner}/{repo}/contributors") void rawContributors(@Path(value = "owner") String owner, @Path(value = "repo") String repo,
// Path: library/src/main/java/org/mariotaku/restfu/callback/RawCallback.java // public interface RawCallback<E extends Exception> extends Callback<HttpResponse, E> { // // } // Path: sample/src/main/java/Github.java import org.mariotaku.restfu.annotation.method.GET; import org.mariotaku.restfu.annotation.param.Headers; import org.mariotaku.restfu.annotation.param.KeyValue; import org.mariotaku.restfu.annotation.param.Path; import org.mariotaku.restfu.annotation.param.Queries; import org.mariotaku.restfu.callback.RawCallback; import java.util.List; /** * Created by mariotaku on 16/1/17. */ public interface Github { @GET("/repos/{owner}/{repo}/contributors") @Queries(@KeyValue(key = "test", value = "ok")) @Headers(@KeyValue(key = "X-Invalid-Character", value = "无效字符")) List<Contributor> contributors(@Path(value = "owner") String owner, @Path(value = "repo") String repo) throws GithubException; @GET("/repos/{owner}/{repo}/contributors") void rawContributors(@Path(value = "owner") String owner, @Path(value = "repo") String repo,
RawCallback callback) throws GithubException;
mariotaku/RestFu
library/src/test/java/org/mariotaku/restfu/http/mime/NullConverterFactory.java
// Path: library/src/main/java/org/mariotaku/restfu/RestConverter.java // public interface RestConverter<F, T, E extends Exception> { // // @NotNull // T convert(@NotNull F from) throws ConvertException, IOException, E; // // interface Factory<E extends Exception> { // // @NotNull // RestConverter<HttpResponse, ?, E> forResponse(@NotNull Type toType) throws ConvertException; // // @NotNull // RestConverter<?, Body, E> forRequest(@NotNull Type fromType) throws ConvertException; // } // // abstract class SimpleFactory<E extends Exception> implements Factory<E> { // @NotNull // @Override // public RestConverter<?, Body, E> forRequest(@NotNull Type fromType) throws ConvertException { // if (!SimpleBody.supports(fromType)) throw new UnsupportedTypeException(fromType); // return new SimpleBodyConverter<>(fromType); // } // // public static class SimpleBodyConverter<E extends Exception> implements RestConverter<Object, Body, E> { // private final Type fromType; // // public SimpleBodyConverter(Type fromType) { // this.fromType = fromType; // } // // @NotNull // @Override // public Body convert(@NotNull Object from) throws ConvertException, IOException { // return SimpleBody.wrap(from); // } // } // } // // class ConvertException extends Exception { // public ConvertException() { // super(); // } // // public ConvertException(String message) { // super(message); // } // // public ConvertException(String message, Throwable cause) { // super(message, cause); // } // // public ConvertException(Throwable cause) { // super(cause); // } // // protected ConvertException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // class UnsupportedTypeException extends RuntimeException { // public UnsupportedTypeException(Type type) { // super(type.toString()); // } // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // }
import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.RestConverter; import org.mariotaku.restfu.http.HttpResponse; import java.lang.reflect.Type;
package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/3/25. */ class NullConverterFactory<E extends Exception> extends RestConverter.SimpleFactory<E> { @NotNull @Override
// Path: library/src/main/java/org/mariotaku/restfu/RestConverter.java // public interface RestConverter<F, T, E extends Exception> { // // @NotNull // T convert(@NotNull F from) throws ConvertException, IOException, E; // // interface Factory<E extends Exception> { // // @NotNull // RestConverter<HttpResponse, ?, E> forResponse(@NotNull Type toType) throws ConvertException; // // @NotNull // RestConverter<?, Body, E> forRequest(@NotNull Type fromType) throws ConvertException; // } // // abstract class SimpleFactory<E extends Exception> implements Factory<E> { // @NotNull // @Override // public RestConverter<?, Body, E> forRequest(@NotNull Type fromType) throws ConvertException { // if (!SimpleBody.supports(fromType)) throw new UnsupportedTypeException(fromType); // return new SimpleBodyConverter<>(fromType); // } // // public static class SimpleBodyConverter<E extends Exception> implements RestConverter<Object, Body, E> { // private final Type fromType; // // public SimpleBodyConverter(Type fromType) { // this.fromType = fromType; // } // // @NotNull // @Override // public Body convert(@NotNull Object from) throws ConvertException, IOException { // return SimpleBody.wrap(from); // } // } // } // // class ConvertException extends Exception { // public ConvertException() { // super(); // } // // public ConvertException(String message) { // super(message); // } // // public ConvertException(String message, Throwable cause) { // super(message, cause); // } // // public ConvertException(Throwable cause) { // super(cause); // } // // protected ConvertException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // class UnsupportedTypeException extends RuntimeException { // public UnsupportedTypeException(Type type) { // super(type.toString()); // } // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // } // Path: library/src/test/java/org/mariotaku/restfu/http/mime/NullConverterFactory.java import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.RestConverter; import org.mariotaku.restfu.http.HttpResponse; import java.lang.reflect.Type; package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/3/25. */ class NullConverterFactory<E extends Exception> extends RestConverter.SimpleFactory<E> { @NotNull @Override
public RestConverter<HttpResponse, ?, E> forResponse(@NotNull Type toType) {
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/http/BodyType.java
// Path: library/src/main/java/org/mariotaku/restfu/http/mime/BodyConverter.java // public interface BodyConverter { // @NotNull // Body convert(@NotNull MultiValueMap<Body> params, @NotNull String[] args); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/mime/DefaultBodyConverter.java // public final class DefaultBodyConverter implements BodyConverter { // @NotNull // @Override // public Body convert(@NotNull MultiValueMap<Body> params, @NotNull String[] args) { // throw new UnsupportedOperationException(); // } // }
import org.mariotaku.restfu.http.mime.BodyConverter; import org.mariotaku.restfu.http.mime.DefaultBodyConverter; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
/* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu.http; /** * Created by mariotaku on 15/2/6. */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface BodyType { String value();
// Path: library/src/main/java/org/mariotaku/restfu/http/mime/BodyConverter.java // public interface BodyConverter { // @NotNull // Body convert(@NotNull MultiValueMap<Body> params, @NotNull String[] args); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/mime/DefaultBodyConverter.java // public final class DefaultBodyConverter implements BodyConverter { // @NotNull // @Override // public Body convert(@NotNull MultiValueMap<Body> params, @NotNull String[] args) { // throw new UnsupportedOperationException(); // } // } // Path: library/src/main/java/org/mariotaku/restfu/http/BodyType.java import org.mariotaku.restfu.http.mime.BodyConverter; import org.mariotaku.restfu.http.mime.DefaultBodyConverter; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu.http; /** * Created by mariotaku on 15/2/6. */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface BodyType { String value();
Class<? extends BodyConverter> converter() default DefaultBodyConverter.class;
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/http/BodyType.java
// Path: library/src/main/java/org/mariotaku/restfu/http/mime/BodyConverter.java // public interface BodyConverter { // @NotNull // Body convert(@NotNull MultiValueMap<Body> params, @NotNull String[] args); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/mime/DefaultBodyConverter.java // public final class DefaultBodyConverter implements BodyConverter { // @NotNull // @Override // public Body convert(@NotNull MultiValueMap<Body> params, @NotNull String[] args) { // throw new UnsupportedOperationException(); // } // }
import org.mariotaku.restfu.http.mime.BodyConverter; import org.mariotaku.restfu.http.mime.DefaultBodyConverter; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
/* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu.http; /** * Created by mariotaku on 15/2/6. */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface BodyType { String value();
// Path: library/src/main/java/org/mariotaku/restfu/http/mime/BodyConverter.java // public interface BodyConverter { // @NotNull // Body convert(@NotNull MultiValueMap<Body> params, @NotNull String[] args); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/mime/DefaultBodyConverter.java // public final class DefaultBodyConverter implements BodyConverter { // @NotNull // @Override // public Body convert(@NotNull MultiValueMap<Body> params, @NotNull String[] args) { // throw new UnsupportedOperationException(); // } // } // Path: library/src/main/java/org/mariotaku/restfu/http/BodyType.java import org.mariotaku.restfu.http.mime.BodyConverter; import org.mariotaku.restfu.http.mime.DefaultBodyConverter; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu.http; /** * Created by mariotaku on 15/2/6. */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface BodyType { String value();
Class<? extends BodyConverter> converter() default DefaultBodyConverter.class;
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/http/mime/FileBody.java
// Path: library/src/main/java/org/mariotaku/restfu/http/ContentType.java // public final class ContentType { // // public static final ContentType OCTET_STREAM = ContentType.parse("application/octet-stream"); // // private final String contentType; // private final List<Pair<String, String>> parameters; // // public ContentType(String contentType, Charset charset) { // this(contentType, new ArrayList<Pair<String, String>>()); // addParameter("charset", charset.name()); // } // // public ContentType(String contentType) { // this(contentType, new ArrayList<Pair<String, String>>()); // } // // public ContentType(String contentType, List<Pair<String, String>> parameters) { // this.contentType = contentType; // this.parameters = parameters; // } // // public boolean addParameter(String name, String value) { // return parameters.add(Pair.create(name, value)); // } // // public ContentType parameter(String name, String value) { // addParameter(name, value); // return this; // } // // public String parameter(String name) { // for (Pair<String, String> parameter : parameters) { // if (name.equalsIgnoreCase(parameter.first)) return parameter.second; // } // return null; // } // // @Override // public String toString() { // return "ContentType{" + // "contentType='" + contentType + '\'' + // ", parameters=" + parameters + // '}'; // } // // public Charset getCharset() { // if (parameters == null) return null; // final String charset = parameter("charset"); // if (charset != null) return Charset.forName(charset); // return null; // } // // public String getContentType() { // return contentType; // } // // public String toHeader() { // final StringBuilder sb = new StringBuilder(contentType); // for (Pair<String, String> parameter : parameters) { // sb.append("; "); // sb.append(parameter.first); // sb.append("="); // sb.append(parameter.second); // } // return sb.toString(); // } // // public static ContentType parse(String string) { // final List<Pair<String, String>> parameters = new ArrayList<>(); // int previousIndex = string.indexOf(';', 0); // String contentType; // if (previousIndex == -1) { // contentType = string; // } else { // contentType = string.substring(0, previousIndex); // } // while (previousIndex != -1) { // final int idx = string.indexOf(';', previousIndex + 1); // final String[] segs; // if (idx < 0) { // segs = RestFuUtils.split(string.substring(previousIndex + 1, string.length()).trim(), "="); // } else { // segs = RestFuUtils.split(string.substring(previousIndex + 1, idx).trim(), "="); // } // if (segs.length == 2) { // parameters.add(Pair.create(segs[0], segs[1])); // } // if (idx < 0) { // break; // } // previousIndex = idx; // } // return new ContentType(contentType, parameters); // } // // public ContentType charset(Charset charset) { // removeParameter("charset"); // return parameter("charset", charset.name()); // } // // private void removeParameter(String name) { // for (int i = parameters.size() - 1; i >= 0; i++) { // if (name.equals(parameters.get(i).first)) { // parameters.remove(i); // } // } // } // }
import org.mariotaku.commons.io.StreamUtils; import org.mariotaku.restfu.http.ContentType; import java.io.*;
/* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 15/5/6. */ public class FileBody implements Body { private long length = -1; private File file;
// Path: library/src/main/java/org/mariotaku/restfu/http/ContentType.java // public final class ContentType { // // public static final ContentType OCTET_STREAM = ContentType.parse("application/octet-stream"); // // private final String contentType; // private final List<Pair<String, String>> parameters; // // public ContentType(String contentType, Charset charset) { // this(contentType, new ArrayList<Pair<String, String>>()); // addParameter("charset", charset.name()); // } // // public ContentType(String contentType) { // this(contentType, new ArrayList<Pair<String, String>>()); // } // // public ContentType(String contentType, List<Pair<String, String>> parameters) { // this.contentType = contentType; // this.parameters = parameters; // } // // public boolean addParameter(String name, String value) { // return parameters.add(Pair.create(name, value)); // } // // public ContentType parameter(String name, String value) { // addParameter(name, value); // return this; // } // // public String parameter(String name) { // for (Pair<String, String> parameter : parameters) { // if (name.equalsIgnoreCase(parameter.first)) return parameter.second; // } // return null; // } // // @Override // public String toString() { // return "ContentType{" + // "contentType='" + contentType + '\'' + // ", parameters=" + parameters + // '}'; // } // // public Charset getCharset() { // if (parameters == null) return null; // final String charset = parameter("charset"); // if (charset != null) return Charset.forName(charset); // return null; // } // // public String getContentType() { // return contentType; // } // // public String toHeader() { // final StringBuilder sb = new StringBuilder(contentType); // for (Pair<String, String> parameter : parameters) { // sb.append("; "); // sb.append(parameter.first); // sb.append("="); // sb.append(parameter.second); // } // return sb.toString(); // } // // public static ContentType parse(String string) { // final List<Pair<String, String>> parameters = new ArrayList<>(); // int previousIndex = string.indexOf(';', 0); // String contentType; // if (previousIndex == -1) { // contentType = string; // } else { // contentType = string.substring(0, previousIndex); // } // while (previousIndex != -1) { // final int idx = string.indexOf(';', previousIndex + 1); // final String[] segs; // if (idx < 0) { // segs = RestFuUtils.split(string.substring(previousIndex + 1, string.length()).trim(), "="); // } else { // segs = RestFuUtils.split(string.substring(previousIndex + 1, idx).trim(), "="); // } // if (segs.length == 2) { // parameters.add(Pair.create(segs[0], segs[1])); // } // if (idx < 0) { // break; // } // previousIndex = idx; // } // return new ContentType(contentType, parameters); // } // // public ContentType charset(Charset charset) { // removeParameter("charset"); // return parameter("charset", charset.name()); // } // // private void removeParameter(String name) { // for (int i = parameters.size() - 1; i >= 0; i++) { // if (name.equals(parameters.get(i).first)) { // parameters.remove(i); // } // } // } // } // Path: library/src/main/java/org/mariotaku/restfu/http/mime/FileBody.java import org.mariotaku.commons.io.StreamUtils; import org.mariotaku.restfu.http.ContentType; import java.io.*; /* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 15/5/6. */ public class FileBody implements Body { private long length = -1; private File file;
private ContentType contentType;
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/RestAPIFactory.java
// Path: library/src/main/java/org/mariotaku/restfu/callback/Callback.java // public interface Callback<T, E extends Exception> { // void result(@NotNull T result) throws E, IOException; // // void error(@NotNull E exception); // } // // Path: library/src/main/java/org/mariotaku/restfu/callback/RawCallback.java // public interface RawCallback<E extends Exception> extends Callback<HttpResponse, E> { // // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.restfu.callback.Callback; import org.mariotaku.restfu.callback.RawCallback; import org.mariotaku.restfu.http.*; import java.io.IOException; import java.lang.reflect.*;
@Override public Endpoint getEndpoint() { return endpoint; } @Override public RestHttpClient getRestClient() { return restClient; } @Override public Authorization getAuthorization() { return authorization; } @SuppressWarnings({"TryWithIdenticalCatches"}) @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws E { try { if (method.getDeclaringClass() == Object.class) { return method.invoke(this, args); } else if (method.getDeclaringClass() == RestClient.class) { return method.invoke(this, args); } } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } final RestMethod<E> restMethod = RestMethod.get(method, args);
// Path: library/src/main/java/org/mariotaku/restfu/callback/Callback.java // public interface Callback<T, E extends Exception> { // void result(@NotNull T result) throws E, IOException; // // void error(@NotNull E exception); // } // // Path: library/src/main/java/org/mariotaku/restfu/callback/RawCallback.java // public interface RawCallback<E extends Exception> extends Callback<HttpResponse, E> { // // } // Path: library/src/main/java/org/mariotaku/restfu/RestAPIFactory.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.restfu.callback.Callback; import org.mariotaku.restfu.callback.RawCallback; import org.mariotaku.restfu.http.*; import java.io.IOException; import java.lang.reflect.*; @Override public Endpoint getEndpoint() { return endpoint; } @Override public RestHttpClient getRestClient() { return restClient; } @Override public Authorization getAuthorization() { return authorization; } @SuppressWarnings({"TryWithIdenticalCatches"}) @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws E { try { if (method.getDeclaringClass() == Object.class) { return method.invoke(this, args); } else if (method.getDeclaringClass() == RestClient.class) { return method.invoke(this, args); } } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } final RestMethod<E> restMethod = RestMethod.get(method, args);
final Callback<?, E> callback = findCallback(args);
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/RestAPIFactory.java
// Path: library/src/main/java/org/mariotaku/restfu/callback/Callback.java // public interface Callback<T, E extends Exception> { // void result(@NotNull T result) throws E, IOException; // // void error(@NotNull E exception); // } // // Path: library/src/main/java/org/mariotaku/restfu/callback/RawCallback.java // public interface RawCallback<E extends Exception> extends Callback<HttpResponse, E> { // // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.restfu.callback.Callback; import org.mariotaku.restfu.callback.RawCallback; import org.mariotaku.restfu.http.*; import java.io.IOException; import java.lang.reflect.*;
// Get converter before network requests, https://github.com/TwidereProject/Twidere-Android/issues/378 // We can throw exceptions before network requests sent final Type returnType = method.getGenericReturnType(); restRequest = requestInfoFactory.create(restMethod, converterFactory, constantPoll); httpRequest = requestFactory.create(endpoint, restRequest, authorization, converterFactory); httpCall = restClient.newCall(httpRequest); httpResponse = httpCall.execute(); if (!httpResponse.isSuccessful()) { return onError(null, httpRequest, httpResponse, callback); } return onResult(returnType, httpResponse, callback); } catch (IOException e) { return onError(e, httpRequest, httpResponse, callback); } catch (RestConverter.ConvertException e) { return onError(e, httpRequest, httpResponse, callback); } finally { RestFuUtils.closeSilently(httpResponse); RestFuUtils.closeSilently(httpCall); } } private <T> Object onResult(@NotNull Type returnType, @NotNull HttpResponse httpResponse, @Nullable final Callback<?, E> callback) throws RestConverter.ConvertException, E, IOException { if (callback == null) { //noinspection unchecked final RestConverter<HttpResponse, T, E> converter = (RestConverter<HttpResponse, T, E>) converterFactory.forResponse(returnType); return converter.convert(httpResponse); }
// Path: library/src/main/java/org/mariotaku/restfu/callback/Callback.java // public interface Callback<T, E extends Exception> { // void result(@NotNull T result) throws E, IOException; // // void error(@NotNull E exception); // } // // Path: library/src/main/java/org/mariotaku/restfu/callback/RawCallback.java // public interface RawCallback<E extends Exception> extends Callback<HttpResponse, E> { // // } // Path: library/src/main/java/org/mariotaku/restfu/RestAPIFactory.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.restfu.callback.Callback; import org.mariotaku.restfu.callback.RawCallback; import org.mariotaku.restfu.http.*; import java.io.IOException; import java.lang.reflect.*; // Get converter before network requests, https://github.com/TwidereProject/Twidere-Android/issues/378 // We can throw exceptions before network requests sent final Type returnType = method.getGenericReturnType(); restRequest = requestInfoFactory.create(restMethod, converterFactory, constantPoll); httpRequest = requestFactory.create(endpoint, restRequest, authorization, converterFactory); httpCall = restClient.newCall(httpRequest); httpResponse = httpCall.execute(); if (!httpResponse.isSuccessful()) { return onError(null, httpRequest, httpResponse, callback); } return onResult(returnType, httpResponse, callback); } catch (IOException e) { return onError(e, httpRequest, httpResponse, callback); } catch (RestConverter.ConvertException e) { return onError(e, httpRequest, httpResponse, callback); } finally { RestFuUtils.closeSilently(httpResponse); RestFuUtils.closeSilently(httpCall); } } private <T> Object onResult(@NotNull Type returnType, @NotNull HttpResponse httpResponse, @Nullable final Callback<?, E> callback) throws RestConverter.ConvertException, E, IOException { if (callback == null) { //noinspection unchecked final RestConverter<HttpResponse, T, E> converter = (RestConverter<HttpResponse, T, E>) converterFactory.forResponse(returnType); return converter.convert(httpResponse); }
if (callback instanceof RawCallback) {
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/http/mime/SimpleBody.java
// Path: library/src/main/java/org/mariotaku/restfu/http/ContentType.java // public final class ContentType { // // public static final ContentType OCTET_STREAM = ContentType.parse("application/octet-stream"); // // private final String contentType; // private final List<Pair<String, String>> parameters; // // public ContentType(String contentType, Charset charset) { // this(contentType, new ArrayList<Pair<String, String>>()); // addParameter("charset", charset.name()); // } // // public ContentType(String contentType) { // this(contentType, new ArrayList<Pair<String, String>>()); // } // // public ContentType(String contentType, List<Pair<String, String>> parameters) { // this.contentType = contentType; // this.parameters = parameters; // } // // public boolean addParameter(String name, String value) { // return parameters.add(Pair.create(name, value)); // } // // public ContentType parameter(String name, String value) { // addParameter(name, value); // return this; // } // // public String parameter(String name) { // for (Pair<String, String> parameter : parameters) { // if (name.equalsIgnoreCase(parameter.first)) return parameter.second; // } // return null; // } // // @Override // public String toString() { // return "ContentType{" + // "contentType='" + contentType + '\'' + // ", parameters=" + parameters + // '}'; // } // // public Charset getCharset() { // if (parameters == null) return null; // final String charset = parameter("charset"); // if (charset != null) return Charset.forName(charset); // return null; // } // // public String getContentType() { // return contentType; // } // // public String toHeader() { // final StringBuilder sb = new StringBuilder(contentType); // for (Pair<String, String> parameter : parameters) { // sb.append("; "); // sb.append(parameter.first); // sb.append("="); // sb.append(parameter.second); // } // return sb.toString(); // } // // public static ContentType parse(String string) { // final List<Pair<String, String>> parameters = new ArrayList<>(); // int previousIndex = string.indexOf(';', 0); // String contentType; // if (previousIndex == -1) { // contentType = string; // } else { // contentType = string.substring(0, previousIndex); // } // while (previousIndex != -1) { // final int idx = string.indexOf(';', previousIndex + 1); // final String[] segs; // if (idx < 0) { // segs = RestFuUtils.split(string.substring(previousIndex + 1, string.length()).trim(), "="); // } else { // segs = RestFuUtils.split(string.substring(previousIndex + 1, idx).trim(), "="); // } // if (segs.length == 2) { // parameters.add(Pair.create(segs[0], segs[1])); // } // if (idx < 0) { // break; // } // previousIndex = idx; // } // return new ContentType(contentType, parameters); // } // // public ContentType charset(Charset charset) { // removeParameter("charset"); // return parameter("charset", charset.name()); // } // // private void removeParameter(String name) { // for (int i = parameters.size() - 1; i >= 0; i++) { // if (name.equals(parameters.get(i).first)) { // parameters.remove(i); // } // } // } // } // // Path: library/src/main/java/org/mariotaku/restfu/io/StreamingGZIPInputStream.java // public final class StreamingGZIPInputStream extends GZIPInputStream { // private final InputStream wrapped; // // public StreamingGZIPInputStream(InputStream is) throws IOException { // super(is); // wrapped = is; // } // // /** // * <p> // * Overrides behavior of GZIPInputStream which assumes we have all the data available // * which is not true for streaming. We instead rely on the underlying stream to tell us // * how much data is available. // * </p> // * <p> // * Programs should not count on this method to return the actual number // * of bytes that could be read without blocking. // * </p> // * // * @return - whatever the wrapped InputStream returns // * @throws IOException if an I/O error occurs. // */ // public int available() throws IOException { // return wrapped.available(); // } // }
import org.mariotaku.commons.io.StreamUtils; import org.mariotaku.restfu.http.ContentType; import org.mariotaku.restfu.io.StreamingGZIPInputStream; import java.io.*; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.charset.Charset;
/* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 15/2/7. */ public class SimpleBody implements Body { private final ContentType contentType; private final long contentLength; private final InputStream stream; private final String contentEncoding; public SimpleBody(ContentType contentType, String contentEncoding, long contentLength, InputStream stream) throws IOException { this.contentType = contentType; this.contentEncoding = contentEncoding; this.contentLength = contentLength; if ("gzip".equals(contentEncoding)) {
// Path: library/src/main/java/org/mariotaku/restfu/http/ContentType.java // public final class ContentType { // // public static final ContentType OCTET_STREAM = ContentType.parse("application/octet-stream"); // // private final String contentType; // private final List<Pair<String, String>> parameters; // // public ContentType(String contentType, Charset charset) { // this(contentType, new ArrayList<Pair<String, String>>()); // addParameter("charset", charset.name()); // } // // public ContentType(String contentType) { // this(contentType, new ArrayList<Pair<String, String>>()); // } // // public ContentType(String contentType, List<Pair<String, String>> parameters) { // this.contentType = contentType; // this.parameters = parameters; // } // // public boolean addParameter(String name, String value) { // return parameters.add(Pair.create(name, value)); // } // // public ContentType parameter(String name, String value) { // addParameter(name, value); // return this; // } // // public String parameter(String name) { // for (Pair<String, String> parameter : parameters) { // if (name.equalsIgnoreCase(parameter.first)) return parameter.second; // } // return null; // } // // @Override // public String toString() { // return "ContentType{" + // "contentType='" + contentType + '\'' + // ", parameters=" + parameters + // '}'; // } // // public Charset getCharset() { // if (parameters == null) return null; // final String charset = parameter("charset"); // if (charset != null) return Charset.forName(charset); // return null; // } // // public String getContentType() { // return contentType; // } // // public String toHeader() { // final StringBuilder sb = new StringBuilder(contentType); // for (Pair<String, String> parameter : parameters) { // sb.append("; "); // sb.append(parameter.first); // sb.append("="); // sb.append(parameter.second); // } // return sb.toString(); // } // // public static ContentType parse(String string) { // final List<Pair<String, String>> parameters = new ArrayList<>(); // int previousIndex = string.indexOf(';', 0); // String contentType; // if (previousIndex == -1) { // contentType = string; // } else { // contentType = string.substring(0, previousIndex); // } // while (previousIndex != -1) { // final int idx = string.indexOf(';', previousIndex + 1); // final String[] segs; // if (idx < 0) { // segs = RestFuUtils.split(string.substring(previousIndex + 1, string.length()).trim(), "="); // } else { // segs = RestFuUtils.split(string.substring(previousIndex + 1, idx).trim(), "="); // } // if (segs.length == 2) { // parameters.add(Pair.create(segs[0], segs[1])); // } // if (idx < 0) { // break; // } // previousIndex = idx; // } // return new ContentType(contentType, parameters); // } // // public ContentType charset(Charset charset) { // removeParameter("charset"); // return parameter("charset", charset.name()); // } // // private void removeParameter(String name) { // for (int i = parameters.size() - 1; i >= 0; i++) { // if (name.equals(parameters.get(i).first)) { // parameters.remove(i); // } // } // } // } // // Path: library/src/main/java/org/mariotaku/restfu/io/StreamingGZIPInputStream.java // public final class StreamingGZIPInputStream extends GZIPInputStream { // private final InputStream wrapped; // // public StreamingGZIPInputStream(InputStream is) throws IOException { // super(is); // wrapped = is; // } // // /** // * <p> // * Overrides behavior of GZIPInputStream which assumes we have all the data available // * which is not true for streaming. We instead rely on the underlying stream to tell us // * how much data is available. // * </p> // * <p> // * Programs should not count on this method to return the actual number // * of bytes that could be read without blocking. // * </p> // * // * @return - whatever the wrapped InputStream returns // * @throws IOException if an I/O error occurs. // */ // public int available() throws IOException { // return wrapped.available(); // } // } // Path: library/src/main/java/org/mariotaku/restfu/http/mime/SimpleBody.java import org.mariotaku.commons.io.StreamUtils; import org.mariotaku.restfu.http.ContentType; import org.mariotaku.restfu.io.StreamingGZIPInputStream; import java.io.*; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.charset.Charset; /* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 15/2/7. */ public class SimpleBody implements Body { private final ContentType contentType; private final long contentLength; private final InputStream stream; private final String contentEncoding; public SimpleBody(ContentType contentType, String contentEncoding, long contentLength, InputStream stream) throws IOException { this.contentType = contentType; this.contentEncoding = contentEncoding; this.contentLength = contentLength; if ("gzip".equals(contentEncoding)) {
this.stream = new StreamingGZIPInputStream(stream);
mariotaku/RestFu
library/src/test/java/org/mariotaku/restfu/http/mime/DirectThrowCall.java
// Path: library/src/main/java/org/mariotaku/restfu/http/HttpCall.java // public interface HttpCall extends Closeable { // // @NotNull // HttpResponse execute() throws IOException; // // void enqueue(@NotNull HttpCallback callback); // // void cancel(); // // boolean isCanceled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpCallback.java // public interface HttpCallback { // // void response(@NotNull HttpResponse response); // // void failure(@NotNull IOException ioe); // // void cancelled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // }
import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.http.HttpCall; import org.mariotaku.restfu.http.HttpCallback; import org.mariotaku.restfu.http.HttpResponse; import java.io.IOException;
package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/3/25. */ public class DirectThrowCall implements HttpCall { @NotNull @Override
// Path: library/src/main/java/org/mariotaku/restfu/http/HttpCall.java // public interface HttpCall extends Closeable { // // @NotNull // HttpResponse execute() throws IOException; // // void enqueue(@NotNull HttpCallback callback); // // void cancel(); // // boolean isCanceled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpCallback.java // public interface HttpCallback { // // void response(@NotNull HttpResponse response); // // void failure(@NotNull IOException ioe); // // void cancelled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // } // Path: library/src/test/java/org/mariotaku/restfu/http/mime/DirectThrowCall.java import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.http.HttpCall; import org.mariotaku.restfu.http.HttpCallback; import org.mariotaku.restfu.http.HttpResponse; import java.io.IOException; package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/3/25. */ public class DirectThrowCall implements HttpCall { @NotNull @Override
public HttpResponse execute() throws IOException {
mariotaku/RestFu
library/src/test/java/org/mariotaku/restfu/http/mime/DirectThrowCall.java
// Path: library/src/main/java/org/mariotaku/restfu/http/HttpCall.java // public interface HttpCall extends Closeable { // // @NotNull // HttpResponse execute() throws IOException; // // void enqueue(@NotNull HttpCallback callback); // // void cancel(); // // boolean isCanceled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpCallback.java // public interface HttpCallback { // // void response(@NotNull HttpResponse response); // // void failure(@NotNull IOException ioe); // // void cancelled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // }
import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.http.HttpCall; import org.mariotaku.restfu.http.HttpCallback; import org.mariotaku.restfu.http.HttpResponse; import java.io.IOException;
package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/3/25. */ public class DirectThrowCall implements HttpCall { @NotNull @Override public HttpResponse execute() throws IOException { throw new IOException("Must throw"); } @Override
// Path: library/src/main/java/org/mariotaku/restfu/http/HttpCall.java // public interface HttpCall extends Closeable { // // @NotNull // HttpResponse execute() throws IOException; // // void enqueue(@NotNull HttpCallback callback); // // void cancel(); // // boolean isCanceled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpCallback.java // public interface HttpCallback { // // void response(@NotNull HttpResponse response); // // void failure(@NotNull IOException ioe); // // void cancelled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // } // Path: library/src/test/java/org/mariotaku/restfu/http/mime/DirectThrowCall.java import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.http.HttpCall; import org.mariotaku.restfu.http.HttpCallback; import org.mariotaku.restfu.http.HttpResponse; import java.io.IOException; package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/3/25. */ public class DirectThrowCall implements HttpCall { @NotNull @Override public HttpResponse execute() throws IOException { throw new IOException("Must throw"); } @Override
public void enqueue(@NotNull HttpCallback callback) {
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/RestMethod.java
// Path: library/src/main/java/org/mariotaku/restfu/http/mime/Body.java // public interface Body extends Closeable { // ContentType contentType(); // // String contentEncoding(); // // long length() throws IOException; // // long writeTo(final OutputStream os) throws IOException; // // InputStream stream() throws IOException; // // void close() throws IOException; // // } // // Path: library/src/main/java/org/mariotaku/restfu/http/mime/UrlSerialization.java // public abstract class UrlSerialization { // // static final char[] HEX_CHAR_TABLE = { // '0', '1', '2', '3', // '4', '5', '6', '7', // '8', '9', 'A', 'B', // 'C', 'D', 'E', 'F' // }; // // public static UrlSerialization PATH = new UrlSerialization() { // final BitSet allowedSet; // // { // allowedSet = new BitSet(0xFF); // // allowedSet.set('_', true); // allowedSet.set('-', true); // allowedSet.set('!', true); // allowedSet.set('.', true); // allowedSet.set('~', true); // allowedSet.set('\'', true); // allowedSet.set('(', true); // allowedSet.set(')', true); // allowedSet.set('*', true); // for (int i = '0'; i <= '9'; i++) { // allowedSet.set(i, true); // } // for (int i = 'A'; i <= 'Z'; i++) { // allowedSet.set(i, true); // } // for (int i = 'a'; i <= 'z'; i++) { // allowedSet.set(i, true); // } // } // // @Override // protected void appendEscape(int codePoint, Charset charset, StringBuilder target) { // if (codePoint <= 0xFF && allowedSet.get(codePoint)) { // target.appendCodePoint(codePoint); // } else { // percentEncode(codePoint, charset, target); // } // } // }; // // /** // * https://url.spec.whatwg.org/#concept-urlsearchparams-list // */ // public static UrlSerialization QUERY = new UrlSerialization() { // final BitSet allowedSet; // // { // allowedSet = new BitSet(0xFF); // // allowedSet.set('*', true); // allowedSet.set('-', true); // allowedSet.set('.', true); // allowedSet.set('_', true); // for (int i = '0'; i <= '9'; i++) { // allowedSet.set(i, true); // } // for (int i = 'A'; i <= 'Z'; i++) { // allowedSet.set(i, true); // } // for (int i = 'a'; i <= 'z'; i++) { // allowedSet.set(i, true); // } // } // // @Override // protected void appendEscape(int codePoint, Charset charset, StringBuilder target) { // if (codePoint == 0x20) { // target.append('+'); // } else if (codePoint <= 0xFF && allowedSet.get(codePoint)) { // target.appendCodePoint(codePoint); // } else { // percentEncode(codePoint, charset, target); // } // } // }; // // // protected abstract void appendEscape(int codePoint, Charset charset, StringBuilder target); // // protected final void percentEncode(int codePoint, Charset charset, StringBuilder target) { // CharBuffer cb = CharBuffer.wrap(Character.toChars(codePoint)); // ByteBuffer encoded = charset.encode(cb); // for (int i = 0, j = encoded.limit(); i < j; i++) { // target.append('%'); // byte v = encoded.get(i); // target.append(HEX_CHAR_TABLE[(v & 0xF0) >>> 4]); // target.append(HEX_CHAR_TABLE[v & 0xF]); // } // } // // public final String serialize(String str, Charset charset) { // final StringBuilder sb = new StringBuilder(); // serialize(str, charset, sb); // return sb.toString(); // } // // public final void serialize(String str, Charset charset, StringBuilder target) { // final int length = str.length(); // for (int offset = 0; offset < length; ) { // final int codePoint = str.codePointAt(offset); // appendEscape(codePoint, charset, target); // offset += Character.charCount(codePoint); // } // } // // }
import java.util.HashMap; import java.util.Map; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.commons.collection.Pair; import org.mariotaku.restfu.annotation.HttpMethod; import org.mariotaku.restfu.annotation.param.*; import org.mariotaku.restfu.http.*; import org.mariotaku.restfu.http.mime.Body; import org.mariotaku.restfu.http.mime.UrlSerialization; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.util.ArrayList;
map.put(key, valueMap.get(key)); } } } else if (value != null) { for (String key : extra.value()) { map.put(key, value); } } } return extrasCache = map; } @NotNull public RestRequest toRestRequest(@NotNull RestConverter.Factory<E> factory, @Nullable final ValueMap valuesPool) throws RestConverter.ConvertException, IOException, E { final HttpMethod method = getMethod(); final MultiValueMap<Body> params = getParams(factory, valuesPool); final RawValue fileValue = getRawValue(); checkMethod(method, fileValue); return new RestRequest(method.value(), method.allowBody(), getPath(), getHeaders(valuesPool), getQueries(valuesPool), params, fileValue, getBodyType(), getExtras()); } private String findPathReplacement(String key) { final Charset charset = Charset.forName("UTF-8"); for (Pair<Path, Object> entry : paths) { if (key.equals(entry.first.value())) { if (entry.first.encoded()) { return String.valueOf(entry.second); } else {
// Path: library/src/main/java/org/mariotaku/restfu/http/mime/Body.java // public interface Body extends Closeable { // ContentType contentType(); // // String contentEncoding(); // // long length() throws IOException; // // long writeTo(final OutputStream os) throws IOException; // // InputStream stream() throws IOException; // // void close() throws IOException; // // } // // Path: library/src/main/java/org/mariotaku/restfu/http/mime/UrlSerialization.java // public abstract class UrlSerialization { // // static final char[] HEX_CHAR_TABLE = { // '0', '1', '2', '3', // '4', '5', '6', '7', // '8', '9', 'A', 'B', // 'C', 'D', 'E', 'F' // }; // // public static UrlSerialization PATH = new UrlSerialization() { // final BitSet allowedSet; // // { // allowedSet = new BitSet(0xFF); // // allowedSet.set('_', true); // allowedSet.set('-', true); // allowedSet.set('!', true); // allowedSet.set('.', true); // allowedSet.set('~', true); // allowedSet.set('\'', true); // allowedSet.set('(', true); // allowedSet.set(')', true); // allowedSet.set('*', true); // for (int i = '0'; i <= '9'; i++) { // allowedSet.set(i, true); // } // for (int i = 'A'; i <= 'Z'; i++) { // allowedSet.set(i, true); // } // for (int i = 'a'; i <= 'z'; i++) { // allowedSet.set(i, true); // } // } // // @Override // protected void appendEscape(int codePoint, Charset charset, StringBuilder target) { // if (codePoint <= 0xFF && allowedSet.get(codePoint)) { // target.appendCodePoint(codePoint); // } else { // percentEncode(codePoint, charset, target); // } // } // }; // // /** // * https://url.spec.whatwg.org/#concept-urlsearchparams-list // */ // public static UrlSerialization QUERY = new UrlSerialization() { // final BitSet allowedSet; // // { // allowedSet = new BitSet(0xFF); // // allowedSet.set('*', true); // allowedSet.set('-', true); // allowedSet.set('.', true); // allowedSet.set('_', true); // for (int i = '0'; i <= '9'; i++) { // allowedSet.set(i, true); // } // for (int i = 'A'; i <= 'Z'; i++) { // allowedSet.set(i, true); // } // for (int i = 'a'; i <= 'z'; i++) { // allowedSet.set(i, true); // } // } // // @Override // protected void appendEscape(int codePoint, Charset charset, StringBuilder target) { // if (codePoint == 0x20) { // target.append('+'); // } else if (codePoint <= 0xFF && allowedSet.get(codePoint)) { // target.appendCodePoint(codePoint); // } else { // percentEncode(codePoint, charset, target); // } // } // }; // // // protected abstract void appendEscape(int codePoint, Charset charset, StringBuilder target); // // protected final void percentEncode(int codePoint, Charset charset, StringBuilder target) { // CharBuffer cb = CharBuffer.wrap(Character.toChars(codePoint)); // ByteBuffer encoded = charset.encode(cb); // for (int i = 0, j = encoded.limit(); i < j; i++) { // target.append('%'); // byte v = encoded.get(i); // target.append(HEX_CHAR_TABLE[(v & 0xF0) >>> 4]); // target.append(HEX_CHAR_TABLE[v & 0xF]); // } // } // // public final String serialize(String str, Charset charset) { // final StringBuilder sb = new StringBuilder(); // serialize(str, charset, sb); // return sb.toString(); // } // // public final void serialize(String str, Charset charset, StringBuilder target) { // final int length = str.length(); // for (int offset = 0; offset < length; ) { // final int codePoint = str.codePointAt(offset); // appendEscape(codePoint, charset, target); // offset += Character.charCount(codePoint); // } // } // // } // Path: library/src/main/java/org/mariotaku/restfu/RestMethod.java import java.util.HashMap; import java.util.Map; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.commons.collection.Pair; import org.mariotaku.restfu.annotation.HttpMethod; import org.mariotaku.restfu.annotation.param.*; import org.mariotaku.restfu.http.*; import org.mariotaku.restfu.http.mime.Body; import org.mariotaku.restfu.http.mime.UrlSerialization; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.util.ArrayList; map.put(key, valueMap.get(key)); } } } else if (value != null) { for (String key : extra.value()) { map.put(key, value); } } } return extrasCache = map; } @NotNull public RestRequest toRestRequest(@NotNull RestConverter.Factory<E> factory, @Nullable final ValueMap valuesPool) throws RestConverter.ConvertException, IOException, E { final HttpMethod method = getMethod(); final MultiValueMap<Body> params = getParams(factory, valuesPool); final RawValue fileValue = getRawValue(); checkMethod(method, fileValue); return new RestRequest(method.value(), method.allowBody(), getPath(), getHeaders(valuesPool), getQueries(valuesPool), params, fileValue, getBodyType(), getExtras()); } private String findPathReplacement(String key) { final Charset charset = Charset.forName("UTF-8"); for (Pair<Path, Object> entry : paths) { if (key.equals(entry.first.value())) { if (entry.first.encoded()) { return String.valueOf(entry.second); } else {
return UrlSerialization.PATH.serialize(String.valueOf(entry.second), charset);
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/exception/RestException.java
// Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // }
import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.HttpResponse;
/* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu.exception; /** * Created by mariotaku on 15/2/7. */ public class RestException extends RuntimeException { private HttpRequest request;
// Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // } // Path: library/src/main/java/org/mariotaku/restfu/exception/RestException.java import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.HttpResponse; /* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu.exception; /** * Created by mariotaku on 15/2/7. */ public class RestException extends RuntimeException { private HttpRequest request;
private HttpResponse response;
mariotaku/RestFu
urlconnection/src/main/java/org/mariotaku/restfu/urlconnection/URLConnectionRestClient.java
// Path: library/src/main/java/org/mariotaku/restfu/http/mime/Body.java // public interface Body extends Closeable { // ContentType contentType(); // // String contentEncoding(); // // long length() throws IOException; // // long writeTo(final OutputStream os) throws IOException; // // InputStream stream() throws IOException; // // void close() throws IOException; // // }
import org.jetbrains.annotations.NotNull; import org.mariotaku.commons.collection.Pair; import org.mariotaku.commons.io.StreamUtils; import org.mariotaku.restfu.http.*; import org.mariotaku.restfu.http.mime.Body; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.Map;
package org.mariotaku.restfu.urlconnection; /** * Created by mariotaku on 16/2/12. */ public class URLConnectionRestClient implements RestHttpClient { @NotNull @Override public HttpCall newCall(@NotNull HttpRequest request) { return new URLConnectionCall(request); } @Override public void enqueue(@NotNull HttpCall call, @NotNull HttpCallback callback) { call.enqueue(callback); } static class URLConnectionCall implements HttpCall { private final HttpRequest request; private URLConnectionResponse resp; public URLConnectionCall(HttpRequest request) { this.request = request; } @NotNull @Override public HttpResponse execute() throws IOException { if (resp != null) throw new IllegalStateException("A call can be executed only once"); final URL url = new URL(request.getUrl()); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(request.getMethod()); for (Pair<String, String> pair : request.getHeaders().toList()) { conn.addRequestProperty(pair.first, pair.second); }
// Path: library/src/main/java/org/mariotaku/restfu/http/mime/Body.java // public interface Body extends Closeable { // ContentType contentType(); // // String contentEncoding(); // // long length() throws IOException; // // long writeTo(final OutputStream os) throws IOException; // // InputStream stream() throws IOException; // // void close() throws IOException; // // } // Path: urlconnection/src/main/java/org/mariotaku/restfu/urlconnection/URLConnectionRestClient.java import org.jetbrains.annotations.NotNull; import org.mariotaku.commons.collection.Pair; import org.mariotaku.commons.io.StreamUtils; import org.mariotaku.restfu.http.*; import org.mariotaku.restfu.http.mime.Body; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.Map; package org.mariotaku.restfu.urlconnection; /** * Created by mariotaku on 16/2/12. */ public class URLConnectionRestClient implements RestHttpClient { @NotNull @Override public HttpCall newCall(@NotNull HttpRequest request) { return new URLConnectionCall(request); } @Override public void enqueue(@NotNull HttpCall call, @NotNull HttpCallback callback) { call.enqueue(callback); } static class URLConnectionCall implements HttpCall { private final HttpRequest request; private URLConnectionResponse resp; public URLConnectionCall(HttpRequest request) { this.request = request; } @NotNull @Override public HttpResponse execute() throws IOException { if (resp != null) throw new IllegalStateException("A call can be executed only once"); final URL url = new URL(request.getUrl()); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(request.getMethod()); for (Pair<String, String> pair : request.getHeaders().toList()) { conn.addRequestProperty(pair.first, pair.second); }
final Body body = request.getBody();
mariotaku/RestFu
library/src/test/java/org/mariotaku/restfu/http/mime/DirectThrowRestHttpClient.java
// Path: library/src/main/java/org/mariotaku/restfu/http/HttpCall.java // public interface HttpCall extends Closeable { // // @NotNull // HttpResponse execute() throws IOException; // // void enqueue(@NotNull HttpCallback callback); // // void cancel(); // // boolean isCanceled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpCallback.java // public interface HttpCallback { // // void response(@NotNull HttpResponse response); // // void failure(@NotNull IOException ioe); // // void cancelled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/RestHttpClient.java // public interface RestHttpClient { // // @NotNull HttpCall newCall(@NotNull HttpRequest request); // // void enqueue(@NotNull HttpCall call, @NotNull HttpCallback callback); // // }
import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.http.HttpCall; import org.mariotaku.restfu.http.HttpCallback; import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.RestHttpClient; import java.io.IOException;
package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/3/25. */ class DirectThrowRestHttpClient implements RestHttpClient { @NotNull @Override
// Path: library/src/main/java/org/mariotaku/restfu/http/HttpCall.java // public interface HttpCall extends Closeable { // // @NotNull // HttpResponse execute() throws IOException; // // void enqueue(@NotNull HttpCallback callback); // // void cancel(); // // boolean isCanceled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpCallback.java // public interface HttpCallback { // // void response(@NotNull HttpResponse response); // // void failure(@NotNull IOException ioe); // // void cancelled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/RestHttpClient.java // public interface RestHttpClient { // // @NotNull HttpCall newCall(@NotNull HttpRequest request); // // void enqueue(@NotNull HttpCall call, @NotNull HttpCallback callback); // // } // Path: library/src/test/java/org/mariotaku/restfu/http/mime/DirectThrowRestHttpClient.java import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.http.HttpCall; import org.mariotaku.restfu.http.HttpCallback; import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.RestHttpClient; import java.io.IOException; package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/3/25. */ class DirectThrowRestHttpClient implements RestHttpClient { @NotNull @Override
public HttpCall newCall(@NotNull HttpRequest request) {
mariotaku/RestFu
library/src/test/java/org/mariotaku/restfu/http/mime/DirectThrowRestHttpClient.java
// Path: library/src/main/java/org/mariotaku/restfu/http/HttpCall.java // public interface HttpCall extends Closeable { // // @NotNull // HttpResponse execute() throws IOException; // // void enqueue(@NotNull HttpCallback callback); // // void cancel(); // // boolean isCanceled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpCallback.java // public interface HttpCallback { // // void response(@NotNull HttpResponse response); // // void failure(@NotNull IOException ioe); // // void cancelled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/RestHttpClient.java // public interface RestHttpClient { // // @NotNull HttpCall newCall(@NotNull HttpRequest request); // // void enqueue(@NotNull HttpCall call, @NotNull HttpCallback callback); // // }
import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.http.HttpCall; import org.mariotaku.restfu.http.HttpCallback; import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.RestHttpClient; import java.io.IOException;
package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/3/25. */ class DirectThrowRestHttpClient implements RestHttpClient { @NotNull @Override
// Path: library/src/main/java/org/mariotaku/restfu/http/HttpCall.java // public interface HttpCall extends Closeable { // // @NotNull // HttpResponse execute() throws IOException; // // void enqueue(@NotNull HttpCallback callback); // // void cancel(); // // boolean isCanceled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpCallback.java // public interface HttpCallback { // // void response(@NotNull HttpResponse response); // // void failure(@NotNull IOException ioe); // // void cancelled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/RestHttpClient.java // public interface RestHttpClient { // // @NotNull HttpCall newCall(@NotNull HttpRequest request); // // void enqueue(@NotNull HttpCall call, @NotNull HttpCallback callback); // // } // Path: library/src/test/java/org/mariotaku/restfu/http/mime/DirectThrowRestHttpClient.java import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.http.HttpCall; import org.mariotaku.restfu.http.HttpCallback; import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.RestHttpClient; import java.io.IOException; package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/3/25. */ class DirectThrowRestHttpClient implements RestHttpClient { @NotNull @Override
public HttpCall newCall(@NotNull HttpRequest request) {
mariotaku/RestFu
library/src/test/java/org/mariotaku/restfu/http/mime/DirectThrowRestHttpClient.java
// Path: library/src/main/java/org/mariotaku/restfu/http/HttpCall.java // public interface HttpCall extends Closeable { // // @NotNull // HttpResponse execute() throws IOException; // // void enqueue(@NotNull HttpCallback callback); // // void cancel(); // // boolean isCanceled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpCallback.java // public interface HttpCallback { // // void response(@NotNull HttpResponse response); // // void failure(@NotNull IOException ioe); // // void cancelled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/RestHttpClient.java // public interface RestHttpClient { // // @NotNull HttpCall newCall(@NotNull HttpRequest request); // // void enqueue(@NotNull HttpCall call, @NotNull HttpCallback callback); // // }
import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.http.HttpCall; import org.mariotaku.restfu.http.HttpCallback; import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.RestHttpClient; import java.io.IOException;
package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/3/25. */ class DirectThrowRestHttpClient implements RestHttpClient { @NotNull @Override public HttpCall newCall(@NotNull HttpRequest request) { return new DirectThrowCall(); } @Override
// Path: library/src/main/java/org/mariotaku/restfu/http/HttpCall.java // public interface HttpCall extends Closeable { // // @NotNull // HttpResponse execute() throws IOException; // // void enqueue(@NotNull HttpCallback callback); // // void cancel(); // // boolean isCanceled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpCallback.java // public interface HttpCallback { // // void response(@NotNull HttpResponse response); // // void failure(@NotNull IOException ioe); // // void cancelled(); // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/RestHttpClient.java // public interface RestHttpClient { // // @NotNull HttpCall newCall(@NotNull HttpRequest request); // // void enqueue(@NotNull HttpCall call, @NotNull HttpCallback callback); // // } // Path: library/src/test/java/org/mariotaku/restfu/http/mime/DirectThrowRestHttpClient.java import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.http.HttpCall; import org.mariotaku.restfu.http.HttpCallback; import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.RestHttpClient; import java.io.IOException; package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/3/25. */ class DirectThrowRestHttpClient implements RestHttpClient { @NotNull @Override public HttpCall newCall(@NotNull HttpRequest request) { return new DirectThrowCall(); } @Override
public void enqueue(@NotNull HttpCall call, @NotNull HttpCallback callback) {
mariotaku/RestFu
okhttp/src/main/java/org/mariotaku/restfu/okhttp/OkHttpRestClient.java
// Path: library/src/main/java/org/mariotaku/restfu/http/mime/Body.java // public interface Body extends Closeable { // ContentType contentType(); // // String contentEncoding(); // // long length() throws IOException; // // long writeTo(final OutputStream os) throws IOException; // // InputStream stream() throws IOException; // // void close() throws IOException; // // }
import com.squareup.okhttp.*; import okio.BufferedSink; import okio.Okio; import org.jetbrains.annotations.NotNull; import org.mariotaku.commons.collection.Pair; import org.mariotaku.restfu.http.*; import org.mariotaku.restfu.http.mime.Body; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List;
public OkHttpRestClient(@NotNull OkHttpClient client) { this.client = client; } @NotNull @Override public HttpCall newCall(@NotNull final HttpRequest httpRequest) { final Request.Builder builder = new Request.Builder(); builder.method(httpRequest.getMethod(), RestToOkBody.wrap(httpRequest.getBody())); builder.url(httpRequest.getUrl()); final MultiValueMap<String> headers = httpRequest.getHeaders(); if (headers != null) { for (Pair<String, String> header : headers.toList()) { builder.addHeader(header.first, header.second); } } return new OkToRestCall(client.newCall(builder.build())); } @Override public void enqueue(@NotNull final HttpCall call, @NotNull final HttpCallback callback) { call.enqueue(callback); } @NotNull public OkHttpClient getClient() { return client; } private static class RestToOkBody extends RequestBody {
// Path: library/src/main/java/org/mariotaku/restfu/http/mime/Body.java // public interface Body extends Closeable { // ContentType contentType(); // // String contentEncoding(); // // long length() throws IOException; // // long writeTo(final OutputStream os) throws IOException; // // InputStream stream() throws IOException; // // void close() throws IOException; // // } // Path: okhttp/src/main/java/org/mariotaku/restfu/okhttp/OkHttpRestClient.java import com.squareup.okhttp.*; import okio.BufferedSink; import okio.Okio; import org.jetbrains.annotations.NotNull; import org.mariotaku.commons.collection.Pair; import org.mariotaku.restfu.http.*; import org.mariotaku.restfu.http.mime.Body; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; public OkHttpRestClient(@NotNull OkHttpClient client) { this.client = client; } @NotNull @Override public HttpCall newCall(@NotNull final HttpRequest httpRequest) { final Request.Builder builder = new Request.Builder(); builder.method(httpRequest.getMethod(), RestToOkBody.wrap(httpRequest.getBody())); builder.url(httpRequest.getUrl()); final MultiValueMap<String> headers = httpRequest.getHeaders(); if (headers != null) { for (Pair<String, String> header : headers.toList()) { builder.addHeader(header.first, header.second); } } return new OkToRestCall(client.newCall(builder.build())); } @Override public void enqueue(@NotNull final HttpCall call, @NotNull final HttpCallback callback) { call.enqueue(callback); } @NotNull public OkHttpClient getClient() { return client; } private static class RestToOkBody extends RequestBody {
private final Body body;
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/ExceptionFactory.java
// Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.HttpResponse;
/* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu; /** * Created by mariotaku on 15/5/25. */ public interface ExceptionFactory<E extends Exception> { @NotNull
// Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // } // Path: library/src/main/java/org/mariotaku/restfu/ExceptionFactory.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.HttpResponse; /* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu; /** * Created by mariotaku on 15/5/25. */ public interface ExceptionFactory<E extends Exception> { @NotNull
E newException(@Nullable final Throwable cause, @Nullable final HttpRequest request,
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/ExceptionFactory.java
// Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.HttpResponse;
/* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu; /** * Created by mariotaku on 15/5/25. */ public interface ExceptionFactory<E extends Exception> { @NotNull E newException(@Nullable final Throwable cause, @Nullable final HttpRequest request,
// Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // } // Path: library/src/main/java/org/mariotaku/restfu/ExceptionFactory.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.HttpResponse; /* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu; /** * Created by mariotaku on 15/5/25. */ public interface ExceptionFactory<E extends Exception> { @NotNull E newException(@Nullable final Throwable cause, @Nullable final HttpRequest request,
@Nullable final HttpResponse response);
mariotaku/RestFu
okhttp3/src/main/java/org/mariotaku/restfu/okhttp3/OkHttpRestClient.java
// Path: library/src/main/java/org/mariotaku/restfu/http/mime/Body.java // public interface Body extends Closeable { // ContentType contentType(); // // String contentEncoding(); // // long length() throws IOException; // // long writeTo(final OutputStream os) throws IOException; // // InputStream stream() throws IOException; // // void close() throws IOException; // // }
import okhttp3.*; import okio.BufferedSink; import okio.Okio; import org.jetbrains.annotations.NotNull; import org.mariotaku.commons.collection.Pair; import org.mariotaku.restfu.http.*; import org.mariotaku.restfu.http.mime.Body; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List;
@Override public HttpCall newCall(@NotNull final HttpRequest httpRequest) { final Request.Builder builder = new Request.Builder(); builder.method(httpRequest.getMethod(), RestToOkRequestBody.wrap(httpRequest.getBody())); builder.url(httpRequest.getUrl()); final MultiValueMap<String> headers = httpRequest.getHeaders(); if (headers != null) { for (Pair<String, String> header : headers.toList()) { builder.addHeader(header.first, header.second); } } return new OkToRestCall(client.newCall(builder.build())); } @Override public void enqueue(@NotNull final HttpCall call, @NotNull final HttpCallback callback) { call.enqueue(callback); } public void setClient(OkHttpClient client) { if (client == null) throw new NullPointerException(); this.client = client; } public OkHttpClient getClient() { return client; } private static class OkToRestResponse extends HttpResponse { private final Response response;
// Path: library/src/main/java/org/mariotaku/restfu/http/mime/Body.java // public interface Body extends Closeable { // ContentType contentType(); // // String contentEncoding(); // // long length() throws IOException; // // long writeTo(final OutputStream os) throws IOException; // // InputStream stream() throws IOException; // // void close() throws IOException; // // } // Path: okhttp3/src/main/java/org/mariotaku/restfu/okhttp3/OkHttpRestClient.java import okhttp3.*; import okio.BufferedSink; import okio.Okio; import org.jetbrains.annotations.NotNull; import org.mariotaku.commons.collection.Pair; import org.mariotaku.restfu.http.*; import org.mariotaku.restfu.http.mime.Body; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; @Override public HttpCall newCall(@NotNull final HttpRequest httpRequest) { final Request.Builder builder = new Request.Builder(); builder.method(httpRequest.getMethod(), RestToOkRequestBody.wrap(httpRequest.getBody())); builder.url(httpRequest.getUrl()); final MultiValueMap<String> headers = httpRequest.getHeaders(); if (headers != null) { for (Pair<String, String> header : headers.toList()) { builder.addHeader(header.first, header.second); } } return new OkToRestCall(client.newCall(builder.build())); } @Override public void enqueue(@NotNull final HttpCall call, @NotNull final HttpCallback callback) { call.enqueue(callback); } public void setClient(OkHttpClient client) { if (client == null) throw new NullPointerException(); this.client = client; } public OkHttpClient getClient() { return client; } private static class OkToRestResponse extends HttpResponse { private final Response response;
private final Body body;
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/http/mime/DefaultBodyConverter.java
// Path: library/src/main/java/org/mariotaku/restfu/http/MultiValueMap.java // public final class MultiValueMap<V> extends MultiMap<String, V> { // // public MultiValueMap() { // this(new HashMap<String, List<V>>(), false); // } // // public MultiValueMap(Map<String, List<V>> map) { // this(map, false); // } // // public MultiValueMap(boolean ignoreCase) { // this(null, ignoreCase); // } // // public MultiValueMap(Map<String, List<V>> map, boolean ignoreCase) { // super(map, new StringEquatable(ignoreCase)); // } // // private static class StringEquatable implements Equatable<String> { // private boolean ignoreCase; // // StringEquatable(boolean ignoreCase) { // this.ignoreCase = ignoreCase; // } // // @Override // public boolean equals(String s1, String s2) { // if (s1 == null || s2 == null) { // //noinspection StringEquality // return s1 == s2; // } // if (ignoreCase) { // return s1.equalsIgnoreCase(s2); // } // return s1.equals(s2); // } // } // }
import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.http.MultiValueMap;
package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/4/19. */ public final class DefaultBodyConverter implements BodyConverter { @NotNull @Override
// Path: library/src/main/java/org/mariotaku/restfu/http/MultiValueMap.java // public final class MultiValueMap<V> extends MultiMap<String, V> { // // public MultiValueMap() { // this(new HashMap<String, List<V>>(), false); // } // // public MultiValueMap(Map<String, List<V>> map) { // this(map, false); // } // // public MultiValueMap(boolean ignoreCase) { // this(null, ignoreCase); // } // // public MultiValueMap(Map<String, List<V>> map, boolean ignoreCase) { // super(map, new StringEquatable(ignoreCase)); // } // // private static class StringEquatable implements Equatable<String> { // private boolean ignoreCase; // // StringEquatable(boolean ignoreCase) { // this.ignoreCase = ignoreCase; // } // // @Override // public boolean equals(String s1, String s2) { // if (s1 == null || s2 == null) { // //noinspection StringEquality // return s1 == s2; // } // if (ignoreCase) { // return s1.equalsIgnoreCase(s2); // } // return s1.equals(s2); // } // } // } // Path: library/src/main/java/org/mariotaku/restfu/http/mime/DefaultBodyConverter.java import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.http.MultiValueMap; package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/4/19. */ public final class DefaultBodyConverter implements BodyConverter { @NotNull @Override
public Body convert(@NotNull MultiValueMap<Body> params, @NotNull String[] args) {
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/RestConverter.java
// Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/mime/Body.java // public interface Body extends Closeable { // ContentType contentType(); // // String contentEncoding(); // // long length() throws IOException; // // long writeTo(final OutputStream os) throws IOException; // // InputStream stream() throws IOException; // // void close() throws IOException; // // } // // Path: library/src/main/java/org/mariotaku/restfu/http/mime/SimpleBody.java // public class SimpleBody implements Body { // // private final ContentType contentType; // private final long contentLength; // private final InputStream stream; // private final String contentEncoding; // // public SimpleBody(ContentType contentType, String contentEncoding, long contentLength, InputStream stream) throws IOException { // this.contentType = contentType; // this.contentEncoding = contentEncoding; // this.contentLength = contentLength; // if ("gzip".equals(contentEncoding)) { // this.stream = new StreamingGZIPInputStream(stream); // } else { // this.stream = stream; // } // } // // @Override // public ContentType contentType() { // return contentType; // } // // @Override // public String contentEncoding() { // return contentEncoding; // } // // @Override // public long length() { // return contentLength; // } // // @Override // public String toString() { // return "BaseTypedData{" + // "contentType=" + contentType + // ", contentLength=" + contentLength + // ", stream=" + stream + // ", contentEncoding='" + contentEncoding + '\'' + // '}'; // } // // @Override // public long writeTo(OutputStream os) throws IOException { // final LengthLimitCopyListener listener = new LengthLimitCopyListener(contentLength); // return StreamUtils.copy(stream(), os, listener, listener); // } // // // @Override // public InputStream stream() { // return stream; // } // // @Override // public void close() throws IOException { // stream.close(); // } // // public static Body wrap(Object value) { // if (value == null) return null; // if (value instanceof Body) { // return (Body) value; // } else if (value instanceof File) { // return new FileBody((File) value); // } else if (value instanceof String) { // return new StringBody((String) value, Charset.defaultCharset()); // } else if (value instanceof Number) { // return new StringBody(value.toString(), Charset.defaultCharset()); // } else if (value instanceof Character) { // return new StringBody(value.toString(), Charset.defaultCharset()); // } else if (value instanceof Boolean) { // return new StringBody(value.toString(), Charset.defaultCharset()); // } // throw new UnsupportedOperationException(value.getClass().toString()); // } // // public static boolean supports(Type value) { // if (value instanceof Class) { // return supportsClass((Class<?>) value); // } else if (value instanceof ParameterizedType) { // Type rawType = ((ParameterizedType) value).getRawType(); // if (rawType instanceof Class) { // return supportsClass((Class<?>) rawType); // } // } // return false; // } // // private static boolean supportsClass(Class<?> value) { // if (Body.class.isAssignableFrom(value)) { // return true; // } else if (value == File.class) { // return true; // } else if (value == String.class) { // return true; // } else if (Number.class.isAssignableFrom(value)) { // return true; // } else if (value == Character.class) { // return true; // } else if (value == Boolean.class) { // return true; // } // return false; // } // // public static Reader reader(Body data) throws IOException { // final ContentType contentType = data.contentType(); // final Charset charset = contentType != null ? contentType.getCharset() : null; // return new InputStreamReader(data.stream(), charset != null ? charset : Charset.defaultCharset()); // } // }
import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.http.HttpResponse; import org.mariotaku.restfu.http.mime.Body; import org.mariotaku.restfu.http.mime.SimpleBody; import java.io.IOException; import java.lang.reflect.Type;
/* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu; /** * Created by mariotaku on 15/2/6. */ public interface RestConverter<F, T, E extends Exception> { @NotNull T convert(@NotNull F from) throws ConvertException, IOException, E; interface Factory<E extends Exception> { @NotNull
// Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/mime/Body.java // public interface Body extends Closeable { // ContentType contentType(); // // String contentEncoding(); // // long length() throws IOException; // // long writeTo(final OutputStream os) throws IOException; // // InputStream stream() throws IOException; // // void close() throws IOException; // // } // // Path: library/src/main/java/org/mariotaku/restfu/http/mime/SimpleBody.java // public class SimpleBody implements Body { // // private final ContentType contentType; // private final long contentLength; // private final InputStream stream; // private final String contentEncoding; // // public SimpleBody(ContentType contentType, String contentEncoding, long contentLength, InputStream stream) throws IOException { // this.contentType = contentType; // this.contentEncoding = contentEncoding; // this.contentLength = contentLength; // if ("gzip".equals(contentEncoding)) { // this.stream = new StreamingGZIPInputStream(stream); // } else { // this.stream = stream; // } // } // // @Override // public ContentType contentType() { // return contentType; // } // // @Override // public String contentEncoding() { // return contentEncoding; // } // // @Override // public long length() { // return contentLength; // } // // @Override // public String toString() { // return "BaseTypedData{" + // "contentType=" + contentType + // ", contentLength=" + contentLength + // ", stream=" + stream + // ", contentEncoding='" + contentEncoding + '\'' + // '}'; // } // // @Override // public long writeTo(OutputStream os) throws IOException { // final LengthLimitCopyListener listener = new LengthLimitCopyListener(contentLength); // return StreamUtils.copy(stream(), os, listener, listener); // } // // // @Override // public InputStream stream() { // return stream; // } // // @Override // public void close() throws IOException { // stream.close(); // } // // public static Body wrap(Object value) { // if (value == null) return null; // if (value instanceof Body) { // return (Body) value; // } else if (value instanceof File) { // return new FileBody((File) value); // } else if (value instanceof String) { // return new StringBody((String) value, Charset.defaultCharset()); // } else if (value instanceof Number) { // return new StringBody(value.toString(), Charset.defaultCharset()); // } else if (value instanceof Character) { // return new StringBody(value.toString(), Charset.defaultCharset()); // } else if (value instanceof Boolean) { // return new StringBody(value.toString(), Charset.defaultCharset()); // } // throw new UnsupportedOperationException(value.getClass().toString()); // } // // public static boolean supports(Type value) { // if (value instanceof Class) { // return supportsClass((Class<?>) value); // } else if (value instanceof ParameterizedType) { // Type rawType = ((ParameterizedType) value).getRawType(); // if (rawType instanceof Class) { // return supportsClass((Class<?>) rawType); // } // } // return false; // } // // private static boolean supportsClass(Class<?> value) { // if (Body.class.isAssignableFrom(value)) { // return true; // } else if (value == File.class) { // return true; // } else if (value == String.class) { // return true; // } else if (Number.class.isAssignableFrom(value)) { // return true; // } else if (value == Character.class) { // return true; // } else if (value == Boolean.class) { // return true; // } // return false; // } // // public static Reader reader(Body data) throws IOException { // final ContentType contentType = data.contentType(); // final Charset charset = contentType != null ? contentType.getCharset() : null; // return new InputStreamReader(data.stream(), charset != null ? charset : Charset.defaultCharset()); // } // } // Path: library/src/main/java/org/mariotaku/restfu/RestConverter.java import org.jetbrains.annotations.NotNull; import org.mariotaku.restfu.http.HttpResponse; import org.mariotaku.restfu.http.mime.Body; import org.mariotaku.restfu.http.mime.SimpleBody; import java.io.IOException; import java.lang.reflect.Type; /* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu; /** * Created by mariotaku on 15/2/6. */ public interface RestConverter<F, T, E extends Exception> { @NotNull T convert(@NotNull F from) throws ConvertException, IOException, E; interface Factory<E extends Exception> { @NotNull
RestConverter<HttpResponse, ?, E> forResponse(@NotNull Type toType) throws ConvertException;
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/RestRequest.java
// Path: library/src/main/java/org/mariotaku/restfu/http/MultiValueMap.java // public final class MultiValueMap<V> extends MultiMap<String, V> { // // public MultiValueMap() { // this(new HashMap<String, List<V>>(), false); // } // // public MultiValueMap(Map<String, List<V>> map) { // this(map, false); // } // // public MultiValueMap(boolean ignoreCase) { // this(null, ignoreCase); // } // // public MultiValueMap(Map<String, List<V>> map, boolean ignoreCase) { // super(map, new StringEquatable(ignoreCase)); // } // // private static class StringEquatable implements Equatable<String> { // private boolean ignoreCase; // // StringEquatable(boolean ignoreCase) { // this.ignoreCase = ignoreCase; // } // // @Override // public boolean equals(String s1, String s2) { // if (s1 == null || s2 == null) { // //noinspection StringEquality // return s1 == s2; // } // if (ignoreCase) { // return s1.equalsIgnoreCase(s2); // } // return s1.equals(s2); // } // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/RawValue.java // public final class RawValue { // private final Raw annotation; // private final Object value; // // @Override // public String toString() { // return "FileValue{" + // "annotation=" + annotation + // ", value=" + value + // '}'; // } // // public RawValue(Raw annotation, Object value) { // this.annotation = annotation; // this.value = value; // } // // public <E extends Exception> Body body(RestConverter.Factory<E> converterFactory) throws E, IOException, // RestConverter.ConvertException { // if (value == null) return null; // //noinspection unchecked // final RestConverter<Object, Body, E> converter = // (RestConverter<Object, Body, E>) converterFactory.forRequest(value.getClass()); // if (converter != null) return converter.convert(value); // return SimpleBody.wrap(value); // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/ValueMap.java // public interface ValueMap { // // boolean has(@NotNull String key); // // @Nullable // Object get(@NotNull String key); // // @NotNull // String[] keys(); // // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.commons.collection.Pair; import org.mariotaku.restfu.http.BodyType; import org.mariotaku.restfu.http.MultiValueMap; import org.mariotaku.restfu.http.RawValue; import org.mariotaku.restfu.http.ValueMap; import org.mariotaku.restfu.http.mime.*; import java.io.IOException; import java.util.Map;
/* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu; @SuppressWarnings("WeakerAccess") public final class RestRequest { @NotNull private final String method; private final boolean hasBody; @NotNull private final String path; @Nullable
// Path: library/src/main/java/org/mariotaku/restfu/http/MultiValueMap.java // public final class MultiValueMap<V> extends MultiMap<String, V> { // // public MultiValueMap() { // this(new HashMap<String, List<V>>(), false); // } // // public MultiValueMap(Map<String, List<V>> map) { // this(map, false); // } // // public MultiValueMap(boolean ignoreCase) { // this(null, ignoreCase); // } // // public MultiValueMap(Map<String, List<V>> map, boolean ignoreCase) { // super(map, new StringEquatable(ignoreCase)); // } // // private static class StringEquatable implements Equatable<String> { // private boolean ignoreCase; // // StringEquatable(boolean ignoreCase) { // this.ignoreCase = ignoreCase; // } // // @Override // public boolean equals(String s1, String s2) { // if (s1 == null || s2 == null) { // //noinspection StringEquality // return s1 == s2; // } // if (ignoreCase) { // return s1.equalsIgnoreCase(s2); // } // return s1.equals(s2); // } // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/RawValue.java // public final class RawValue { // private final Raw annotation; // private final Object value; // // @Override // public String toString() { // return "FileValue{" + // "annotation=" + annotation + // ", value=" + value + // '}'; // } // // public RawValue(Raw annotation, Object value) { // this.annotation = annotation; // this.value = value; // } // // public <E extends Exception> Body body(RestConverter.Factory<E> converterFactory) throws E, IOException, // RestConverter.ConvertException { // if (value == null) return null; // //noinspection unchecked // final RestConverter<Object, Body, E> converter = // (RestConverter<Object, Body, E>) converterFactory.forRequest(value.getClass()); // if (converter != null) return converter.convert(value); // return SimpleBody.wrap(value); // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/ValueMap.java // public interface ValueMap { // // boolean has(@NotNull String key); // // @Nullable // Object get(@NotNull String key); // // @NotNull // String[] keys(); // // } // Path: library/src/main/java/org/mariotaku/restfu/RestRequest.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.commons.collection.Pair; import org.mariotaku.restfu.http.BodyType; import org.mariotaku.restfu.http.MultiValueMap; import org.mariotaku.restfu.http.RawValue; import org.mariotaku.restfu.http.ValueMap; import org.mariotaku.restfu.http.mime.*; import java.io.IOException; import java.util.Map; /* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu; @SuppressWarnings("WeakerAccess") public final class RestRequest { @NotNull private final String method; private final boolean hasBody; @NotNull private final String path; @Nullable
private final MultiValueMap<String> headers;
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/RestRequest.java
// Path: library/src/main/java/org/mariotaku/restfu/http/MultiValueMap.java // public final class MultiValueMap<V> extends MultiMap<String, V> { // // public MultiValueMap() { // this(new HashMap<String, List<V>>(), false); // } // // public MultiValueMap(Map<String, List<V>> map) { // this(map, false); // } // // public MultiValueMap(boolean ignoreCase) { // this(null, ignoreCase); // } // // public MultiValueMap(Map<String, List<V>> map, boolean ignoreCase) { // super(map, new StringEquatable(ignoreCase)); // } // // private static class StringEquatable implements Equatable<String> { // private boolean ignoreCase; // // StringEquatable(boolean ignoreCase) { // this.ignoreCase = ignoreCase; // } // // @Override // public boolean equals(String s1, String s2) { // if (s1 == null || s2 == null) { // //noinspection StringEquality // return s1 == s2; // } // if (ignoreCase) { // return s1.equalsIgnoreCase(s2); // } // return s1.equals(s2); // } // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/RawValue.java // public final class RawValue { // private final Raw annotation; // private final Object value; // // @Override // public String toString() { // return "FileValue{" + // "annotation=" + annotation + // ", value=" + value + // '}'; // } // // public RawValue(Raw annotation, Object value) { // this.annotation = annotation; // this.value = value; // } // // public <E extends Exception> Body body(RestConverter.Factory<E> converterFactory) throws E, IOException, // RestConverter.ConvertException { // if (value == null) return null; // //noinspection unchecked // final RestConverter<Object, Body, E> converter = // (RestConverter<Object, Body, E>) converterFactory.forRequest(value.getClass()); // if (converter != null) return converter.convert(value); // return SimpleBody.wrap(value); // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/ValueMap.java // public interface ValueMap { // // boolean has(@NotNull String key); // // @Nullable // Object get(@NotNull String key); // // @NotNull // String[] keys(); // // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.commons.collection.Pair; import org.mariotaku.restfu.http.BodyType; import org.mariotaku.restfu.http.MultiValueMap; import org.mariotaku.restfu.http.RawValue; import org.mariotaku.restfu.http.ValueMap; import org.mariotaku.restfu.http.mime.*; import java.io.IOException; import java.util.Map;
/* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu; @SuppressWarnings("WeakerAccess") public final class RestRequest { @NotNull private final String method; private final boolean hasBody; @NotNull private final String path; @Nullable private final MultiValueMap<String> headers; @Nullable private final MultiValueMap<String> queries; @Nullable private final MultiValueMap<Body> params;
// Path: library/src/main/java/org/mariotaku/restfu/http/MultiValueMap.java // public final class MultiValueMap<V> extends MultiMap<String, V> { // // public MultiValueMap() { // this(new HashMap<String, List<V>>(), false); // } // // public MultiValueMap(Map<String, List<V>> map) { // this(map, false); // } // // public MultiValueMap(boolean ignoreCase) { // this(null, ignoreCase); // } // // public MultiValueMap(Map<String, List<V>> map, boolean ignoreCase) { // super(map, new StringEquatable(ignoreCase)); // } // // private static class StringEquatable implements Equatable<String> { // private boolean ignoreCase; // // StringEquatable(boolean ignoreCase) { // this.ignoreCase = ignoreCase; // } // // @Override // public boolean equals(String s1, String s2) { // if (s1 == null || s2 == null) { // //noinspection StringEquality // return s1 == s2; // } // if (ignoreCase) { // return s1.equalsIgnoreCase(s2); // } // return s1.equals(s2); // } // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/RawValue.java // public final class RawValue { // private final Raw annotation; // private final Object value; // // @Override // public String toString() { // return "FileValue{" + // "annotation=" + annotation + // ", value=" + value + // '}'; // } // // public RawValue(Raw annotation, Object value) { // this.annotation = annotation; // this.value = value; // } // // public <E extends Exception> Body body(RestConverter.Factory<E> converterFactory) throws E, IOException, // RestConverter.ConvertException { // if (value == null) return null; // //noinspection unchecked // final RestConverter<Object, Body, E> converter = // (RestConverter<Object, Body, E>) converterFactory.forRequest(value.getClass()); // if (converter != null) return converter.convert(value); // return SimpleBody.wrap(value); // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/ValueMap.java // public interface ValueMap { // // boolean has(@NotNull String key); // // @Nullable // Object get(@NotNull String key); // // @NotNull // String[] keys(); // // } // Path: library/src/main/java/org/mariotaku/restfu/RestRequest.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.commons.collection.Pair; import org.mariotaku.restfu.http.BodyType; import org.mariotaku.restfu.http.MultiValueMap; import org.mariotaku.restfu.http.RawValue; import org.mariotaku.restfu.http.ValueMap; import org.mariotaku.restfu.http.mime.*; import java.io.IOException; import java.util.Map; /* * Copyright (c) 2015 mariotaku * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mariotaku.restfu; @SuppressWarnings("WeakerAccess") public final class RestRequest { @NotNull private final String method; private final boolean hasBody; @NotNull private final String path; @Nullable private final MultiValueMap<String> headers; @Nullable private final MultiValueMap<String> queries; @Nullable private final MultiValueMap<Body> params;
private final RawValue file;
mariotaku/RestFu
library/src/main/java/org/mariotaku/restfu/RestRequest.java
// Path: library/src/main/java/org/mariotaku/restfu/http/MultiValueMap.java // public final class MultiValueMap<V> extends MultiMap<String, V> { // // public MultiValueMap() { // this(new HashMap<String, List<V>>(), false); // } // // public MultiValueMap(Map<String, List<V>> map) { // this(map, false); // } // // public MultiValueMap(boolean ignoreCase) { // this(null, ignoreCase); // } // // public MultiValueMap(Map<String, List<V>> map, boolean ignoreCase) { // super(map, new StringEquatable(ignoreCase)); // } // // private static class StringEquatable implements Equatable<String> { // private boolean ignoreCase; // // StringEquatable(boolean ignoreCase) { // this.ignoreCase = ignoreCase; // } // // @Override // public boolean equals(String s1, String s2) { // if (s1 == null || s2 == null) { // //noinspection StringEquality // return s1 == s2; // } // if (ignoreCase) { // return s1.equalsIgnoreCase(s2); // } // return s1.equals(s2); // } // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/RawValue.java // public final class RawValue { // private final Raw annotation; // private final Object value; // // @Override // public String toString() { // return "FileValue{" + // "annotation=" + annotation + // ", value=" + value + // '}'; // } // // public RawValue(Raw annotation, Object value) { // this.annotation = annotation; // this.value = value; // } // // public <E extends Exception> Body body(RestConverter.Factory<E> converterFactory) throws E, IOException, // RestConverter.ConvertException { // if (value == null) return null; // //noinspection unchecked // final RestConverter<Object, Body, E> converter = // (RestConverter<Object, Body, E>) converterFactory.forRequest(value.getClass()); // if (converter != null) return converter.convert(value); // return SimpleBody.wrap(value); // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/ValueMap.java // public interface ValueMap { // // boolean has(@NotNull String key); // // @Nullable // Object get(@NotNull String key); // // @NotNull // String[] keys(); // // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.commons.collection.Pair; import org.mariotaku.restfu.http.BodyType; import org.mariotaku.restfu.http.MultiValueMap; import org.mariotaku.restfu.http.RawValue; import org.mariotaku.restfu.http.ValueMap; import org.mariotaku.restfu.http.mime.*; import java.io.IOException; import java.util.Map;
public String getMethod() { return method; } @NotNull private BodyConverter getBodyConverter() { assert this.bodyType != null; try { return bodyType.converter().newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } /** * <p> * Creates {@link RestRequest} from {@link RestMethod} * </p> * <p> * Use this method if you want to modify requests <b>before</b> normal HTTP request created. * </p> * <br> * <p> * When using OAuth authorization, this would be very useful, because normal HTTP request cannot * be modified once OAuth signature generated. * </p> */ public interface Factory<E extends Exception> { RestRequest create(@NotNull RestMethod<E> restMethod, @NotNull RestConverter.Factory<E> factory,
// Path: library/src/main/java/org/mariotaku/restfu/http/MultiValueMap.java // public final class MultiValueMap<V> extends MultiMap<String, V> { // // public MultiValueMap() { // this(new HashMap<String, List<V>>(), false); // } // // public MultiValueMap(Map<String, List<V>> map) { // this(map, false); // } // // public MultiValueMap(boolean ignoreCase) { // this(null, ignoreCase); // } // // public MultiValueMap(Map<String, List<V>> map, boolean ignoreCase) { // super(map, new StringEquatable(ignoreCase)); // } // // private static class StringEquatable implements Equatable<String> { // private boolean ignoreCase; // // StringEquatable(boolean ignoreCase) { // this.ignoreCase = ignoreCase; // } // // @Override // public boolean equals(String s1, String s2) { // if (s1 == null || s2 == null) { // //noinspection StringEquality // return s1 == s2; // } // if (ignoreCase) { // return s1.equalsIgnoreCase(s2); // } // return s1.equals(s2); // } // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/RawValue.java // public final class RawValue { // private final Raw annotation; // private final Object value; // // @Override // public String toString() { // return "FileValue{" + // "annotation=" + annotation + // ", value=" + value + // '}'; // } // // public RawValue(Raw annotation, Object value) { // this.annotation = annotation; // this.value = value; // } // // public <E extends Exception> Body body(RestConverter.Factory<E> converterFactory) throws E, IOException, // RestConverter.ConvertException { // if (value == null) return null; // //noinspection unchecked // final RestConverter<Object, Body, E> converter = // (RestConverter<Object, Body, E>) converterFactory.forRequest(value.getClass()); // if (converter != null) return converter.convert(value); // return SimpleBody.wrap(value); // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/ValueMap.java // public interface ValueMap { // // boolean has(@NotNull String key); // // @Nullable // Object get(@NotNull String key); // // @NotNull // String[] keys(); // // } // Path: library/src/main/java/org/mariotaku/restfu/RestRequest.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.commons.collection.Pair; import org.mariotaku.restfu.http.BodyType; import org.mariotaku.restfu.http.MultiValueMap; import org.mariotaku.restfu.http.RawValue; import org.mariotaku.restfu.http.ValueMap; import org.mariotaku.restfu.http.mime.*; import java.io.IOException; import java.util.Map; public String getMethod() { return method; } @NotNull private BodyConverter getBodyConverter() { assert this.bodyType != null; try { return bodyType.converter().newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } /** * <p> * Creates {@link RestRequest} from {@link RestMethod} * </p> * <p> * Use this method if you want to modify requests <b>before</b> normal HTTP request created. * </p> * <br> * <p> * When using OAuth authorization, this would be very useful, because normal HTTP request cannot * be modified once OAuth signature generated. * </p> */ public interface Factory<E extends Exception> { RestRequest create(@NotNull RestMethod<E> restMethod, @NotNull RestConverter.Factory<E> factory,
@Nullable ValueMap valuePool)
mariotaku/RestFu
library/src/test/java/org/mariotaku/restfu/http/mime/HttpRequestInfoExceptionFactory.java
// Path: library/src/main/java/org/mariotaku/restfu/ExceptionFactory.java // public interface ExceptionFactory<E extends Exception> { // // @NotNull // E newException(@Nullable final Throwable cause, @Nullable final HttpRequest request, // @Nullable final HttpResponse response); // // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.restfu.ExceptionFactory; import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.HttpResponse;
package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/3/25. */ class HttpRequestInfoExceptionFactory implements ExceptionFactory<HttpRequestInfoException> { @NotNull @Override
// Path: library/src/main/java/org/mariotaku/restfu/ExceptionFactory.java // public interface ExceptionFactory<E extends Exception> { // // @NotNull // E newException(@Nullable final Throwable cause, @Nullable final HttpRequest request, // @Nullable final HttpResponse response); // // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // } // Path: library/src/test/java/org/mariotaku/restfu/http/mime/HttpRequestInfoExceptionFactory.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.restfu.ExceptionFactory; import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.HttpResponse; package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/3/25. */ class HttpRequestInfoExceptionFactory implements ExceptionFactory<HttpRequestInfoException> { @NotNull @Override
public HttpRequestInfoException newException(@Nullable Throwable cause, @Nullable HttpRequest request, @Nullable HttpResponse response) {
mariotaku/RestFu
library/src/test/java/org/mariotaku/restfu/http/mime/HttpRequestInfoExceptionFactory.java
// Path: library/src/main/java/org/mariotaku/restfu/ExceptionFactory.java // public interface ExceptionFactory<E extends Exception> { // // @NotNull // E newException(@Nullable final Throwable cause, @Nullable final HttpRequest request, // @Nullable final HttpResponse response); // // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.restfu.ExceptionFactory; import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.HttpResponse;
package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/3/25. */ class HttpRequestInfoExceptionFactory implements ExceptionFactory<HttpRequestInfoException> { @NotNull @Override
// Path: library/src/main/java/org/mariotaku/restfu/ExceptionFactory.java // public interface ExceptionFactory<E extends Exception> { // // @NotNull // E newException(@Nullable final Throwable cause, @Nullable final HttpRequest request, // @Nullable final HttpResponse response); // // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpRequest.java // public final class HttpRequest { // // private final String method; // private final String url; // private final MultiValueMap<String> headers; // private final Body body; // private final Object tag; // // public String getMethod() { // return method; // } // // public String getUrl() { // return url; // } // // public MultiValueMap<String> getHeaders() { // return headers; // } // // public Body getBody() { // return body; // } // // public Object getTag() { // return tag; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(method); // sb.append(' '); // sb.append(url); // if (body != null) { // sb.append(" (has body)"); // } // return sb.toString(); // } // // public HttpRequest(String method, String url, MultiValueMap<String> headers, Body body, Object tag) { // this.method = method; // this.url = url; // this.headers = headers; // this.body = body; // this.tag = tag; // } // // public static final class Builder { // private String method; // private String url; // private MultiValueMap<String> headers; // private Body body; // private Object tag; // // public Builder() { // } // // public Builder method(String method) { // this.method = method; // return this; // } // // public Builder url(String url) { // this.url = url; // return this; // } // // public Builder headers(MultiValueMap<String> headers) { // this.headers = headers; // return this; // } // // public Builder body(Body body) { // this.body = body; // return this; // } // // public Builder tag(Object tag) { // this.tag = tag; // return this; // } // // public HttpRequest build() { // return new HttpRequest(method, url, headers, body, tag); // } // } // // // public static class DefaultFactory<E extends Exception> implements Factory<E> { // // @NotNull // @Override // public HttpRequest create(Endpoint endpoint, RestRequest requestInfo, // Authorization authorization, RestConverter.Factory<E> converterFactory) throws E, // RestConverter.ConvertException, IOException { // final String url = Endpoint.constructUrl(endpoint.getUrl(), requestInfo); // MultiValueMap<String> headers = requestInfo.getHeaders(); // if (headers == null) { // headers = new MultiValueMap<>(); // } // if (authorization != null && authorization.hasAuthorization()) { // headers.add("Authorization", authorization.getHeader(endpoint, requestInfo)); // } // return new HttpRequest(requestInfo.getMethod(), url, headers, requestInfo.getBody(converterFactory), null); // } // } // // /** // * Created by mariotaku on 15/5/25. // */ // public interface Factory<E extends Exception> { // @NotNull // HttpRequest create(Endpoint endpoint, RestRequest info, Authorization authorization, // RestConverter.Factory<E> converterFactory) throws E, RestConverter.ConvertException, IOException; // } // } // // Path: library/src/main/java/org/mariotaku/restfu/http/HttpResponse.java // public abstract class HttpResponse implements Closeable { // public abstract int getStatus(); // // public abstract MultiValueMap<String> getHeaders(); // // public abstract Body getBody(); // // public String getHeader(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().getFirst(name); // } // // public List<String> getHeaders(String name) { // if (name == null) throw new NullPointerException(); // return getHeaders().get(name); // } // // /** // * Returns true if the code is in [200..300), which means the request was // * successfully received, understood, and accepted. // * // * @return True if HTTP response is successful response // */ // public boolean isSuccessful() { // final int status = getStatus(); // return status >= 200 && status < 300; // } // // @Override // public String toString() { // return "HTTP " + getStatus(); // } // } // Path: library/src/test/java/org/mariotaku/restfu/http/mime/HttpRequestInfoExceptionFactory.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mariotaku.restfu.ExceptionFactory; import org.mariotaku.restfu.http.HttpRequest; import org.mariotaku.restfu.http.HttpResponse; package org.mariotaku.restfu.http.mime; /** * Created by mariotaku on 2017/3/25. */ class HttpRequestInfoExceptionFactory implements ExceptionFactory<HttpRequestInfoException> { @NotNull @Override
public HttpRequestInfoException newException(@Nullable Throwable cause, @Nullable HttpRequest request, @Nullable HttpResponse response) {
kiranreddykasa/springrest-angularjs
src/main/java/com/getit/todoapp/rest/FeedbackController.java
// Path: src/main/java/com/getit/todoapp/domain/Feedback.java // public class Feedback { // // private String email; // private String body; // // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // public String getBody() { // return body; // } // public void setBody(String body) { // this.body = body; // } // // // public static Feedback fromJsonToFeedback(String json) { // return new JSONDeserializer<Feedback>().use(null, Feedback.class).deserialize(json); // } // // } // // Path: src/main/java/com/getit/todoapp/service/EmailService.java // public interface EmailService { // StatusResponse send(Message message); // } // // Path: src/main/java/com/getit/todoapp/service/Message.java // public class Message implements Serializable { // // private static final long serialVersionUID = -4093981756240899937L; // private String senderName; // private String senderEmail; // private String ccEmail; // private String subject; // private String body; // private String receiverName; // private String receiverEmail; // // public Message() { // super(); // } // // public Message(String senderName, String senderEmail, String ccEmail, // String subject, String body, String receiverName, // String receiverEmail) { // super(); // this.senderName = senderName; // this.senderEmail = senderEmail; // this.ccEmail = ccEmail; // this.subject = subject; // this.body = body; // this.receiverName = receiverName; // this.receiverEmail = receiverEmail; // } // // public String getSenderName() { // return senderName; // } // // public void setSenderName(String senderName) { // this.senderName = senderName; // } // // public String getSenderEmail() { // return senderEmail; // } // // public void setSenderEmail(String senderEmail) { // this.senderEmail = senderEmail; // } // // public String getCcEmail() { // return ccEmail; // } // // public void setCcEmail(String ccEmail) { // this.ccEmail = ccEmail; // } // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getReceiverName() { // return receiverName; // } // // public void setReceiverName(String receiverName) { // this.receiverName = receiverName; // } // // public String getReceiverEmail() { // return receiverEmail; // } // // public void setReceiverEmail(String receiverEmail) { // this.receiverEmail = receiverEmail; // } // // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.getit.todoapp.domain.Feedback; import com.getit.todoapp.service.EmailService; import com.getit.todoapp.service.Message;
package com.getit.todoapp.rest; @Controller @RequestMapping("/feedback") public class FeedbackController { @Autowired
// Path: src/main/java/com/getit/todoapp/domain/Feedback.java // public class Feedback { // // private String email; // private String body; // // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // public String getBody() { // return body; // } // public void setBody(String body) { // this.body = body; // } // // // public static Feedback fromJsonToFeedback(String json) { // return new JSONDeserializer<Feedback>().use(null, Feedback.class).deserialize(json); // } // // } // // Path: src/main/java/com/getit/todoapp/service/EmailService.java // public interface EmailService { // StatusResponse send(Message message); // } // // Path: src/main/java/com/getit/todoapp/service/Message.java // public class Message implements Serializable { // // private static final long serialVersionUID = -4093981756240899937L; // private String senderName; // private String senderEmail; // private String ccEmail; // private String subject; // private String body; // private String receiverName; // private String receiverEmail; // // public Message() { // super(); // } // // public Message(String senderName, String senderEmail, String ccEmail, // String subject, String body, String receiverName, // String receiverEmail) { // super(); // this.senderName = senderName; // this.senderEmail = senderEmail; // this.ccEmail = ccEmail; // this.subject = subject; // this.body = body; // this.receiverName = receiverName; // this.receiverEmail = receiverEmail; // } // // public String getSenderName() { // return senderName; // } // // public void setSenderName(String senderName) { // this.senderName = senderName; // } // // public String getSenderEmail() { // return senderEmail; // } // // public void setSenderEmail(String senderEmail) { // this.senderEmail = senderEmail; // } // // public String getCcEmail() { // return ccEmail; // } // // public void setCcEmail(String ccEmail) { // this.ccEmail = ccEmail; // } // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getReceiverName() { // return receiverName; // } // // public void setReceiverName(String receiverName) { // this.receiverName = receiverName; // } // // public String getReceiverEmail() { // return receiverEmail; // } // // public void setReceiverEmail(String receiverEmail) { // this.receiverEmail = receiverEmail; // } // // } // Path: src/main/java/com/getit/todoapp/rest/FeedbackController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.getit.todoapp.domain.Feedback; import com.getit.todoapp.service.EmailService; import com.getit.todoapp.service.Message; package com.getit.todoapp.rest; @Controller @RequestMapping("/feedback") public class FeedbackController { @Autowired
private EmailService emailService;
kiranreddykasa/springrest-angularjs
src/main/java/com/getit/todoapp/rest/FeedbackController.java
// Path: src/main/java/com/getit/todoapp/domain/Feedback.java // public class Feedback { // // private String email; // private String body; // // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // public String getBody() { // return body; // } // public void setBody(String body) { // this.body = body; // } // // // public static Feedback fromJsonToFeedback(String json) { // return new JSONDeserializer<Feedback>().use(null, Feedback.class).deserialize(json); // } // // } // // Path: src/main/java/com/getit/todoapp/service/EmailService.java // public interface EmailService { // StatusResponse send(Message message); // } // // Path: src/main/java/com/getit/todoapp/service/Message.java // public class Message implements Serializable { // // private static final long serialVersionUID = -4093981756240899937L; // private String senderName; // private String senderEmail; // private String ccEmail; // private String subject; // private String body; // private String receiverName; // private String receiverEmail; // // public Message() { // super(); // } // // public Message(String senderName, String senderEmail, String ccEmail, // String subject, String body, String receiverName, // String receiverEmail) { // super(); // this.senderName = senderName; // this.senderEmail = senderEmail; // this.ccEmail = ccEmail; // this.subject = subject; // this.body = body; // this.receiverName = receiverName; // this.receiverEmail = receiverEmail; // } // // public String getSenderName() { // return senderName; // } // // public void setSenderName(String senderName) { // this.senderName = senderName; // } // // public String getSenderEmail() { // return senderEmail; // } // // public void setSenderEmail(String senderEmail) { // this.senderEmail = senderEmail; // } // // public String getCcEmail() { // return ccEmail; // } // // public void setCcEmail(String ccEmail) { // this.ccEmail = ccEmail; // } // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getReceiverName() { // return receiverName; // } // // public void setReceiverName(String receiverName) { // this.receiverName = receiverName; // } // // public String getReceiverEmail() { // return receiverEmail; // } // // public void setReceiverEmail(String receiverEmail) { // this.receiverEmail = receiverEmail; // } // // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.getit.todoapp.domain.Feedback; import com.getit.todoapp.service.EmailService; import com.getit.todoapp.service.Message;
package com.getit.todoapp.rest; @Controller @RequestMapping("/feedback") public class FeedbackController { @Autowired private EmailService emailService; @RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json") public ResponseEntity<String> createFromJson(@RequestBody String json) {
// Path: src/main/java/com/getit/todoapp/domain/Feedback.java // public class Feedback { // // private String email; // private String body; // // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // public String getBody() { // return body; // } // public void setBody(String body) { // this.body = body; // } // // // public static Feedback fromJsonToFeedback(String json) { // return new JSONDeserializer<Feedback>().use(null, Feedback.class).deserialize(json); // } // // } // // Path: src/main/java/com/getit/todoapp/service/EmailService.java // public interface EmailService { // StatusResponse send(Message message); // } // // Path: src/main/java/com/getit/todoapp/service/Message.java // public class Message implements Serializable { // // private static final long serialVersionUID = -4093981756240899937L; // private String senderName; // private String senderEmail; // private String ccEmail; // private String subject; // private String body; // private String receiverName; // private String receiverEmail; // // public Message() { // super(); // } // // public Message(String senderName, String senderEmail, String ccEmail, // String subject, String body, String receiverName, // String receiverEmail) { // super(); // this.senderName = senderName; // this.senderEmail = senderEmail; // this.ccEmail = ccEmail; // this.subject = subject; // this.body = body; // this.receiverName = receiverName; // this.receiverEmail = receiverEmail; // } // // public String getSenderName() { // return senderName; // } // // public void setSenderName(String senderName) { // this.senderName = senderName; // } // // public String getSenderEmail() { // return senderEmail; // } // // public void setSenderEmail(String senderEmail) { // this.senderEmail = senderEmail; // } // // public String getCcEmail() { // return ccEmail; // } // // public void setCcEmail(String ccEmail) { // this.ccEmail = ccEmail; // } // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getReceiverName() { // return receiverName; // } // // public void setReceiverName(String receiverName) { // this.receiverName = receiverName; // } // // public String getReceiverEmail() { // return receiverEmail; // } // // public void setReceiverEmail(String receiverEmail) { // this.receiverEmail = receiverEmail; // } // // } // Path: src/main/java/com/getit/todoapp/rest/FeedbackController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.getit.todoapp.domain.Feedback; import com.getit.todoapp.service.EmailService; import com.getit.todoapp.service.Message; package com.getit.todoapp.rest; @Controller @RequestMapping("/feedback") public class FeedbackController { @Autowired private EmailService emailService; @RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json") public ResponseEntity<String> createFromJson(@RequestBody String json) {
Feedback feedback = Feedback.fromJsonToFeedback(json);
kiranreddykasa/springrest-angularjs
src/main/java/com/getit/todoapp/rest/FeedbackController.java
// Path: src/main/java/com/getit/todoapp/domain/Feedback.java // public class Feedback { // // private String email; // private String body; // // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // public String getBody() { // return body; // } // public void setBody(String body) { // this.body = body; // } // // // public static Feedback fromJsonToFeedback(String json) { // return new JSONDeserializer<Feedback>().use(null, Feedback.class).deserialize(json); // } // // } // // Path: src/main/java/com/getit/todoapp/service/EmailService.java // public interface EmailService { // StatusResponse send(Message message); // } // // Path: src/main/java/com/getit/todoapp/service/Message.java // public class Message implements Serializable { // // private static final long serialVersionUID = -4093981756240899937L; // private String senderName; // private String senderEmail; // private String ccEmail; // private String subject; // private String body; // private String receiverName; // private String receiverEmail; // // public Message() { // super(); // } // // public Message(String senderName, String senderEmail, String ccEmail, // String subject, String body, String receiverName, // String receiverEmail) { // super(); // this.senderName = senderName; // this.senderEmail = senderEmail; // this.ccEmail = ccEmail; // this.subject = subject; // this.body = body; // this.receiverName = receiverName; // this.receiverEmail = receiverEmail; // } // // public String getSenderName() { // return senderName; // } // // public void setSenderName(String senderName) { // this.senderName = senderName; // } // // public String getSenderEmail() { // return senderEmail; // } // // public void setSenderEmail(String senderEmail) { // this.senderEmail = senderEmail; // } // // public String getCcEmail() { // return ccEmail; // } // // public void setCcEmail(String ccEmail) { // this.ccEmail = ccEmail; // } // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getReceiverName() { // return receiverName; // } // // public void setReceiverName(String receiverName) { // this.receiverName = receiverName; // } // // public String getReceiverEmail() { // return receiverEmail; // } // // public void setReceiverEmail(String receiverEmail) { // this.receiverEmail = receiverEmail; // } // // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.getit.todoapp.domain.Feedback; import com.getit.todoapp.service.EmailService; import com.getit.todoapp.service.Message;
package com.getit.todoapp.rest; @Controller @RequestMapping("/feedback") public class FeedbackController { @Autowired private EmailService emailService; @RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json") public ResponseEntity<String> createFromJson(@RequestBody String json) { Feedback feedback = Feedback.fromJsonToFeedback(json);
// Path: src/main/java/com/getit/todoapp/domain/Feedback.java // public class Feedback { // // private String email; // private String body; // // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // public String getBody() { // return body; // } // public void setBody(String body) { // this.body = body; // } // // // public static Feedback fromJsonToFeedback(String json) { // return new JSONDeserializer<Feedback>().use(null, Feedback.class).deserialize(json); // } // // } // // Path: src/main/java/com/getit/todoapp/service/EmailService.java // public interface EmailService { // StatusResponse send(Message message); // } // // Path: src/main/java/com/getit/todoapp/service/Message.java // public class Message implements Serializable { // // private static final long serialVersionUID = -4093981756240899937L; // private String senderName; // private String senderEmail; // private String ccEmail; // private String subject; // private String body; // private String receiverName; // private String receiverEmail; // // public Message() { // super(); // } // // public Message(String senderName, String senderEmail, String ccEmail, // String subject, String body, String receiverName, // String receiverEmail) { // super(); // this.senderName = senderName; // this.senderEmail = senderEmail; // this.ccEmail = ccEmail; // this.subject = subject; // this.body = body; // this.receiverName = receiverName; // this.receiverEmail = receiverEmail; // } // // public String getSenderName() { // return senderName; // } // // public void setSenderName(String senderName) { // this.senderName = senderName; // } // // public String getSenderEmail() { // return senderEmail; // } // // public void setSenderEmail(String senderEmail) { // this.senderEmail = senderEmail; // } // // public String getCcEmail() { // return ccEmail; // } // // public void setCcEmail(String ccEmail) { // this.ccEmail = ccEmail; // } // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject; // } // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getReceiverName() { // return receiverName; // } // // public void setReceiverName(String receiverName) { // this.receiverName = receiverName; // } // // public String getReceiverEmail() { // return receiverEmail; // } // // public void setReceiverEmail(String receiverEmail) { // this.receiverEmail = receiverEmail; // } // // } // Path: src/main/java/com/getit/todoapp/rest/FeedbackController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.getit.todoapp.domain.Feedback; import com.getit.todoapp.service.EmailService; import com.getit.todoapp.service.Message; package com.getit.todoapp.rest; @Controller @RequestMapping("/feedback") public class FeedbackController { @Autowired private EmailService emailService; @RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json") public ResponseEntity<String> createFromJson(@RequestBody String json) { Feedback feedback = Feedback.fromJsonToFeedback(json);
Message message=new Message();
kiranreddykasa/springrest-angularjs
src/test/java/com/getit/todoapp/domain/UserinfoDataOnDemand.java
// Path: src/main/java/com/getit/todoapp/repository/UserRepository.java // @Repository // @RooJpaRepository(domainType = Userinfo.class) // public interface UserRepository extends JpaSpecificationExecutor<Userinfo>, JpaRepository<Userinfo, Long> { // // List<Userinfo> findByUserName(String userName); // } // // Path: src/main/java/com/getit/todoapp/service/UserService.java // @RooService(domainTypes = { com.getit.todoapp.domain.Userinfo.class }) // public interface UserService { // // List<Userinfo> findByUserName(String userName); // // public abstract long countAllUserinfoes(); // // // public abstract void deleteUserinfo(Userinfo userinfo); // // // public abstract Userinfo findUserinfo(Long id); // // // public abstract List<Userinfo> findAllUserinfoes(); // // // public abstract List<Userinfo> findUserinfoEntries(int firstResult, int maxResults); // // // public abstract void saveUserinfo(Userinfo userinfo); // // // public abstract Userinfo updateUserinfo(Userinfo userinfo); // // }
import com.getit.todoapp.repository.UserRepository; import com.getit.todoapp.service.UserService; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.roo.addon.dod.RooDataOnDemand; import org.springframework.stereotype.Component;
package com.getit.todoapp.domain; @Component @Configurable @RooDataOnDemand(entity = Userinfo.class) public class UserinfoDataOnDemand { private Random rnd = new SecureRandom(); private List<Userinfo> data; @Autowired
// Path: src/main/java/com/getit/todoapp/repository/UserRepository.java // @Repository // @RooJpaRepository(domainType = Userinfo.class) // public interface UserRepository extends JpaSpecificationExecutor<Userinfo>, JpaRepository<Userinfo, Long> { // // List<Userinfo> findByUserName(String userName); // } // // Path: src/main/java/com/getit/todoapp/service/UserService.java // @RooService(domainTypes = { com.getit.todoapp.domain.Userinfo.class }) // public interface UserService { // // List<Userinfo> findByUserName(String userName); // // public abstract long countAllUserinfoes(); // // // public abstract void deleteUserinfo(Userinfo userinfo); // // // public abstract Userinfo findUserinfo(Long id); // // // public abstract List<Userinfo> findAllUserinfoes(); // // // public abstract List<Userinfo> findUserinfoEntries(int firstResult, int maxResults); // // // public abstract void saveUserinfo(Userinfo userinfo); // // // public abstract Userinfo updateUserinfo(Userinfo userinfo); // // } // Path: src/test/java/com/getit/todoapp/domain/UserinfoDataOnDemand.java import com.getit.todoapp.repository.UserRepository; import com.getit.todoapp.service.UserService; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.roo.addon.dod.RooDataOnDemand; import org.springframework.stereotype.Component; package com.getit.todoapp.domain; @Component @Configurable @RooDataOnDemand(entity = Userinfo.class) public class UserinfoDataOnDemand { private Random rnd = new SecureRandom(); private List<Userinfo> data; @Autowired
UserService userService;
kiranreddykasa/springrest-angularjs
src/test/java/com/getit/todoapp/domain/UserinfoDataOnDemand.java
// Path: src/main/java/com/getit/todoapp/repository/UserRepository.java // @Repository // @RooJpaRepository(domainType = Userinfo.class) // public interface UserRepository extends JpaSpecificationExecutor<Userinfo>, JpaRepository<Userinfo, Long> { // // List<Userinfo> findByUserName(String userName); // } // // Path: src/main/java/com/getit/todoapp/service/UserService.java // @RooService(domainTypes = { com.getit.todoapp.domain.Userinfo.class }) // public interface UserService { // // List<Userinfo> findByUserName(String userName); // // public abstract long countAllUserinfoes(); // // // public abstract void deleteUserinfo(Userinfo userinfo); // // // public abstract Userinfo findUserinfo(Long id); // // // public abstract List<Userinfo> findAllUserinfoes(); // // // public abstract List<Userinfo> findUserinfoEntries(int firstResult, int maxResults); // // // public abstract void saveUserinfo(Userinfo userinfo); // // // public abstract Userinfo updateUserinfo(Userinfo userinfo); // // }
import com.getit.todoapp.repository.UserRepository; import com.getit.todoapp.service.UserService; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.roo.addon.dod.RooDataOnDemand; import org.springframework.stereotype.Component;
package com.getit.todoapp.domain; @Component @Configurable @RooDataOnDemand(entity = Userinfo.class) public class UserinfoDataOnDemand { private Random rnd = new SecureRandom(); private List<Userinfo> data; @Autowired UserService userService; @Autowired
// Path: src/main/java/com/getit/todoapp/repository/UserRepository.java // @Repository // @RooJpaRepository(domainType = Userinfo.class) // public interface UserRepository extends JpaSpecificationExecutor<Userinfo>, JpaRepository<Userinfo, Long> { // // List<Userinfo> findByUserName(String userName); // } // // Path: src/main/java/com/getit/todoapp/service/UserService.java // @RooService(domainTypes = { com.getit.todoapp.domain.Userinfo.class }) // public interface UserService { // // List<Userinfo> findByUserName(String userName); // // public abstract long countAllUserinfoes(); // // // public abstract void deleteUserinfo(Userinfo userinfo); // // // public abstract Userinfo findUserinfo(Long id); // // // public abstract List<Userinfo> findAllUserinfoes(); // // // public abstract List<Userinfo> findUserinfoEntries(int firstResult, int maxResults); // // // public abstract void saveUserinfo(Userinfo userinfo); // // // public abstract Userinfo updateUserinfo(Userinfo userinfo); // // } // Path: src/test/java/com/getit/todoapp/domain/UserinfoDataOnDemand.java import com.getit.todoapp.repository.UserRepository; import com.getit.todoapp.service.UserService; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.roo.addon.dod.RooDataOnDemand; import org.springframework.stereotype.Component; package com.getit.todoapp.domain; @Component @Configurable @RooDataOnDemand(entity = Userinfo.class) public class UserinfoDataOnDemand { private Random rnd = new SecureRandom(); private List<Userinfo> data; @Autowired UserService userService; @Autowired
UserRepository userRepository;
kiranreddykasa/springrest-angularjs
src/main/java/com/getit/todoapp/service/TodoServiceImpl.java
// Path: src/main/java/com/getit/todoapp/domain/Todo.java // @Entity // @RooJavaBean // @RooToString // @RooJpaEntity // @RooJson // public class Todo { // private static final String CLASS_EXTENSION = "*.class"; // // /** // */ // @NotNull // private String name; // // /** // */ // @NotNull // @Temporal(TemporalType.TIMESTAMP) // @DateTimeFormat(style = "M-") // private Date targetDate; // // /** // */ // private Boolean isCompleted; // // /** // */ // @Enumerated // private Priority priority; // // /** // */ // @ManyToOne // private Userinfo userName; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "id") // private Long id; // // @Version // @Column(name = "version") // private Integer version; // // public String toJson() { // return new JSONSerializer().exclude(CLASS_EXTENSION).transform(new DateTransformer("MM/dd/yyyy"), Date.class).serialize(this); // } // // public String toJson(String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(this); // } // // public static Todo fromJsonToTodo(String json) { // return new JSONDeserializer<Todo>().use(null, Todo.class).deserialize(json); // } // // public static String toJsonArray(Collection<Todo> collection) { // return new JSONSerializer().exclude(CLASS_EXTENSION).transform(new DateTransformer("MM/dd/yyyy"), Date.class).serialize(collection); // } // // public static String toJsonArray(Collection<Todo> collection, String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(collection); // } // // public static Collection<Todo> fromJsonArrayToTodoes(String json) { // return new JSONDeserializer<List<Todo>>().use(null, ArrayList.class).use("values", Todo.class).deserialize(json); // } // // // // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public Integer getVersion() { // return this.version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // public Date getTargetDate() { // return this.targetDate; // } // // public void setTargetDate(Date targetDate) { // this.targetDate = targetDate; // } // // public Boolean getIsCompleted() { // return this.isCompleted; // } // // public void setIsCompleted(Boolean isCompleted) { // this.isCompleted = isCompleted; // } // // public Priority getPriority() { // return this.priority; // } // // public void setPriority(Priority priority) { // this.priority = priority; // } // // public Userinfo getUserName() { // return this.userName; // } // // public void setUserName(Userinfo userName) { // this.userName = userName; // } // } // // Path: src/main/java/com/getit/todoapp/repository/TodoRepository.java // @Repository // @RooJpaRepository(domainType = Todo.class) // public interface TodoRepository extends JpaSpecificationExecutor<Todo>, JpaRepository<Todo, Long> { // // @Query("select t from Todo t where t.userName.userName = ?1") // List<Todo> findTodosByUserName(String userName); // // @Query("select t from Todo t where t.userName.userName = ?1 and t.id= ?2") // Todo findTodoByUserNameAndId(String userName,Long id); // }
import com.getit.todoapp.domain.Todo; import com.getit.todoapp.repository.TodoRepository; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;
package com.getit.todoapp.service; @Service @Transactional public class TodoServiceImpl implements TodoService { @Autowired
// Path: src/main/java/com/getit/todoapp/domain/Todo.java // @Entity // @RooJavaBean // @RooToString // @RooJpaEntity // @RooJson // public class Todo { // private static final String CLASS_EXTENSION = "*.class"; // // /** // */ // @NotNull // private String name; // // /** // */ // @NotNull // @Temporal(TemporalType.TIMESTAMP) // @DateTimeFormat(style = "M-") // private Date targetDate; // // /** // */ // private Boolean isCompleted; // // /** // */ // @Enumerated // private Priority priority; // // /** // */ // @ManyToOne // private Userinfo userName; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "id") // private Long id; // // @Version // @Column(name = "version") // private Integer version; // // public String toJson() { // return new JSONSerializer().exclude(CLASS_EXTENSION).transform(new DateTransformer("MM/dd/yyyy"), Date.class).serialize(this); // } // // public String toJson(String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(this); // } // // public static Todo fromJsonToTodo(String json) { // return new JSONDeserializer<Todo>().use(null, Todo.class).deserialize(json); // } // // public static String toJsonArray(Collection<Todo> collection) { // return new JSONSerializer().exclude(CLASS_EXTENSION).transform(new DateTransformer("MM/dd/yyyy"), Date.class).serialize(collection); // } // // public static String toJsonArray(Collection<Todo> collection, String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(collection); // } // // public static Collection<Todo> fromJsonArrayToTodoes(String json) { // return new JSONDeserializer<List<Todo>>().use(null, ArrayList.class).use("values", Todo.class).deserialize(json); // } // // // // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public Integer getVersion() { // return this.version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // public Date getTargetDate() { // return this.targetDate; // } // // public void setTargetDate(Date targetDate) { // this.targetDate = targetDate; // } // // public Boolean getIsCompleted() { // return this.isCompleted; // } // // public void setIsCompleted(Boolean isCompleted) { // this.isCompleted = isCompleted; // } // // public Priority getPriority() { // return this.priority; // } // // public void setPriority(Priority priority) { // this.priority = priority; // } // // public Userinfo getUserName() { // return this.userName; // } // // public void setUserName(Userinfo userName) { // this.userName = userName; // } // } // // Path: src/main/java/com/getit/todoapp/repository/TodoRepository.java // @Repository // @RooJpaRepository(domainType = Todo.class) // public interface TodoRepository extends JpaSpecificationExecutor<Todo>, JpaRepository<Todo, Long> { // // @Query("select t from Todo t where t.userName.userName = ?1") // List<Todo> findTodosByUserName(String userName); // // @Query("select t from Todo t where t.userName.userName = ?1 and t.id= ?2") // Todo findTodoByUserNameAndId(String userName,Long id); // } // Path: src/main/java/com/getit/todoapp/service/TodoServiceImpl.java import com.getit.todoapp.domain.Todo; import com.getit.todoapp.repository.TodoRepository; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; package com.getit.todoapp.service; @Service @Transactional public class TodoServiceImpl implements TodoService { @Autowired
private TodoRepository todoRepository;
kiranreddykasa/springrest-angularjs
src/main/java/com/getit/todoapp/service/TodoServiceImpl.java
// Path: src/main/java/com/getit/todoapp/domain/Todo.java // @Entity // @RooJavaBean // @RooToString // @RooJpaEntity // @RooJson // public class Todo { // private static final String CLASS_EXTENSION = "*.class"; // // /** // */ // @NotNull // private String name; // // /** // */ // @NotNull // @Temporal(TemporalType.TIMESTAMP) // @DateTimeFormat(style = "M-") // private Date targetDate; // // /** // */ // private Boolean isCompleted; // // /** // */ // @Enumerated // private Priority priority; // // /** // */ // @ManyToOne // private Userinfo userName; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "id") // private Long id; // // @Version // @Column(name = "version") // private Integer version; // // public String toJson() { // return new JSONSerializer().exclude(CLASS_EXTENSION).transform(new DateTransformer("MM/dd/yyyy"), Date.class).serialize(this); // } // // public String toJson(String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(this); // } // // public static Todo fromJsonToTodo(String json) { // return new JSONDeserializer<Todo>().use(null, Todo.class).deserialize(json); // } // // public static String toJsonArray(Collection<Todo> collection) { // return new JSONSerializer().exclude(CLASS_EXTENSION).transform(new DateTransformer("MM/dd/yyyy"), Date.class).serialize(collection); // } // // public static String toJsonArray(Collection<Todo> collection, String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(collection); // } // // public static Collection<Todo> fromJsonArrayToTodoes(String json) { // return new JSONDeserializer<List<Todo>>().use(null, ArrayList.class).use("values", Todo.class).deserialize(json); // } // // // // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public Integer getVersion() { // return this.version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // public Date getTargetDate() { // return this.targetDate; // } // // public void setTargetDate(Date targetDate) { // this.targetDate = targetDate; // } // // public Boolean getIsCompleted() { // return this.isCompleted; // } // // public void setIsCompleted(Boolean isCompleted) { // this.isCompleted = isCompleted; // } // // public Priority getPriority() { // return this.priority; // } // // public void setPriority(Priority priority) { // this.priority = priority; // } // // public Userinfo getUserName() { // return this.userName; // } // // public void setUserName(Userinfo userName) { // this.userName = userName; // } // } // // Path: src/main/java/com/getit/todoapp/repository/TodoRepository.java // @Repository // @RooJpaRepository(domainType = Todo.class) // public interface TodoRepository extends JpaSpecificationExecutor<Todo>, JpaRepository<Todo, Long> { // // @Query("select t from Todo t where t.userName.userName = ?1") // List<Todo> findTodosByUserName(String userName); // // @Query("select t from Todo t where t.userName.userName = ?1 and t.id= ?2") // Todo findTodoByUserNameAndId(String userName,Long id); // }
import com.getit.todoapp.domain.Todo; import com.getit.todoapp.repository.TodoRepository; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;
package com.getit.todoapp.service; @Service @Transactional public class TodoServiceImpl implements TodoService { @Autowired private TodoRepository todoRepository; public long countAllTodoes() { return todoRepository.count(); }
// Path: src/main/java/com/getit/todoapp/domain/Todo.java // @Entity // @RooJavaBean // @RooToString // @RooJpaEntity // @RooJson // public class Todo { // private static final String CLASS_EXTENSION = "*.class"; // // /** // */ // @NotNull // private String name; // // /** // */ // @NotNull // @Temporal(TemporalType.TIMESTAMP) // @DateTimeFormat(style = "M-") // private Date targetDate; // // /** // */ // private Boolean isCompleted; // // /** // */ // @Enumerated // private Priority priority; // // /** // */ // @ManyToOne // private Userinfo userName; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "id") // private Long id; // // @Version // @Column(name = "version") // private Integer version; // // public String toJson() { // return new JSONSerializer().exclude(CLASS_EXTENSION).transform(new DateTransformer("MM/dd/yyyy"), Date.class).serialize(this); // } // // public String toJson(String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(this); // } // // public static Todo fromJsonToTodo(String json) { // return new JSONDeserializer<Todo>().use(null, Todo.class).deserialize(json); // } // // public static String toJsonArray(Collection<Todo> collection) { // return new JSONSerializer().exclude(CLASS_EXTENSION).transform(new DateTransformer("MM/dd/yyyy"), Date.class).serialize(collection); // } // // public static String toJsonArray(Collection<Todo> collection, String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(collection); // } // // public static Collection<Todo> fromJsonArrayToTodoes(String json) { // return new JSONDeserializer<List<Todo>>().use(null, ArrayList.class).use("values", Todo.class).deserialize(json); // } // // // // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public Integer getVersion() { // return this.version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // public Date getTargetDate() { // return this.targetDate; // } // // public void setTargetDate(Date targetDate) { // this.targetDate = targetDate; // } // // public Boolean getIsCompleted() { // return this.isCompleted; // } // // public void setIsCompleted(Boolean isCompleted) { // this.isCompleted = isCompleted; // } // // public Priority getPriority() { // return this.priority; // } // // public void setPriority(Priority priority) { // this.priority = priority; // } // // public Userinfo getUserName() { // return this.userName; // } // // public void setUserName(Userinfo userName) { // this.userName = userName; // } // } // // Path: src/main/java/com/getit/todoapp/repository/TodoRepository.java // @Repository // @RooJpaRepository(domainType = Todo.class) // public interface TodoRepository extends JpaSpecificationExecutor<Todo>, JpaRepository<Todo, Long> { // // @Query("select t from Todo t where t.userName.userName = ?1") // List<Todo> findTodosByUserName(String userName); // // @Query("select t from Todo t where t.userName.userName = ?1 and t.id= ?2") // Todo findTodoByUserNameAndId(String userName,Long id); // } // Path: src/main/java/com/getit/todoapp/service/TodoServiceImpl.java import com.getit.todoapp.domain.Todo; import com.getit.todoapp.repository.TodoRepository; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; package com.getit.todoapp.service; @Service @Transactional public class TodoServiceImpl implements TodoService { @Autowired private TodoRepository todoRepository; public long countAllTodoes() { return todoRepository.count(); }
public void deleteTodo(Todo todo) {
kiranreddykasa/springrest-angularjs
src/test/java/com/getit/todoapp/domain/TodoIntegrationTest.java
// Path: src/main/java/com/getit/todoapp/repository/TodoRepository.java // @Repository // @RooJpaRepository(domainType = Todo.class) // public interface TodoRepository extends JpaSpecificationExecutor<Todo>, JpaRepository<Todo, Long> { // // @Query("select t from Todo t where t.userName.userName = ?1") // List<Todo> findTodosByUserName(String userName); // // @Query("select t from Todo t where t.userName.userName = ?1 and t.id= ?2") // Todo findTodoByUserNameAndId(String userName,Long id); // } // // Path: src/main/java/com/getit/todoapp/service/TodoService.java // @RooService(domainTypes = { com.getit.todoapp.domain.Todo.class }) // public interface TodoService { // // public abstract long countAllTodoes(); // // // public abstract void deleteTodo(Todo todo); // // // public abstract Todo findTodo(Long id); // // // public abstract List<Todo> findAllTodoes(); // // // public abstract List<Todo> findTodoEntries(int firstResult, int maxResults); // // // public abstract void saveTodo(Todo todo); // // // public abstract Todo updateTodo(Todo todo); // // public abstract List<Todo> findTodosByUserName(String userName); // // public abstract Todo findTodoByUserNameAndId(String userName,Long id); // }
import com.getit.todoapp.repository.TodoRepository; import com.getit.todoapp.service.TodoService; import java.util.Iterator; import java.util.List; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.roo.addon.test.RooIntegrationTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional;
package com.getit.todoapp.domain; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath*:/META-INF/spring/applicationContext*.xml") @Transactional @Configurable @RooIntegrationTest(entity = Todo.class) public class TodoIntegrationTest { @Test public void testMarkerMethod() { } @Autowired TodoDataOnDemand dod; @Autowired
// Path: src/main/java/com/getit/todoapp/repository/TodoRepository.java // @Repository // @RooJpaRepository(domainType = Todo.class) // public interface TodoRepository extends JpaSpecificationExecutor<Todo>, JpaRepository<Todo, Long> { // // @Query("select t from Todo t where t.userName.userName = ?1") // List<Todo> findTodosByUserName(String userName); // // @Query("select t from Todo t where t.userName.userName = ?1 and t.id= ?2") // Todo findTodoByUserNameAndId(String userName,Long id); // } // // Path: src/main/java/com/getit/todoapp/service/TodoService.java // @RooService(domainTypes = { com.getit.todoapp.domain.Todo.class }) // public interface TodoService { // // public abstract long countAllTodoes(); // // // public abstract void deleteTodo(Todo todo); // // // public abstract Todo findTodo(Long id); // // // public abstract List<Todo> findAllTodoes(); // // // public abstract List<Todo> findTodoEntries(int firstResult, int maxResults); // // // public abstract void saveTodo(Todo todo); // // // public abstract Todo updateTodo(Todo todo); // // public abstract List<Todo> findTodosByUserName(String userName); // // public abstract Todo findTodoByUserNameAndId(String userName,Long id); // } // Path: src/test/java/com/getit/todoapp/domain/TodoIntegrationTest.java import com.getit.todoapp.repository.TodoRepository; import com.getit.todoapp.service.TodoService; import java.util.Iterator; import java.util.List; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.roo.addon.test.RooIntegrationTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; package com.getit.todoapp.domain; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath*:/META-INF/spring/applicationContext*.xml") @Transactional @Configurable @RooIntegrationTest(entity = Todo.class) public class TodoIntegrationTest { @Test public void testMarkerMethod() { } @Autowired TodoDataOnDemand dod; @Autowired
TodoService todoService;
kiranreddykasa/springrest-angularjs
src/test/java/com/getit/todoapp/domain/TodoIntegrationTest.java
// Path: src/main/java/com/getit/todoapp/repository/TodoRepository.java // @Repository // @RooJpaRepository(domainType = Todo.class) // public interface TodoRepository extends JpaSpecificationExecutor<Todo>, JpaRepository<Todo, Long> { // // @Query("select t from Todo t where t.userName.userName = ?1") // List<Todo> findTodosByUserName(String userName); // // @Query("select t from Todo t where t.userName.userName = ?1 and t.id= ?2") // Todo findTodoByUserNameAndId(String userName,Long id); // } // // Path: src/main/java/com/getit/todoapp/service/TodoService.java // @RooService(domainTypes = { com.getit.todoapp.domain.Todo.class }) // public interface TodoService { // // public abstract long countAllTodoes(); // // // public abstract void deleteTodo(Todo todo); // // // public abstract Todo findTodo(Long id); // // // public abstract List<Todo> findAllTodoes(); // // // public abstract List<Todo> findTodoEntries(int firstResult, int maxResults); // // // public abstract void saveTodo(Todo todo); // // // public abstract Todo updateTodo(Todo todo); // // public abstract List<Todo> findTodosByUserName(String userName); // // public abstract Todo findTodoByUserNameAndId(String userName,Long id); // }
import com.getit.todoapp.repository.TodoRepository; import com.getit.todoapp.service.TodoService; import java.util.Iterator; import java.util.List; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.roo.addon.test.RooIntegrationTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional;
package com.getit.todoapp.domain; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath*:/META-INF/spring/applicationContext*.xml") @Transactional @Configurable @RooIntegrationTest(entity = Todo.class) public class TodoIntegrationTest { @Test public void testMarkerMethod() { } @Autowired TodoDataOnDemand dod; @Autowired TodoService todoService; @Autowired
// Path: src/main/java/com/getit/todoapp/repository/TodoRepository.java // @Repository // @RooJpaRepository(domainType = Todo.class) // public interface TodoRepository extends JpaSpecificationExecutor<Todo>, JpaRepository<Todo, Long> { // // @Query("select t from Todo t where t.userName.userName = ?1") // List<Todo> findTodosByUserName(String userName); // // @Query("select t from Todo t where t.userName.userName = ?1 and t.id= ?2") // Todo findTodoByUserNameAndId(String userName,Long id); // } // // Path: src/main/java/com/getit/todoapp/service/TodoService.java // @RooService(domainTypes = { com.getit.todoapp.domain.Todo.class }) // public interface TodoService { // // public abstract long countAllTodoes(); // // // public abstract void deleteTodo(Todo todo); // // // public abstract Todo findTodo(Long id); // // // public abstract List<Todo> findAllTodoes(); // // // public abstract List<Todo> findTodoEntries(int firstResult, int maxResults); // // // public abstract void saveTodo(Todo todo); // // // public abstract Todo updateTodo(Todo todo); // // public abstract List<Todo> findTodosByUserName(String userName); // // public abstract Todo findTodoByUserNameAndId(String userName,Long id); // } // Path: src/test/java/com/getit/todoapp/domain/TodoIntegrationTest.java import com.getit.todoapp.repository.TodoRepository; import com.getit.todoapp.service.TodoService; import java.util.Iterator; import java.util.List; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.roo.addon.test.RooIntegrationTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; package com.getit.todoapp.domain; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath*:/META-INF/spring/applicationContext*.xml") @Transactional @Configurable @RooIntegrationTest(entity = Todo.class) public class TodoIntegrationTest { @Test public void testMarkerMethod() { } @Autowired TodoDataOnDemand dod; @Autowired TodoService todoService; @Autowired
TodoRepository todoRepository;
kiranreddykasa/springrest-angularjs
src/test/java/com/getit/todoapp/domain/TodoDataOnDemand.java
// Path: src/main/java/com/getit/todoapp/repository/TodoRepository.java // @Repository // @RooJpaRepository(domainType = Todo.class) // public interface TodoRepository extends JpaSpecificationExecutor<Todo>, JpaRepository<Todo, Long> { // // @Query("select t from Todo t where t.userName.userName = ?1") // List<Todo> findTodosByUserName(String userName); // // @Query("select t from Todo t where t.userName.userName = ?1 and t.id= ?2") // Todo findTodoByUserNameAndId(String userName,Long id); // } // // Path: src/main/java/com/getit/todoapp/service/TodoService.java // @RooService(domainTypes = { com.getit.todoapp.domain.Todo.class }) // public interface TodoService { // // public abstract long countAllTodoes(); // // // public abstract void deleteTodo(Todo todo); // // // public abstract Todo findTodo(Long id); // // // public abstract List<Todo> findAllTodoes(); // // // public abstract List<Todo> findTodoEntries(int firstResult, int maxResults); // // // public abstract void saveTodo(Todo todo); // // // public abstract Todo updateTodo(Todo todo); // // public abstract List<Todo> findTodosByUserName(String userName); // // public abstract Todo findTodoByUserNameAndId(String userName,Long id); // }
import com.getit.todoapp.repository.TodoRepository; import com.getit.todoapp.service.TodoService; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Random; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.roo.addon.dod.RooDataOnDemand; import org.springframework.stereotype.Component;
package com.getit.todoapp.domain; @Component @Configurable @RooDataOnDemand(entity = Todo.class) public class TodoDataOnDemand { private Random rnd = new SecureRandom(); private List<Todo> data; @Autowired UserinfoDataOnDemand userinfoDataOnDemand; @Autowired
// Path: src/main/java/com/getit/todoapp/repository/TodoRepository.java // @Repository // @RooJpaRepository(domainType = Todo.class) // public interface TodoRepository extends JpaSpecificationExecutor<Todo>, JpaRepository<Todo, Long> { // // @Query("select t from Todo t where t.userName.userName = ?1") // List<Todo> findTodosByUserName(String userName); // // @Query("select t from Todo t where t.userName.userName = ?1 and t.id= ?2") // Todo findTodoByUserNameAndId(String userName,Long id); // } // // Path: src/main/java/com/getit/todoapp/service/TodoService.java // @RooService(domainTypes = { com.getit.todoapp.domain.Todo.class }) // public interface TodoService { // // public abstract long countAllTodoes(); // // // public abstract void deleteTodo(Todo todo); // // // public abstract Todo findTodo(Long id); // // // public abstract List<Todo> findAllTodoes(); // // // public abstract List<Todo> findTodoEntries(int firstResult, int maxResults); // // // public abstract void saveTodo(Todo todo); // // // public abstract Todo updateTodo(Todo todo); // // public abstract List<Todo> findTodosByUserName(String userName); // // public abstract Todo findTodoByUserNameAndId(String userName,Long id); // } // Path: src/test/java/com/getit/todoapp/domain/TodoDataOnDemand.java import com.getit.todoapp.repository.TodoRepository; import com.getit.todoapp.service.TodoService; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Random; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.roo.addon.dod.RooDataOnDemand; import org.springframework.stereotype.Component; package com.getit.todoapp.domain; @Component @Configurable @RooDataOnDemand(entity = Todo.class) public class TodoDataOnDemand { private Random rnd = new SecureRandom(); private List<Todo> data; @Autowired UserinfoDataOnDemand userinfoDataOnDemand; @Autowired
TodoService todoService;
kiranreddykasa/springrest-angularjs
src/test/java/com/getit/todoapp/domain/TodoDataOnDemand.java
// Path: src/main/java/com/getit/todoapp/repository/TodoRepository.java // @Repository // @RooJpaRepository(domainType = Todo.class) // public interface TodoRepository extends JpaSpecificationExecutor<Todo>, JpaRepository<Todo, Long> { // // @Query("select t from Todo t where t.userName.userName = ?1") // List<Todo> findTodosByUserName(String userName); // // @Query("select t from Todo t where t.userName.userName = ?1 and t.id= ?2") // Todo findTodoByUserNameAndId(String userName,Long id); // } // // Path: src/main/java/com/getit/todoapp/service/TodoService.java // @RooService(domainTypes = { com.getit.todoapp.domain.Todo.class }) // public interface TodoService { // // public abstract long countAllTodoes(); // // // public abstract void deleteTodo(Todo todo); // // // public abstract Todo findTodo(Long id); // // // public abstract List<Todo> findAllTodoes(); // // // public abstract List<Todo> findTodoEntries(int firstResult, int maxResults); // // // public abstract void saveTodo(Todo todo); // // // public abstract Todo updateTodo(Todo todo); // // public abstract List<Todo> findTodosByUserName(String userName); // // public abstract Todo findTodoByUserNameAndId(String userName,Long id); // }
import com.getit.todoapp.repository.TodoRepository; import com.getit.todoapp.service.TodoService; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Random; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.roo.addon.dod.RooDataOnDemand; import org.springframework.stereotype.Component;
package com.getit.todoapp.domain; @Component @Configurable @RooDataOnDemand(entity = Todo.class) public class TodoDataOnDemand { private Random rnd = new SecureRandom(); private List<Todo> data; @Autowired UserinfoDataOnDemand userinfoDataOnDemand; @Autowired TodoService todoService; @Autowired
// Path: src/main/java/com/getit/todoapp/repository/TodoRepository.java // @Repository // @RooJpaRepository(domainType = Todo.class) // public interface TodoRepository extends JpaSpecificationExecutor<Todo>, JpaRepository<Todo, Long> { // // @Query("select t from Todo t where t.userName.userName = ?1") // List<Todo> findTodosByUserName(String userName); // // @Query("select t from Todo t where t.userName.userName = ?1 and t.id= ?2") // Todo findTodoByUserNameAndId(String userName,Long id); // } // // Path: src/main/java/com/getit/todoapp/service/TodoService.java // @RooService(domainTypes = { com.getit.todoapp.domain.Todo.class }) // public interface TodoService { // // public abstract long countAllTodoes(); // // // public abstract void deleteTodo(Todo todo); // // // public abstract Todo findTodo(Long id); // // // public abstract List<Todo> findAllTodoes(); // // // public abstract List<Todo> findTodoEntries(int firstResult, int maxResults); // // // public abstract void saveTodo(Todo todo); // // // public abstract Todo updateTodo(Todo todo); // // public abstract List<Todo> findTodosByUserName(String userName); // // public abstract Todo findTodoByUserNameAndId(String userName,Long id); // } // Path: src/test/java/com/getit/todoapp/domain/TodoDataOnDemand.java import com.getit.todoapp.repository.TodoRepository; import com.getit.todoapp.service.TodoService; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Random; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.roo.addon.dod.RooDataOnDemand; import org.springframework.stereotype.Component; package com.getit.todoapp.domain; @Component @Configurable @RooDataOnDemand(entity = Todo.class) public class TodoDataOnDemand { private Random rnd = new SecureRandom(); private List<Todo> data; @Autowired UserinfoDataOnDemand userinfoDataOnDemand; @Autowired TodoService todoService; @Autowired
TodoRepository todoRepository;
kiranreddykasa/springrest-angularjs
src/main/java/com/getit/todoapp/service/CustomUserDeatilService.java
// Path: src/main/java/com/getit/todoapp/domain/Userinfo.java // @Entity // @RooJavaBean // @RooToString // @RooJpaEntity // @RooJson // public class Userinfo { // private static final String CLASS_EXTENSION = "*.class"; // // /** // */ // @NotNull // @Column(unique = true) // private String userName; // // /** // */ // @NotNull // @Column(unique = true) // private String email; // // /** // */ // private String firstName; // // /** // */ // private String lastName; // // /** // */ // @OneToMany(cascade = CascadeType.ALL, mappedBy = "userName") // private Set<Todo> todoes = new HashSet<Todo>(); // // /** // */ // @NotNull // private String password; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "id") // private Long id; // // @Version // @Column(name = "version") // private Integer version; // // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public Integer getVersion() { // return this.version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getUserName() { // return this.userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getEmail() { // return this.email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return this.firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Todo> getTodoes() { // return this.todoes; // } // // public void setTodoes(Set<Todo> todoes) { // this.todoes = todoes; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String toJson() { // return new JSONSerializer().exclude(CLASS_EXTENSION).serialize(this); // } // // public String toJson(String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(this); // } // // public static Userinfo fromJsonToUserinfo(String json) { // return new JSONDeserializer<Userinfo>().use(null, Userinfo.class).deserialize(json); // } // // public static String toJsonArray(Collection<Userinfo> collection) { // return new JSONSerializer().exclude(CLASS_EXTENSION).serialize(collection); // } // // public static String toJsonArray(Collection<Userinfo> collection, String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(collection); // } // // public static Collection<Userinfo> fromJsonArrayToUserinfoes(String json) { // return new JSONDeserializer<List<Userinfo>>().use(null, ArrayList.class).use("values", Userinfo.class).deserialize(json); // } // }
import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import com.getit.todoapp.domain.Userinfo;
package com.getit.todoapp.service; public class CustomUserDeatilService implements UserDetailsService { public static final String ROLE_USER = "ROLE_USER"; public static final String ROLE_ADMINISTRATOR = "ROLE_ADMIN"; @Autowired private UserService userService; private final ThreadLocal<User> currentUser = new ThreadLocal<User>(); @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { try { Collection<GrantedAuthority> userAuthorities = new ArrayList<GrantedAuthority>(); userAuthorities.add(new SimpleGrantedAuthority(ROLE_USER));
// Path: src/main/java/com/getit/todoapp/domain/Userinfo.java // @Entity // @RooJavaBean // @RooToString // @RooJpaEntity // @RooJson // public class Userinfo { // private static final String CLASS_EXTENSION = "*.class"; // // /** // */ // @NotNull // @Column(unique = true) // private String userName; // // /** // */ // @NotNull // @Column(unique = true) // private String email; // // /** // */ // private String firstName; // // /** // */ // private String lastName; // // /** // */ // @OneToMany(cascade = CascadeType.ALL, mappedBy = "userName") // private Set<Todo> todoes = new HashSet<Todo>(); // // /** // */ // @NotNull // private String password; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "id") // private Long id; // // @Version // @Column(name = "version") // private Integer version; // // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public Integer getVersion() { // return this.version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getUserName() { // return this.userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getEmail() { // return this.email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return this.firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Todo> getTodoes() { // return this.todoes; // } // // public void setTodoes(Set<Todo> todoes) { // this.todoes = todoes; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String toJson() { // return new JSONSerializer().exclude(CLASS_EXTENSION).serialize(this); // } // // public String toJson(String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(this); // } // // public static Userinfo fromJsonToUserinfo(String json) { // return new JSONDeserializer<Userinfo>().use(null, Userinfo.class).deserialize(json); // } // // public static String toJsonArray(Collection<Userinfo> collection) { // return new JSONSerializer().exclude(CLASS_EXTENSION).serialize(collection); // } // // public static String toJsonArray(Collection<Userinfo> collection, String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(collection); // } // // public static Collection<Userinfo> fromJsonArrayToUserinfoes(String json) { // return new JSONDeserializer<List<Userinfo>>().use(null, ArrayList.class).use("values", Userinfo.class).deserialize(json); // } // } // Path: src/main/java/com/getit/todoapp/service/CustomUserDeatilService.java import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import com.getit.todoapp.domain.Userinfo; package com.getit.todoapp.service; public class CustomUserDeatilService implements UserDetailsService { public static final String ROLE_USER = "ROLE_USER"; public static final String ROLE_ADMINISTRATOR = "ROLE_ADMIN"; @Autowired private UserService userService; private final ThreadLocal<User> currentUser = new ThreadLocal<User>(); @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { try { Collection<GrantedAuthority> userAuthorities = new ArrayList<GrantedAuthority>(); userAuthorities.add(new SimpleGrantedAuthority(ROLE_USER));
List<Userinfo> userinfos = userService.findByUserName(username);
kiranreddykasa/springrest-angularjs
src/main/java/com/getit/todoapp/rest/UserinfoController.java
// Path: src/main/java/com/getit/todoapp/domain/Userinfo.java // @Entity // @RooJavaBean // @RooToString // @RooJpaEntity // @RooJson // public class Userinfo { // private static final String CLASS_EXTENSION = "*.class"; // // /** // */ // @NotNull // @Column(unique = true) // private String userName; // // /** // */ // @NotNull // @Column(unique = true) // private String email; // // /** // */ // private String firstName; // // /** // */ // private String lastName; // // /** // */ // @OneToMany(cascade = CascadeType.ALL, mappedBy = "userName") // private Set<Todo> todoes = new HashSet<Todo>(); // // /** // */ // @NotNull // private String password; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "id") // private Long id; // // @Version // @Column(name = "version") // private Integer version; // // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public Integer getVersion() { // return this.version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getUserName() { // return this.userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getEmail() { // return this.email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return this.firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Todo> getTodoes() { // return this.todoes; // } // // public void setTodoes(Set<Todo> todoes) { // this.todoes = todoes; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String toJson() { // return new JSONSerializer().exclude(CLASS_EXTENSION).serialize(this); // } // // public String toJson(String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(this); // } // // public static Userinfo fromJsonToUserinfo(String json) { // return new JSONDeserializer<Userinfo>().use(null, Userinfo.class).deserialize(json); // } // // public static String toJsonArray(Collection<Userinfo> collection) { // return new JSONSerializer().exclude(CLASS_EXTENSION).serialize(collection); // } // // public static String toJsonArray(Collection<Userinfo> collection, String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(collection); // } // // public static Collection<Userinfo> fromJsonArrayToUserinfoes(String json) { // return new JSONDeserializer<List<Userinfo>>().use(null, ArrayList.class).use("values", Userinfo.class).deserialize(json); // } // } // // Path: src/main/java/com/getit/todoapp/service/UserService.java // @RooService(domainTypes = { com.getit.todoapp.domain.Userinfo.class }) // public interface UserService { // // List<Userinfo> findByUserName(String userName); // // public abstract long countAllUserinfoes(); // // // public abstract void deleteUserinfo(Userinfo userinfo); // // // public abstract Userinfo findUserinfo(Long id); // // // public abstract List<Userinfo> findAllUserinfoes(); // // // public abstract List<Userinfo> findUserinfoEntries(int firstResult, int maxResults); // // // public abstract void saveUserinfo(Userinfo userinfo); // // // public abstract Userinfo updateUserinfo(Userinfo userinfo); // // }
import com.getit.todoapp.domain.Userinfo; import com.getit.todoapp.service.UserService; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.roo.addon.web.mvc.controller.json.RooWebJson; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody;
package com.getit.todoapp.rest; @RooWebJson(jsonObject = Userinfo.class) @Controller @RequestMapping("/userinfoes") public class UserinfoController { private static final String APPLICATION_JSON = "application/json"; private static final String CONTENT_TYPE = "Content-Type"; @Autowired
// Path: src/main/java/com/getit/todoapp/domain/Userinfo.java // @Entity // @RooJavaBean // @RooToString // @RooJpaEntity // @RooJson // public class Userinfo { // private static final String CLASS_EXTENSION = "*.class"; // // /** // */ // @NotNull // @Column(unique = true) // private String userName; // // /** // */ // @NotNull // @Column(unique = true) // private String email; // // /** // */ // private String firstName; // // /** // */ // private String lastName; // // /** // */ // @OneToMany(cascade = CascadeType.ALL, mappedBy = "userName") // private Set<Todo> todoes = new HashSet<Todo>(); // // /** // */ // @NotNull // private String password; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "id") // private Long id; // // @Version // @Column(name = "version") // private Integer version; // // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public Integer getVersion() { // return this.version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getUserName() { // return this.userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getEmail() { // return this.email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return this.firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Todo> getTodoes() { // return this.todoes; // } // // public void setTodoes(Set<Todo> todoes) { // this.todoes = todoes; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String toJson() { // return new JSONSerializer().exclude(CLASS_EXTENSION).serialize(this); // } // // public String toJson(String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(this); // } // // public static Userinfo fromJsonToUserinfo(String json) { // return new JSONDeserializer<Userinfo>().use(null, Userinfo.class).deserialize(json); // } // // public static String toJsonArray(Collection<Userinfo> collection) { // return new JSONSerializer().exclude(CLASS_EXTENSION).serialize(collection); // } // // public static String toJsonArray(Collection<Userinfo> collection, String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(collection); // } // // public static Collection<Userinfo> fromJsonArrayToUserinfoes(String json) { // return new JSONDeserializer<List<Userinfo>>().use(null, ArrayList.class).use("values", Userinfo.class).deserialize(json); // } // } // // Path: src/main/java/com/getit/todoapp/service/UserService.java // @RooService(domainTypes = { com.getit.todoapp.domain.Userinfo.class }) // public interface UserService { // // List<Userinfo> findByUserName(String userName); // // public abstract long countAllUserinfoes(); // // // public abstract void deleteUserinfo(Userinfo userinfo); // // // public abstract Userinfo findUserinfo(Long id); // // // public abstract List<Userinfo> findAllUserinfoes(); // // // public abstract List<Userinfo> findUserinfoEntries(int firstResult, int maxResults); // // // public abstract void saveUserinfo(Userinfo userinfo); // // // public abstract Userinfo updateUserinfo(Userinfo userinfo); // // } // Path: src/main/java/com/getit/todoapp/rest/UserinfoController.java import com.getit.todoapp.domain.Userinfo; import com.getit.todoapp.service.UserService; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.roo.addon.web.mvc.controller.json.RooWebJson; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; package com.getit.todoapp.rest; @RooWebJson(jsonObject = Userinfo.class) @Controller @RequestMapping("/userinfoes") public class UserinfoController { private static final String APPLICATION_JSON = "application/json"; private static final String CONTENT_TYPE = "Content-Type"; @Autowired
private UserService userService;
kiranreddykasa/springrest-angularjs
src/test/java/com/getit/todoapp/domain/UserinfoIntegrationTest.java
// Path: src/main/java/com/getit/todoapp/repository/UserRepository.java // @Repository // @RooJpaRepository(domainType = Userinfo.class) // public interface UserRepository extends JpaSpecificationExecutor<Userinfo>, JpaRepository<Userinfo, Long> { // // List<Userinfo> findByUserName(String userName); // } // // Path: src/main/java/com/getit/todoapp/service/UserService.java // @RooService(domainTypes = { com.getit.todoapp.domain.Userinfo.class }) // public interface UserService { // // List<Userinfo> findByUserName(String userName); // // public abstract long countAllUserinfoes(); // // // public abstract void deleteUserinfo(Userinfo userinfo); // // // public abstract Userinfo findUserinfo(Long id); // // // public abstract List<Userinfo> findAllUserinfoes(); // // // public abstract List<Userinfo> findUserinfoEntries(int firstResult, int maxResults); // // // public abstract void saveUserinfo(Userinfo userinfo); // // // public abstract Userinfo updateUserinfo(Userinfo userinfo); // // }
import com.getit.todoapp.repository.UserRepository; import com.getit.todoapp.service.UserService; import java.util.Iterator; import java.util.List; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.roo.addon.test.RooIntegrationTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional;
package com.getit.todoapp.domain; @Configurable @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath*:/META-INF/spring/applicationContext*.xml") @Transactional @RooIntegrationTest(entity = Userinfo.class) public class UserinfoIntegrationTest { @Test public void testMarkerMethod() { } @Autowired UserinfoDataOnDemand dod; @Autowired
// Path: src/main/java/com/getit/todoapp/repository/UserRepository.java // @Repository // @RooJpaRepository(domainType = Userinfo.class) // public interface UserRepository extends JpaSpecificationExecutor<Userinfo>, JpaRepository<Userinfo, Long> { // // List<Userinfo> findByUserName(String userName); // } // // Path: src/main/java/com/getit/todoapp/service/UserService.java // @RooService(domainTypes = { com.getit.todoapp.domain.Userinfo.class }) // public interface UserService { // // List<Userinfo> findByUserName(String userName); // // public abstract long countAllUserinfoes(); // // // public abstract void deleteUserinfo(Userinfo userinfo); // // // public abstract Userinfo findUserinfo(Long id); // // // public abstract List<Userinfo> findAllUserinfoes(); // // // public abstract List<Userinfo> findUserinfoEntries(int firstResult, int maxResults); // // // public abstract void saveUserinfo(Userinfo userinfo); // // // public abstract Userinfo updateUserinfo(Userinfo userinfo); // // } // Path: src/test/java/com/getit/todoapp/domain/UserinfoIntegrationTest.java import com.getit.todoapp.repository.UserRepository; import com.getit.todoapp.service.UserService; import java.util.Iterator; import java.util.List; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.roo.addon.test.RooIntegrationTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; package com.getit.todoapp.domain; @Configurable @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath*:/META-INF/spring/applicationContext*.xml") @Transactional @RooIntegrationTest(entity = Userinfo.class) public class UserinfoIntegrationTest { @Test public void testMarkerMethod() { } @Autowired UserinfoDataOnDemand dod; @Autowired
UserService userService;
kiranreddykasa/springrest-angularjs
src/test/java/com/getit/todoapp/domain/UserinfoIntegrationTest.java
// Path: src/main/java/com/getit/todoapp/repository/UserRepository.java // @Repository // @RooJpaRepository(domainType = Userinfo.class) // public interface UserRepository extends JpaSpecificationExecutor<Userinfo>, JpaRepository<Userinfo, Long> { // // List<Userinfo> findByUserName(String userName); // } // // Path: src/main/java/com/getit/todoapp/service/UserService.java // @RooService(domainTypes = { com.getit.todoapp.domain.Userinfo.class }) // public interface UserService { // // List<Userinfo> findByUserName(String userName); // // public abstract long countAllUserinfoes(); // // // public abstract void deleteUserinfo(Userinfo userinfo); // // // public abstract Userinfo findUserinfo(Long id); // // // public abstract List<Userinfo> findAllUserinfoes(); // // // public abstract List<Userinfo> findUserinfoEntries(int firstResult, int maxResults); // // // public abstract void saveUserinfo(Userinfo userinfo); // // // public abstract Userinfo updateUserinfo(Userinfo userinfo); // // }
import com.getit.todoapp.repository.UserRepository; import com.getit.todoapp.service.UserService; import java.util.Iterator; import java.util.List; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.roo.addon.test.RooIntegrationTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional;
package com.getit.todoapp.domain; @Configurable @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath*:/META-INF/spring/applicationContext*.xml") @Transactional @RooIntegrationTest(entity = Userinfo.class) public class UserinfoIntegrationTest { @Test public void testMarkerMethod() { } @Autowired UserinfoDataOnDemand dod; @Autowired UserService userService; @Autowired
// Path: src/main/java/com/getit/todoapp/repository/UserRepository.java // @Repository // @RooJpaRepository(domainType = Userinfo.class) // public interface UserRepository extends JpaSpecificationExecutor<Userinfo>, JpaRepository<Userinfo, Long> { // // List<Userinfo> findByUserName(String userName); // } // // Path: src/main/java/com/getit/todoapp/service/UserService.java // @RooService(domainTypes = { com.getit.todoapp.domain.Userinfo.class }) // public interface UserService { // // List<Userinfo> findByUserName(String userName); // // public abstract long countAllUserinfoes(); // // // public abstract void deleteUserinfo(Userinfo userinfo); // // // public abstract Userinfo findUserinfo(Long id); // // // public abstract List<Userinfo> findAllUserinfoes(); // // // public abstract List<Userinfo> findUserinfoEntries(int firstResult, int maxResults); // // // public abstract void saveUserinfo(Userinfo userinfo); // // // public abstract Userinfo updateUserinfo(Userinfo userinfo); // // } // Path: src/test/java/com/getit/todoapp/domain/UserinfoIntegrationTest.java import com.getit.todoapp.repository.UserRepository; import com.getit.todoapp.service.UserService; import java.util.Iterator; import java.util.List; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.roo.addon.test.RooIntegrationTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; package com.getit.todoapp.domain; @Configurable @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath*:/META-INF/spring/applicationContext*.xml") @Transactional @RooIntegrationTest(entity = Userinfo.class) public class UserinfoIntegrationTest { @Test public void testMarkerMethod() { } @Autowired UserinfoDataOnDemand dod; @Autowired UserService userService; @Autowired
UserRepository userRepository;
kiranreddykasa/springrest-angularjs
src/main/java/com/getit/todoapp/service/UserServiceImpl.java
// Path: src/main/java/com/getit/todoapp/domain/Userinfo.java // @Entity // @RooJavaBean // @RooToString // @RooJpaEntity // @RooJson // public class Userinfo { // private static final String CLASS_EXTENSION = "*.class"; // // /** // */ // @NotNull // @Column(unique = true) // private String userName; // // /** // */ // @NotNull // @Column(unique = true) // private String email; // // /** // */ // private String firstName; // // /** // */ // private String lastName; // // /** // */ // @OneToMany(cascade = CascadeType.ALL, mappedBy = "userName") // private Set<Todo> todoes = new HashSet<Todo>(); // // /** // */ // @NotNull // private String password; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "id") // private Long id; // // @Version // @Column(name = "version") // private Integer version; // // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public Integer getVersion() { // return this.version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getUserName() { // return this.userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getEmail() { // return this.email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return this.firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Todo> getTodoes() { // return this.todoes; // } // // public void setTodoes(Set<Todo> todoes) { // this.todoes = todoes; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String toJson() { // return new JSONSerializer().exclude(CLASS_EXTENSION).serialize(this); // } // // public String toJson(String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(this); // } // // public static Userinfo fromJsonToUserinfo(String json) { // return new JSONDeserializer<Userinfo>().use(null, Userinfo.class).deserialize(json); // } // // public static String toJsonArray(Collection<Userinfo> collection) { // return new JSONSerializer().exclude(CLASS_EXTENSION).serialize(collection); // } // // public static String toJsonArray(Collection<Userinfo> collection, String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(collection); // } // // public static Collection<Userinfo> fromJsonArrayToUserinfoes(String json) { // return new JSONDeserializer<List<Userinfo>>().use(null, ArrayList.class).use("values", Userinfo.class).deserialize(json); // } // } // // Path: src/main/java/com/getit/todoapp/repository/UserRepository.java // @Repository // @RooJpaRepository(domainType = Userinfo.class) // public interface UserRepository extends JpaSpecificationExecutor<Userinfo>, JpaRepository<Userinfo, Long> { // // List<Userinfo> findByUserName(String userName); // }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.getit.todoapp.domain.Userinfo; import com.getit.todoapp.repository.UserRepository;
package com.getit.todoapp.service; @Service @Transactional public class UserServiceImpl implements UserService { @Autowired
// Path: src/main/java/com/getit/todoapp/domain/Userinfo.java // @Entity // @RooJavaBean // @RooToString // @RooJpaEntity // @RooJson // public class Userinfo { // private static final String CLASS_EXTENSION = "*.class"; // // /** // */ // @NotNull // @Column(unique = true) // private String userName; // // /** // */ // @NotNull // @Column(unique = true) // private String email; // // /** // */ // private String firstName; // // /** // */ // private String lastName; // // /** // */ // @OneToMany(cascade = CascadeType.ALL, mappedBy = "userName") // private Set<Todo> todoes = new HashSet<Todo>(); // // /** // */ // @NotNull // private String password; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "id") // private Long id; // // @Version // @Column(name = "version") // private Integer version; // // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public Integer getVersion() { // return this.version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getUserName() { // return this.userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getEmail() { // return this.email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return this.firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Todo> getTodoes() { // return this.todoes; // } // // public void setTodoes(Set<Todo> todoes) { // this.todoes = todoes; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String toJson() { // return new JSONSerializer().exclude(CLASS_EXTENSION).serialize(this); // } // // public String toJson(String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(this); // } // // public static Userinfo fromJsonToUserinfo(String json) { // return new JSONDeserializer<Userinfo>().use(null, Userinfo.class).deserialize(json); // } // // public static String toJsonArray(Collection<Userinfo> collection) { // return new JSONSerializer().exclude(CLASS_EXTENSION).serialize(collection); // } // // public static String toJsonArray(Collection<Userinfo> collection, String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(collection); // } // // public static Collection<Userinfo> fromJsonArrayToUserinfoes(String json) { // return new JSONDeserializer<List<Userinfo>>().use(null, ArrayList.class).use("values", Userinfo.class).deserialize(json); // } // } // // Path: src/main/java/com/getit/todoapp/repository/UserRepository.java // @Repository // @RooJpaRepository(domainType = Userinfo.class) // public interface UserRepository extends JpaSpecificationExecutor<Userinfo>, JpaRepository<Userinfo, Long> { // // List<Userinfo> findByUserName(String userName); // } // Path: src/main/java/com/getit/todoapp/service/UserServiceImpl.java import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.getit.todoapp.domain.Userinfo; import com.getit.todoapp.repository.UserRepository; package com.getit.todoapp.service; @Service @Transactional public class UserServiceImpl implements UserService { @Autowired
private UserRepository userRepository;
kiranreddykasa/springrest-angularjs
src/main/java/com/getit/todoapp/service/UserServiceImpl.java
// Path: src/main/java/com/getit/todoapp/domain/Userinfo.java // @Entity // @RooJavaBean // @RooToString // @RooJpaEntity // @RooJson // public class Userinfo { // private static final String CLASS_EXTENSION = "*.class"; // // /** // */ // @NotNull // @Column(unique = true) // private String userName; // // /** // */ // @NotNull // @Column(unique = true) // private String email; // // /** // */ // private String firstName; // // /** // */ // private String lastName; // // /** // */ // @OneToMany(cascade = CascadeType.ALL, mappedBy = "userName") // private Set<Todo> todoes = new HashSet<Todo>(); // // /** // */ // @NotNull // private String password; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "id") // private Long id; // // @Version // @Column(name = "version") // private Integer version; // // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public Integer getVersion() { // return this.version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getUserName() { // return this.userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getEmail() { // return this.email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return this.firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Todo> getTodoes() { // return this.todoes; // } // // public void setTodoes(Set<Todo> todoes) { // this.todoes = todoes; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String toJson() { // return new JSONSerializer().exclude(CLASS_EXTENSION).serialize(this); // } // // public String toJson(String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(this); // } // // public static Userinfo fromJsonToUserinfo(String json) { // return new JSONDeserializer<Userinfo>().use(null, Userinfo.class).deserialize(json); // } // // public static String toJsonArray(Collection<Userinfo> collection) { // return new JSONSerializer().exclude(CLASS_EXTENSION).serialize(collection); // } // // public static String toJsonArray(Collection<Userinfo> collection, String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(collection); // } // // public static Collection<Userinfo> fromJsonArrayToUserinfoes(String json) { // return new JSONDeserializer<List<Userinfo>>().use(null, ArrayList.class).use("values", Userinfo.class).deserialize(json); // } // } // // Path: src/main/java/com/getit/todoapp/repository/UserRepository.java // @Repository // @RooJpaRepository(domainType = Userinfo.class) // public interface UserRepository extends JpaSpecificationExecutor<Userinfo>, JpaRepository<Userinfo, Long> { // // List<Userinfo> findByUserName(String userName); // }
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.getit.todoapp.domain.Userinfo; import com.getit.todoapp.repository.UserRepository;
package com.getit.todoapp.service; @Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository;
// Path: src/main/java/com/getit/todoapp/domain/Userinfo.java // @Entity // @RooJavaBean // @RooToString // @RooJpaEntity // @RooJson // public class Userinfo { // private static final String CLASS_EXTENSION = "*.class"; // // /** // */ // @NotNull // @Column(unique = true) // private String userName; // // /** // */ // @NotNull // @Column(unique = true) // private String email; // // /** // */ // private String firstName; // // /** // */ // private String lastName; // // /** // */ // @OneToMany(cascade = CascadeType.ALL, mappedBy = "userName") // private Set<Todo> todoes = new HashSet<Todo>(); // // /** // */ // @NotNull // private String password; // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @Column(name = "id") // private Long id; // // @Version // @Column(name = "version") // private Integer version; // // public String toString() { // return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); // } // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // public Integer getVersion() { // return this.version; // } // // public void setVersion(Integer version) { // this.version = version; // } // // public String getUserName() { // return this.userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getEmail() { // return this.email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getFirstName() { // return this.firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return this.lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public Set<Todo> getTodoes() { // return this.todoes; // } // // public void setTodoes(Set<Todo> todoes) { // this.todoes = todoes; // } // // public String getPassword() { // return this.password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String toJson() { // return new JSONSerializer().exclude(CLASS_EXTENSION).serialize(this); // } // // public String toJson(String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(this); // } // // public static Userinfo fromJsonToUserinfo(String json) { // return new JSONDeserializer<Userinfo>().use(null, Userinfo.class).deserialize(json); // } // // public static String toJsonArray(Collection<Userinfo> collection) { // return new JSONSerializer().exclude(CLASS_EXTENSION).serialize(collection); // } // // public static String toJsonArray(Collection<Userinfo> collection, String[] fields) { // return new JSONSerializer().include(fields).exclude(CLASS_EXTENSION).serialize(collection); // } // // public static Collection<Userinfo> fromJsonArrayToUserinfoes(String json) { // return new JSONDeserializer<List<Userinfo>>().use(null, ArrayList.class).use("values", Userinfo.class).deserialize(json); // } // } // // Path: src/main/java/com/getit/todoapp/repository/UserRepository.java // @Repository // @RooJpaRepository(domainType = Userinfo.class) // public interface UserRepository extends JpaSpecificationExecutor<Userinfo>, JpaRepository<Userinfo, Long> { // // List<Userinfo> findByUserName(String userName); // } // Path: src/main/java/com/getit/todoapp/service/UserServiceImpl.java import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.getit.todoapp.domain.Userinfo; import com.getit.todoapp.repository.UserRepository; package com.getit.todoapp.service; @Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository;
public List<Userinfo> findByUserName(String userName){
polarcoral/monica
monica-registry/src/main/java/monica/registry/service/ZookeeperRegistration.java
// Path: monica-registry/src/main/java/monica/registry/Registration.java // @SPI(ZookeeperRegistration.NAME) // public interface Registration { // final Logger log = Logger.getLogger(Registration.class); // // public void register(UriSpec uri, RegistryType type) throws Exception; // // public boolean done(); // // } // // Path: monica-registry/src/main/java/monica/registry/base/RegistryType.java // public enum RegistryType { // SERVER, CLIENT // } // // Path: monica-registry/src/main/java/monica/registry/base/UriSpec.java // public class UriSpec { // private String scheme; // private String ip; // private String port; // // public String getScheme() { // return scheme; // } // // public void setScheme(String scheme) { // this.scheme = scheme; // } // // public String getIp() { // return ip; // } // // public void setIp(String ip) { // this.ip = ip; // } // // public String getPort() { // return port; // } // // public void setPort(String port) { // this.port = port; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // if (null == scheme || scheme.equals("")) { // sb.append("monica://"); // } else { // sb.append(scheme); // } // if (null != ip && !ip.equals("")) { // sb.append(ip); // } // sb.append(":"); // if (null != port && !port.equals("")) { // sb.append(port); // } // return sb.toString(); // } // // } // // Path: monica-registry/src/main/java/monica/registry/context/RegistryContext.java // public class RegistryContext { // // caheKey: curatorClient providers server usefulProviders // public static ConcurrentHashMap<String, Object> clientCache = new ConcurrentHashMap<String, Object>(); // }
import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.WatchedEvent; import monica.registry.Registration; import monica.registry.base.RegistryType; import monica.registry.base.UriSpec; import monica.registry.context.RegistryContext;
package monica.registry.service; /** * * @author [email protected] * * 2017-08-29 */ public class ZookeeperRegistration implements Registration { public final static String NAME = "zookeeper"; public final String ZK_NAMESPACE = "monica";
// Path: monica-registry/src/main/java/monica/registry/Registration.java // @SPI(ZookeeperRegistration.NAME) // public interface Registration { // final Logger log = Logger.getLogger(Registration.class); // // public void register(UriSpec uri, RegistryType type) throws Exception; // // public boolean done(); // // } // // Path: monica-registry/src/main/java/monica/registry/base/RegistryType.java // public enum RegistryType { // SERVER, CLIENT // } // // Path: monica-registry/src/main/java/monica/registry/base/UriSpec.java // public class UriSpec { // private String scheme; // private String ip; // private String port; // // public String getScheme() { // return scheme; // } // // public void setScheme(String scheme) { // this.scheme = scheme; // } // // public String getIp() { // return ip; // } // // public void setIp(String ip) { // this.ip = ip; // } // // public String getPort() { // return port; // } // // public void setPort(String port) { // this.port = port; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // if (null == scheme || scheme.equals("")) { // sb.append("monica://"); // } else { // sb.append(scheme); // } // if (null != ip && !ip.equals("")) { // sb.append(ip); // } // sb.append(":"); // if (null != port && !port.equals("")) { // sb.append(port); // } // return sb.toString(); // } // // } // // Path: monica-registry/src/main/java/monica/registry/context/RegistryContext.java // public class RegistryContext { // // caheKey: curatorClient providers server usefulProviders // public static ConcurrentHashMap<String, Object> clientCache = new ConcurrentHashMap<String, Object>(); // } // Path: monica-registry/src/main/java/monica/registry/service/ZookeeperRegistration.java import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.WatchedEvent; import monica.registry.Registration; import monica.registry.base.RegistryType; import monica.registry.base.UriSpec; import monica.registry.context.RegistryContext; package monica.registry.service; /** * * @author [email protected] * * 2017-08-29 */ public class ZookeeperRegistration implements Registration { public final static String NAME = "zookeeper"; public final String ZK_NAMESPACE = "monica";
public void register(UriSpec uri, RegistryType type) throws Exception {
polarcoral/monica
monica-registry/src/main/java/monica/registry/service/ZookeeperRegistration.java
// Path: monica-registry/src/main/java/monica/registry/Registration.java // @SPI(ZookeeperRegistration.NAME) // public interface Registration { // final Logger log = Logger.getLogger(Registration.class); // // public void register(UriSpec uri, RegistryType type) throws Exception; // // public boolean done(); // // } // // Path: monica-registry/src/main/java/monica/registry/base/RegistryType.java // public enum RegistryType { // SERVER, CLIENT // } // // Path: monica-registry/src/main/java/monica/registry/base/UriSpec.java // public class UriSpec { // private String scheme; // private String ip; // private String port; // // public String getScheme() { // return scheme; // } // // public void setScheme(String scheme) { // this.scheme = scheme; // } // // public String getIp() { // return ip; // } // // public void setIp(String ip) { // this.ip = ip; // } // // public String getPort() { // return port; // } // // public void setPort(String port) { // this.port = port; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // if (null == scheme || scheme.equals("")) { // sb.append("monica://"); // } else { // sb.append(scheme); // } // if (null != ip && !ip.equals("")) { // sb.append(ip); // } // sb.append(":"); // if (null != port && !port.equals("")) { // sb.append(port); // } // return sb.toString(); // } // // } // // Path: monica-registry/src/main/java/monica/registry/context/RegistryContext.java // public class RegistryContext { // // caheKey: curatorClient providers server usefulProviders // public static ConcurrentHashMap<String, Object> clientCache = new ConcurrentHashMap<String, Object>(); // }
import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.WatchedEvent; import monica.registry.Registration; import monica.registry.base.RegistryType; import monica.registry.base.UriSpec; import monica.registry.context.RegistryContext;
package monica.registry.service; /** * * @author [email protected] * * 2017-08-29 */ public class ZookeeperRegistration implements Registration { public final static String NAME = "zookeeper"; public final String ZK_NAMESPACE = "monica";
// Path: monica-registry/src/main/java/monica/registry/Registration.java // @SPI(ZookeeperRegistration.NAME) // public interface Registration { // final Logger log = Logger.getLogger(Registration.class); // // public void register(UriSpec uri, RegistryType type) throws Exception; // // public boolean done(); // // } // // Path: monica-registry/src/main/java/monica/registry/base/RegistryType.java // public enum RegistryType { // SERVER, CLIENT // } // // Path: monica-registry/src/main/java/monica/registry/base/UriSpec.java // public class UriSpec { // private String scheme; // private String ip; // private String port; // // public String getScheme() { // return scheme; // } // // public void setScheme(String scheme) { // this.scheme = scheme; // } // // public String getIp() { // return ip; // } // // public void setIp(String ip) { // this.ip = ip; // } // // public String getPort() { // return port; // } // // public void setPort(String port) { // this.port = port; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // if (null == scheme || scheme.equals("")) { // sb.append("monica://"); // } else { // sb.append(scheme); // } // if (null != ip && !ip.equals("")) { // sb.append(ip); // } // sb.append(":"); // if (null != port && !port.equals("")) { // sb.append(port); // } // return sb.toString(); // } // // } // // Path: monica-registry/src/main/java/monica/registry/context/RegistryContext.java // public class RegistryContext { // // caheKey: curatorClient providers server usefulProviders // public static ConcurrentHashMap<String, Object> clientCache = new ConcurrentHashMap<String, Object>(); // } // Path: monica-registry/src/main/java/monica/registry/service/ZookeeperRegistration.java import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.WatchedEvent; import monica.registry.Registration; import monica.registry.base.RegistryType; import monica.registry.base.UriSpec; import monica.registry.context.RegistryContext; package monica.registry.service; /** * * @author [email protected] * * 2017-08-29 */ public class ZookeeperRegistration implements Registration { public final static String NAME = "zookeeper"; public final String ZK_NAMESPACE = "monica";
public void register(UriSpec uri, RegistryType type) throws Exception {
polarcoral/monica
monica-registry/src/main/java/monica/registry/service/ZookeeperRegistration.java
// Path: monica-registry/src/main/java/monica/registry/Registration.java // @SPI(ZookeeperRegistration.NAME) // public interface Registration { // final Logger log = Logger.getLogger(Registration.class); // // public void register(UriSpec uri, RegistryType type) throws Exception; // // public boolean done(); // // } // // Path: monica-registry/src/main/java/monica/registry/base/RegistryType.java // public enum RegistryType { // SERVER, CLIENT // } // // Path: monica-registry/src/main/java/monica/registry/base/UriSpec.java // public class UriSpec { // private String scheme; // private String ip; // private String port; // // public String getScheme() { // return scheme; // } // // public void setScheme(String scheme) { // this.scheme = scheme; // } // // public String getIp() { // return ip; // } // // public void setIp(String ip) { // this.ip = ip; // } // // public String getPort() { // return port; // } // // public void setPort(String port) { // this.port = port; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // if (null == scheme || scheme.equals("")) { // sb.append("monica://"); // } else { // sb.append(scheme); // } // if (null != ip && !ip.equals("")) { // sb.append(ip); // } // sb.append(":"); // if (null != port && !port.equals("")) { // sb.append(port); // } // return sb.toString(); // } // // } // // Path: monica-registry/src/main/java/monica/registry/context/RegistryContext.java // public class RegistryContext { // // caheKey: curatorClient providers server usefulProviders // public static ConcurrentHashMap<String, Object> clientCache = new ConcurrentHashMap<String, Object>(); // }
import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.WatchedEvent; import monica.registry.Registration; import monica.registry.base.RegistryType; import monica.registry.base.UriSpec; import monica.registry.context.RegistryContext;
package monica.registry.service; /** * * @author [email protected] * * 2017-08-29 */ public class ZookeeperRegistration implements Registration { public final static String NAME = "zookeeper"; public final String ZK_NAMESPACE = "monica"; public void register(UriSpec uri, RegistryType type) throws Exception {
// Path: monica-registry/src/main/java/monica/registry/Registration.java // @SPI(ZookeeperRegistration.NAME) // public interface Registration { // final Logger log = Logger.getLogger(Registration.class); // // public void register(UriSpec uri, RegistryType type) throws Exception; // // public boolean done(); // // } // // Path: monica-registry/src/main/java/monica/registry/base/RegistryType.java // public enum RegistryType { // SERVER, CLIENT // } // // Path: monica-registry/src/main/java/monica/registry/base/UriSpec.java // public class UriSpec { // private String scheme; // private String ip; // private String port; // // public String getScheme() { // return scheme; // } // // public void setScheme(String scheme) { // this.scheme = scheme; // } // // public String getIp() { // return ip; // } // // public void setIp(String ip) { // this.ip = ip; // } // // public String getPort() { // return port; // } // // public void setPort(String port) { // this.port = port; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // if (null == scheme || scheme.equals("")) { // sb.append("monica://"); // } else { // sb.append(scheme); // } // if (null != ip && !ip.equals("")) { // sb.append(ip); // } // sb.append(":"); // if (null != port && !port.equals("")) { // sb.append(port); // } // return sb.toString(); // } // // } // // Path: monica-registry/src/main/java/monica/registry/context/RegistryContext.java // public class RegistryContext { // // caheKey: curatorClient providers server usefulProviders // public static ConcurrentHashMap<String, Object> clientCache = new ConcurrentHashMap<String, Object>(); // } // Path: monica-registry/src/main/java/monica/registry/service/ZookeeperRegistration.java import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.WatchedEvent; import monica.registry.Registration; import monica.registry.base.RegistryType; import monica.registry.base.UriSpec; import monica.registry.context.RegistryContext; package monica.registry.service; /** * * @author [email protected] * * 2017-08-29 */ public class ZookeeperRegistration implements Registration { public final static String NAME = "zookeeper"; public final String ZK_NAMESPACE = "monica"; public void register(UriSpec uri, RegistryType type) throws Exception {
CuratorFramework client = (CuratorFramework) RegistryContext.clientCache.get("curatorClient");
polarcoral/monica
monica-registry/src/main/java/monica/registry/service/ZookeeperMonicaClient.java
// Path: monica-configuration/src/main/java/monica/configuration/context/ConfigurationContext.java // public class ConfigurationContext { // private static String yamlBaseFilePath = "yaml"; // // public static ConcurrentHashMap<String, Object> propMap = new ConcurrentHashMap<String, Object>(); // // /** // * need to adapt to different registry framework. below just be customized to zookeeper // * @throws FileNotFoundException // * @throws IOException // */ // public static void loadYamlServerConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("yaml\\monica.yaml"); // //YamlMonica yamlMonica = yaml.loadAs(new FileInputStream(path), YamlMonica.class); // YamlMonica yamlMonica = yaml.loadAs(Utils.loadResources("yaml/monica.yaml").openStream(), YamlMonica.class); // propMap.putIfAbsent("yamlMonica", yamlMonica); // propMap.putIfAbsent("serverString", yamlMonica.toServerString()); // propMap.putIfAbsent("storage", yamlMonica.getStorage()); // } // // // public static void loadYamlClientConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\client.yaml"); // //YamlClient yamlClient = yaml.loadAs(new FileInputStream(path), YamlClient.class); // YamlClient yamlClient = yaml.loadAs(Utils.loadResources("yaml/client.yaml").openStream(), YamlClient.class); // propMap.putIfAbsent("client", yamlClient); // propMap.putIfAbsent("serverString", yamlClient.toServerString()); // } // // public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\router.yaml"); // //YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class); // YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class); // return yamlRouter.toStringList(); // } // // // private static ClassLoader getClassLoader(){ // return ConfigurationContext.class.getClassLoader(); // } // // public static void main(String args[]){ // try { // //loadYamlServerConfig(); // //YamlMonica monica = (YamlMonica)propMap.get("yamlMonica"); // List<String> rules = loadYamlRouterConfig(); // System.out.println("zk -------- "+rules.get(0)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // // Path: monica-registry/src/main/java/monica/registry/context/RegistryContext.java // public class RegistryContext { // // caheKey: curatorClient providers server usefulProviders // public static ConcurrentHashMap<String, Object> clientCache = new ConcurrentHashMap<String, Object>(); // }
import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.apache.zookeeper.KeeperException; import monica.configuration.context.ConfigurationContext; import monica.registry.context.RegistryContext;
package monica.registry.service; /** * * @author [email protected] * * 2017-08-29 */ public class ZookeeperMonicaClient { private final String ZK_NAMESPACE = "monica"; private CuratorFramework zkClient; public void start() { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); zkClient = builder.connectString(getServerConnectionString()).namespace(ZK_NAMESPACE) .retryPolicy(new RetryOneTime(1)).connectionTimeoutMs(1).sessionTimeoutMs(140).build(); zkClient.start();
// Path: monica-configuration/src/main/java/monica/configuration/context/ConfigurationContext.java // public class ConfigurationContext { // private static String yamlBaseFilePath = "yaml"; // // public static ConcurrentHashMap<String, Object> propMap = new ConcurrentHashMap<String, Object>(); // // /** // * need to adapt to different registry framework. below just be customized to zookeeper // * @throws FileNotFoundException // * @throws IOException // */ // public static void loadYamlServerConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("yaml\\monica.yaml"); // //YamlMonica yamlMonica = yaml.loadAs(new FileInputStream(path), YamlMonica.class); // YamlMonica yamlMonica = yaml.loadAs(Utils.loadResources("yaml/monica.yaml").openStream(), YamlMonica.class); // propMap.putIfAbsent("yamlMonica", yamlMonica); // propMap.putIfAbsent("serverString", yamlMonica.toServerString()); // propMap.putIfAbsent("storage", yamlMonica.getStorage()); // } // // // public static void loadYamlClientConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\client.yaml"); // //YamlClient yamlClient = yaml.loadAs(new FileInputStream(path), YamlClient.class); // YamlClient yamlClient = yaml.loadAs(Utils.loadResources("yaml/client.yaml").openStream(), YamlClient.class); // propMap.putIfAbsent("client", yamlClient); // propMap.putIfAbsent("serverString", yamlClient.toServerString()); // } // // public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\router.yaml"); // //YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class); // YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class); // return yamlRouter.toStringList(); // } // // // private static ClassLoader getClassLoader(){ // return ConfigurationContext.class.getClassLoader(); // } // // public static void main(String args[]){ // try { // //loadYamlServerConfig(); // //YamlMonica monica = (YamlMonica)propMap.get("yamlMonica"); // List<String> rules = loadYamlRouterConfig(); // System.out.println("zk -------- "+rules.get(0)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // // Path: monica-registry/src/main/java/monica/registry/context/RegistryContext.java // public class RegistryContext { // // caheKey: curatorClient providers server usefulProviders // public static ConcurrentHashMap<String, Object> clientCache = new ConcurrentHashMap<String, Object>(); // } // Path: monica-registry/src/main/java/monica/registry/service/ZookeeperMonicaClient.java import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.apache.zookeeper.KeeperException; import monica.configuration.context.ConfigurationContext; import monica.registry.context.RegistryContext; package monica.registry.service; /** * * @author [email protected] * * 2017-08-29 */ public class ZookeeperMonicaClient { private final String ZK_NAMESPACE = "monica"; private CuratorFramework zkClient; public void start() { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); zkClient = builder.connectString(getServerConnectionString()).namespace(ZK_NAMESPACE) .retryPolicy(new RetryOneTime(1)).connectionTimeoutMs(1).sessionTimeoutMs(140).build(); zkClient.start();
RegistryContext.clientCache.putIfAbsent("curatorClient", zkClient);
polarcoral/monica
monica-registry/src/main/java/monica/registry/service/ZookeeperMonicaClient.java
// Path: monica-configuration/src/main/java/monica/configuration/context/ConfigurationContext.java // public class ConfigurationContext { // private static String yamlBaseFilePath = "yaml"; // // public static ConcurrentHashMap<String, Object> propMap = new ConcurrentHashMap<String, Object>(); // // /** // * need to adapt to different registry framework. below just be customized to zookeeper // * @throws FileNotFoundException // * @throws IOException // */ // public static void loadYamlServerConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("yaml\\monica.yaml"); // //YamlMonica yamlMonica = yaml.loadAs(new FileInputStream(path), YamlMonica.class); // YamlMonica yamlMonica = yaml.loadAs(Utils.loadResources("yaml/monica.yaml").openStream(), YamlMonica.class); // propMap.putIfAbsent("yamlMonica", yamlMonica); // propMap.putIfAbsent("serverString", yamlMonica.toServerString()); // propMap.putIfAbsent("storage", yamlMonica.getStorage()); // } // // // public static void loadYamlClientConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\client.yaml"); // //YamlClient yamlClient = yaml.loadAs(new FileInputStream(path), YamlClient.class); // YamlClient yamlClient = yaml.loadAs(Utils.loadResources("yaml/client.yaml").openStream(), YamlClient.class); // propMap.putIfAbsent("client", yamlClient); // propMap.putIfAbsent("serverString", yamlClient.toServerString()); // } // // public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\router.yaml"); // //YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class); // YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class); // return yamlRouter.toStringList(); // } // // // private static ClassLoader getClassLoader(){ // return ConfigurationContext.class.getClassLoader(); // } // // public static void main(String args[]){ // try { // //loadYamlServerConfig(); // //YamlMonica monica = (YamlMonica)propMap.get("yamlMonica"); // List<String> rules = loadYamlRouterConfig(); // System.out.println("zk -------- "+rules.get(0)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // // Path: monica-registry/src/main/java/monica/registry/context/RegistryContext.java // public class RegistryContext { // // caheKey: curatorClient providers server usefulProviders // public static ConcurrentHashMap<String, Object> clientCache = new ConcurrentHashMap<String, Object>(); // }
import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.apache.zookeeper.KeeperException; import monica.configuration.context.ConfigurationContext; import monica.registry.context.RegistryContext;
package monica.registry.service; /** * * @author [email protected] * * 2017-08-29 */ public class ZookeeperMonicaClient { private final String ZK_NAMESPACE = "monica"; private CuratorFramework zkClient; public void start() { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); zkClient = builder.connectString(getServerConnectionString()).namespace(ZK_NAMESPACE) .retryPolicy(new RetryOneTime(1)).connectionTimeoutMs(1).sessionTimeoutMs(140).build(); zkClient.start(); RegistryContext.clientCache.putIfAbsent("curatorClient", zkClient); } private String getServerConnectionString() {
// Path: monica-configuration/src/main/java/monica/configuration/context/ConfigurationContext.java // public class ConfigurationContext { // private static String yamlBaseFilePath = "yaml"; // // public static ConcurrentHashMap<String, Object> propMap = new ConcurrentHashMap<String, Object>(); // // /** // * need to adapt to different registry framework. below just be customized to zookeeper // * @throws FileNotFoundException // * @throws IOException // */ // public static void loadYamlServerConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("yaml\\monica.yaml"); // //YamlMonica yamlMonica = yaml.loadAs(new FileInputStream(path), YamlMonica.class); // YamlMonica yamlMonica = yaml.loadAs(Utils.loadResources("yaml/monica.yaml").openStream(), YamlMonica.class); // propMap.putIfAbsent("yamlMonica", yamlMonica); // propMap.putIfAbsent("serverString", yamlMonica.toServerString()); // propMap.putIfAbsent("storage", yamlMonica.getStorage()); // } // // // public static void loadYamlClientConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\client.yaml"); // //YamlClient yamlClient = yaml.loadAs(new FileInputStream(path), YamlClient.class); // YamlClient yamlClient = yaml.loadAs(Utils.loadResources("yaml/client.yaml").openStream(), YamlClient.class); // propMap.putIfAbsent("client", yamlClient); // propMap.putIfAbsent("serverString", yamlClient.toServerString()); // } // // public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\router.yaml"); // //YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class); // YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class); // return yamlRouter.toStringList(); // } // // // private static ClassLoader getClassLoader(){ // return ConfigurationContext.class.getClassLoader(); // } // // public static void main(String args[]){ // try { // //loadYamlServerConfig(); // //YamlMonica monica = (YamlMonica)propMap.get("yamlMonica"); // List<String> rules = loadYamlRouterConfig(); // System.out.println("zk -------- "+rules.get(0)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // // Path: monica-registry/src/main/java/monica/registry/context/RegistryContext.java // public class RegistryContext { // // caheKey: curatorClient providers server usefulProviders // public static ConcurrentHashMap<String, Object> clientCache = new ConcurrentHashMap<String, Object>(); // } // Path: monica-registry/src/main/java/monica/registry/service/ZookeeperMonicaClient.java import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.apache.zookeeper.KeeperException; import monica.configuration.context.ConfigurationContext; import monica.registry.context.RegistryContext; package monica.registry.service; /** * * @author [email protected] * * 2017-08-29 */ public class ZookeeperMonicaClient { private final String ZK_NAMESPACE = "monica"; private CuratorFramework zkClient; public void start() { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); zkClient = builder.connectString(getServerConnectionString()).namespace(ZK_NAMESPACE) .retryPolicy(new RetryOneTime(1)).connectionTimeoutMs(1).sessionTimeoutMs(140).build(); zkClient.start(); RegistryContext.clientCache.putIfAbsent("curatorClient", zkClient); } private String getServerConnectionString() {
return String.valueOf(ConfigurationContext.propMap.get("serverString"));
polarcoral/monica
monica-starter/src/main/java/monica/starter/client/ClientFactory.java
// Path: monica-framework/src/main/java/monica/framework/Client.java // public interface Client { // public void start(String ip, int port) throws Exception; // public boolean isStarted(); // } // // Path: monica-registry/src/main/java/monica/registry/context/RegistryContext.java // public class RegistryContext { // // caheKey: curatorClient providers server usefulProviders // public static ConcurrentHashMap<String, Object> clientCache = new ConcurrentHashMap<String, Object>(); // }
import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import monica.framework.Client; import monica.registry.context.RegistryContext;
package monica.starter.client; /** * * @author [email protected] * * 2017-08-29 */ public class ClientFactory { private final String SERVER_IP_CACHE = "server_ip"; private final String SERVER_PORT_CACHE = "server_port"; private String protocolString = "socket"; private static ClientFactory factory = new ClientFactory();
// Path: monica-framework/src/main/java/monica/framework/Client.java // public interface Client { // public void start(String ip, int port) throws Exception; // public boolean isStarted(); // } // // Path: monica-registry/src/main/java/monica/registry/context/RegistryContext.java // public class RegistryContext { // // caheKey: curatorClient providers server usefulProviders // public static ConcurrentHashMap<String, Object> clientCache = new ConcurrentHashMap<String, Object>(); // } // Path: monica-starter/src/main/java/monica/starter/client/ClientFactory.java import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import monica.framework.Client; import monica.registry.context.RegistryContext; package monica.starter.client; /** * * @author [email protected] * * 2017-08-29 */ public class ClientFactory { private final String SERVER_IP_CACHE = "server_ip"; private final String SERVER_PORT_CACHE = "server_port"; private String protocolString = "socket"; private static ClientFactory factory = new ClientFactory();
private String ip = (String) RegistryContext.clientCache.get(SERVER_IP_CACHE);
polarcoral/monica
monica-starter/src/main/java/monica/starter/client/ClientFactory.java
// Path: monica-framework/src/main/java/monica/framework/Client.java // public interface Client { // public void start(String ip, int port) throws Exception; // public boolean isStarted(); // } // // Path: monica-registry/src/main/java/monica/registry/context/RegistryContext.java // public class RegistryContext { // // caheKey: curatorClient providers server usefulProviders // public static ConcurrentHashMap<String, Object> clientCache = new ConcurrentHashMap<String, Object>(); // }
import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import monica.framework.Client; import monica.registry.context.RegistryContext;
package monica.starter.client; /** * * @author [email protected] * * 2017-08-29 */ public class ClientFactory { private final String SERVER_IP_CACHE = "server_ip"; private final String SERVER_PORT_CACHE = "server_port"; private String protocolString = "socket"; private static ClientFactory factory = new ClientFactory(); private String ip = (String) RegistryContext.clientCache.get(SERVER_IP_CACHE); private int port = Integer.valueOf((String) RegistryContext.clientCache.get(SERVER_PORT_CACHE)); public static ClientFactory newFactory() { if (null != factory) { return factory; } return new ClientFactory(); }
// Path: monica-framework/src/main/java/monica/framework/Client.java // public interface Client { // public void start(String ip, int port) throws Exception; // public boolean isStarted(); // } // // Path: monica-registry/src/main/java/monica/registry/context/RegistryContext.java // public class RegistryContext { // // caheKey: curatorClient providers server usefulProviders // public static ConcurrentHashMap<String, Object> clientCache = new ConcurrentHashMap<String, Object>(); // } // Path: monica-starter/src/main/java/monica/starter/client/ClientFactory.java import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import monica.framework.Client; import monica.registry.context.RegistryContext; package monica.starter.client; /** * * @author [email protected] * * 2017-08-29 */ public class ClientFactory { private final String SERVER_IP_CACHE = "server_ip"; private final String SERVER_PORT_CACHE = "server_port"; private String protocolString = "socket"; private static ClientFactory factory = new ClientFactory(); private String ip = (String) RegistryContext.clientCache.get(SERVER_IP_CACHE); private int port = Integer.valueOf((String) RegistryContext.clientCache.get(SERVER_PORT_CACHE)); public static ClientFactory newFactory() { if (null != factory) { return factory; } return new ClientFactory(); }
public Client getConsumerClient()
polarcoral/monica
monica-registry/src/main/java/monica/registry/service/RegistrationFactory.java
// Path: monica-framework/src/main/java/monica/framework/extension/ExtensionProvider.java // public class ExtensionProvider { // private static final String basePath = "META-INF/monica/internal"; // // public static Class<?> getDefaultExtension(Class<?> c) throws ClassNotFoundException { // SPI cSpi = c.getAnnotation(SPI.class); // String spiValue = cSpi.value(); // String fileName = c.getName(); // String className = loadFile(fileName, spiValue); // return getClassLoader().loadClass(className); // } // // private static String loadFile(String fileName, String key) { // URL url = getClassLoader().getResource(basePath + "/" + fileName); // if (null != url) { // try { // BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); // String line = ""; // // while ((line = reader.readLine()) != null) { // int index = line.trim().indexOf("="); // if (index > 0 && line.substring(0, index).equals(key)) { // return line.substring(index + 1); // } // } // // } catch (UnsupportedEncodingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return null; // } // // private static ClassLoader getClassLoader() { // return ExtensionProvider.class.getClassLoader(); // } // // public static void main(String args[]) { // ExtensionProvider provider = new ExtensionProvider(); // //provider.getDefaultExtension(ConfigService.class); // } // } // // Path: monica-registry/src/main/java/monica/registry/Registration.java // @SPI(ZookeeperRegistration.NAME) // public interface Registration { // final Logger log = Logger.getLogger(Registration.class); // // public void register(UriSpec uri, RegistryType type) throws Exception; // // public boolean done(); // // }
import monica.framework.extension.ExtensionProvider; import monica.registry.Registration;
package monica.registry.service; /** * * @author [email protected] * * 2017-08-29 */ public class RegistrationFactory { public static Registration getRegistryService() throws InstantiationException, ClassNotFoundException, IllegalAccessException {
// Path: monica-framework/src/main/java/monica/framework/extension/ExtensionProvider.java // public class ExtensionProvider { // private static final String basePath = "META-INF/monica/internal"; // // public static Class<?> getDefaultExtension(Class<?> c) throws ClassNotFoundException { // SPI cSpi = c.getAnnotation(SPI.class); // String spiValue = cSpi.value(); // String fileName = c.getName(); // String className = loadFile(fileName, spiValue); // return getClassLoader().loadClass(className); // } // // private static String loadFile(String fileName, String key) { // URL url = getClassLoader().getResource(basePath + "/" + fileName); // if (null != url) { // try { // BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); // String line = ""; // // while ((line = reader.readLine()) != null) { // int index = line.trim().indexOf("="); // if (index > 0 && line.substring(0, index).equals(key)) { // return line.substring(index + 1); // } // } // // } catch (UnsupportedEncodingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return null; // } // // private static ClassLoader getClassLoader() { // return ExtensionProvider.class.getClassLoader(); // } // // public static void main(String args[]) { // ExtensionProvider provider = new ExtensionProvider(); // //provider.getDefaultExtension(ConfigService.class); // } // } // // Path: monica-registry/src/main/java/monica/registry/Registration.java // @SPI(ZookeeperRegistration.NAME) // public interface Registration { // final Logger log = Logger.getLogger(Registration.class); // // public void register(UriSpec uri, RegistryType type) throws Exception; // // public boolean done(); // // } // Path: monica-registry/src/main/java/monica/registry/service/RegistrationFactory.java import monica.framework.extension.ExtensionProvider; import monica.registry.Registration; package monica.registry.service; /** * * @author [email protected] * * 2017-08-29 */ public class RegistrationFactory { public static Registration getRegistryService() throws InstantiationException, ClassNotFoundException, IllegalAccessException {
Registration service = (Registration) ExtensionProvider.getDefaultExtension(Registration.class).newInstance();
polarcoral/monica
monica-coordinator/src/main/java/monica/coordinator/impl/zookeeper/ZookeeperConfigService.java
// Path: monica-configuration/src/main/java/monica/configuration/context/ConfigurationContext.java // public class ConfigurationContext { // private static String yamlBaseFilePath = "yaml"; // // public static ConcurrentHashMap<String, Object> propMap = new ConcurrentHashMap<String, Object>(); // // /** // * need to adapt to different registry framework. below just be customized to zookeeper // * @throws FileNotFoundException // * @throws IOException // */ // public static void loadYamlServerConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("yaml\\monica.yaml"); // //YamlMonica yamlMonica = yaml.loadAs(new FileInputStream(path), YamlMonica.class); // YamlMonica yamlMonica = yaml.loadAs(Utils.loadResources("yaml/monica.yaml").openStream(), YamlMonica.class); // propMap.putIfAbsent("yamlMonica", yamlMonica); // propMap.putIfAbsent("serverString", yamlMonica.toServerString()); // propMap.putIfAbsent("storage", yamlMonica.getStorage()); // } // // // public static void loadYamlClientConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\client.yaml"); // //YamlClient yamlClient = yaml.loadAs(new FileInputStream(path), YamlClient.class); // YamlClient yamlClient = yaml.loadAs(Utils.loadResources("yaml/client.yaml").openStream(), YamlClient.class); // propMap.putIfAbsent("client", yamlClient); // propMap.putIfAbsent("serverString", yamlClient.toServerString()); // } // // public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\router.yaml"); // //YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class); // YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class); // return yamlRouter.toStringList(); // } // // // private static ClassLoader getClassLoader(){ // return ConfigurationContext.class.getClassLoader(); // } // // public static void main(String args[]){ // try { // //loadYamlServerConfig(); // //YamlMonica monica = (YamlMonica)propMap.get("yamlMonica"); // List<String> rules = loadYamlRouterConfig(); // System.out.println("zk -------- "+rules.get(0)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // // Path: monica-coordinator/src/main/java/monica/coordinator/ConfigService.java // @SPI(ZookeeperConfigService.NAME) // public interface ConfigService { // public void initService() throws Exception; // // public void rulesStore(List<String> rules) throws Exception; // // public void rulesStore() throws Exception; // } // // Path: monica-registry/src/main/java/monica/registry/context/RegistryContext.java // public class RegistryContext { // // caheKey: curatorClient providers server usefulProviders // public static ConcurrentHashMap<String, Object> clientCache = new ConcurrentHashMap<String, Object>(); // }
import java.net.URLEncoder; import java.util.List; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.zookeeper.WatchedEvent; import monica.configuration.context.ConfigurationContext; import monica.coordinator.ConfigService; import monica.registry.context.RegistryContext;
package monica.coordinator.impl.zookeeper; /** * * @author [email protected] * * 2017-08-29 */ public class ZookeeperConfigService implements ConfigService { public final static String NAME = "zookeeper";
// Path: monica-configuration/src/main/java/monica/configuration/context/ConfigurationContext.java // public class ConfigurationContext { // private static String yamlBaseFilePath = "yaml"; // // public static ConcurrentHashMap<String, Object> propMap = new ConcurrentHashMap<String, Object>(); // // /** // * need to adapt to different registry framework. below just be customized to zookeeper // * @throws FileNotFoundException // * @throws IOException // */ // public static void loadYamlServerConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("yaml\\monica.yaml"); // //YamlMonica yamlMonica = yaml.loadAs(new FileInputStream(path), YamlMonica.class); // YamlMonica yamlMonica = yaml.loadAs(Utils.loadResources("yaml/monica.yaml").openStream(), YamlMonica.class); // propMap.putIfAbsent("yamlMonica", yamlMonica); // propMap.putIfAbsent("serverString", yamlMonica.toServerString()); // propMap.putIfAbsent("storage", yamlMonica.getStorage()); // } // // // public static void loadYamlClientConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\client.yaml"); // //YamlClient yamlClient = yaml.loadAs(new FileInputStream(path), YamlClient.class); // YamlClient yamlClient = yaml.loadAs(Utils.loadResources("yaml/client.yaml").openStream(), YamlClient.class); // propMap.putIfAbsent("client", yamlClient); // propMap.putIfAbsent("serverString", yamlClient.toServerString()); // } // // public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\router.yaml"); // //YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class); // YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class); // return yamlRouter.toStringList(); // } // // // private static ClassLoader getClassLoader(){ // return ConfigurationContext.class.getClassLoader(); // } // // public static void main(String args[]){ // try { // //loadYamlServerConfig(); // //YamlMonica monica = (YamlMonica)propMap.get("yamlMonica"); // List<String> rules = loadYamlRouterConfig(); // System.out.println("zk -------- "+rules.get(0)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // // Path: monica-coordinator/src/main/java/monica/coordinator/ConfigService.java // @SPI(ZookeeperConfigService.NAME) // public interface ConfigService { // public void initService() throws Exception; // // public void rulesStore(List<String> rules) throws Exception; // // public void rulesStore() throws Exception; // } // // Path: monica-registry/src/main/java/monica/registry/context/RegistryContext.java // public class RegistryContext { // // caheKey: curatorClient providers server usefulProviders // public static ConcurrentHashMap<String, Object> clientCache = new ConcurrentHashMap<String, Object>(); // } // Path: monica-coordinator/src/main/java/monica/coordinator/impl/zookeeper/ZookeeperConfigService.java import java.net.URLEncoder; import java.util.List; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.zookeeper.WatchedEvent; import monica.configuration.context.ConfigurationContext; import monica.coordinator.ConfigService; import monica.registry.context.RegistryContext; package monica.coordinator.impl.zookeeper; /** * * @author [email protected] * * 2017-08-29 */ public class ZookeeperConfigService implements ConfigService { public final static String NAME = "zookeeper";
private CuratorFramework zkClient = (CuratorFramework) RegistryContext.clientCache.get("curatorClient");
polarcoral/monica
monica-coordinator/src/main/java/monica/coordinator/impl/zookeeper/ZookeeperConfigService.java
// Path: monica-configuration/src/main/java/monica/configuration/context/ConfigurationContext.java // public class ConfigurationContext { // private static String yamlBaseFilePath = "yaml"; // // public static ConcurrentHashMap<String, Object> propMap = new ConcurrentHashMap<String, Object>(); // // /** // * need to adapt to different registry framework. below just be customized to zookeeper // * @throws FileNotFoundException // * @throws IOException // */ // public static void loadYamlServerConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("yaml\\monica.yaml"); // //YamlMonica yamlMonica = yaml.loadAs(new FileInputStream(path), YamlMonica.class); // YamlMonica yamlMonica = yaml.loadAs(Utils.loadResources("yaml/monica.yaml").openStream(), YamlMonica.class); // propMap.putIfAbsent("yamlMonica", yamlMonica); // propMap.putIfAbsent("serverString", yamlMonica.toServerString()); // propMap.putIfAbsent("storage", yamlMonica.getStorage()); // } // // // public static void loadYamlClientConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\client.yaml"); // //YamlClient yamlClient = yaml.loadAs(new FileInputStream(path), YamlClient.class); // YamlClient yamlClient = yaml.loadAs(Utils.loadResources("yaml/client.yaml").openStream(), YamlClient.class); // propMap.putIfAbsent("client", yamlClient); // propMap.putIfAbsent("serverString", yamlClient.toServerString()); // } // // public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\router.yaml"); // //YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class); // YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class); // return yamlRouter.toStringList(); // } // // // private static ClassLoader getClassLoader(){ // return ConfigurationContext.class.getClassLoader(); // } // // public static void main(String args[]){ // try { // //loadYamlServerConfig(); // //YamlMonica monica = (YamlMonica)propMap.get("yamlMonica"); // List<String> rules = loadYamlRouterConfig(); // System.out.println("zk -------- "+rules.get(0)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // // Path: monica-coordinator/src/main/java/monica/coordinator/ConfigService.java // @SPI(ZookeeperConfigService.NAME) // public interface ConfigService { // public void initService() throws Exception; // // public void rulesStore(List<String> rules) throws Exception; // // public void rulesStore() throws Exception; // } // // Path: monica-registry/src/main/java/monica/registry/context/RegistryContext.java // public class RegistryContext { // // caheKey: curatorClient providers server usefulProviders // public static ConcurrentHashMap<String, Object> clientCache = new ConcurrentHashMap<String, Object>(); // }
import java.net.URLEncoder; import java.util.List; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.zookeeper.WatchedEvent; import monica.configuration.context.ConfigurationContext; import monica.coordinator.ConfigService; import monica.registry.context.RegistryContext;
package monica.coordinator.impl.zookeeper; /** * * @author [email protected] * * 2017-08-29 */ public class ZookeeperConfigService implements ConfigService { public final static String NAME = "zookeeper"; private CuratorFramework zkClient = (CuratorFramework) RegistryContext.clientCache.get("curatorClient"); private String rulesBasePath = "/routers"; private String CACHE_PROVIDER = "providers"; private String CACHE_TEMP_PROVIDERS = "temp_providers"; private String PROVIDERS_PATH = "/SERVER"; public void initService() throws Exception { if (null != zkClient.checkExists().forPath(PROVIDERS_PATH)) { RegistryContext.clientCache.putIfAbsent(CACHE_PROVIDER, zkClient.getChildren().forPath(PROVIDERS_PATH)); RegistryContext.clientCache.putIfAbsent(CACHE_TEMP_PROVIDERS, zkClient.getChildren().forPath(PROVIDERS_PATH)); } } public void rulesStore() throws Exception {
// Path: monica-configuration/src/main/java/monica/configuration/context/ConfigurationContext.java // public class ConfigurationContext { // private static String yamlBaseFilePath = "yaml"; // // public static ConcurrentHashMap<String, Object> propMap = new ConcurrentHashMap<String, Object>(); // // /** // * need to adapt to different registry framework. below just be customized to zookeeper // * @throws FileNotFoundException // * @throws IOException // */ // public static void loadYamlServerConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("yaml\\monica.yaml"); // //YamlMonica yamlMonica = yaml.loadAs(new FileInputStream(path), YamlMonica.class); // YamlMonica yamlMonica = yaml.loadAs(Utils.loadResources("yaml/monica.yaml").openStream(), YamlMonica.class); // propMap.putIfAbsent("yamlMonica", yamlMonica); // propMap.putIfAbsent("serverString", yamlMonica.toServerString()); // propMap.putIfAbsent("storage", yamlMonica.getStorage()); // } // // // public static void loadYamlClientConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\client.yaml"); // //YamlClient yamlClient = yaml.loadAs(new FileInputStream(path), YamlClient.class); // YamlClient yamlClient = yaml.loadAs(Utils.loadResources("yaml/client.yaml").openStream(), YamlClient.class); // propMap.putIfAbsent("client", yamlClient); // propMap.putIfAbsent("serverString", yamlClient.toServerString()); // } // // public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\router.yaml"); // //YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class); // YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class); // return yamlRouter.toStringList(); // } // // // private static ClassLoader getClassLoader(){ // return ConfigurationContext.class.getClassLoader(); // } // // public static void main(String args[]){ // try { // //loadYamlServerConfig(); // //YamlMonica monica = (YamlMonica)propMap.get("yamlMonica"); // List<String> rules = loadYamlRouterConfig(); // System.out.println("zk -------- "+rules.get(0)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // // Path: monica-coordinator/src/main/java/monica/coordinator/ConfigService.java // @SPI(ZookeeperConfigService.NAME) // public interface ConfigService { // public void initService() throws Exception; // // public void rulesStore(List<String> rules) throws Exception; // // public void rulesStore() throws Exception; // } // // Path: monica-registry/src/main/java/monica/registry/context/RegistryContext.java // public class RegistryContext { // // caheKey: curatorClient providers server usefulProviders // public static ConcurrentHashMap<String, Object> clientCache = new ConcurrentHashMap<String, Object>(); // } // Path: monica-coordinator/src/main/java/monica/coordinator/impl/zookeeper/ZookeeperConfigService.java import java.net.URLEncoder; import java.util.List; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.zookeeper.WatchedEvent; import monica.configuration.context.ConfigurationContext; import monica.coordinator.ConfigService; import monica.registry.context.RegistryContext; package monica.coordinator.impl.zookeeper; /** * * @author [email protected] * * 2017-08-29 */ public class ZookeeperConfigService implements ConfigService { public final static String NAME = "zookeeper"; private CuratorFramework zkClient = (CuratorFramework) RegistryContext.clientCache.get("curatorClient"); private String rulesBasePath = "/routers"; private String CACHE_PROVIDER = "providers"; private String CACHE_TEMP_PROVIDERS = "temp_providers"; private String PROVIDERS_PATH = "/SERVER"; public void initService() throws Exception { if (null != zkClient.checkExists().forPath(PROVIDERS_PATH)) { RegistryContext.clientCache.putIfAbsent(CACHE_PROVIDER, zkClient.getChildren().forPath(PROVIDERS_PATH)); RegistryContext.clientCache.putIfAbsent(CACHE_TEMP_PROVIDERS, zkClient.getChildren().forPath(PROVIDERS_PATH)); } } public void rulesStore() throws Exception {
rulesStore(ConfigurationContext.loadYamlRouterConfig());
polarcoral/monica
monica-files/monica-files-socket/src/main/java/monica/files/socket/FileServerHandler.java
// Path: monica-configuration/src/main/java/monica/configuration/context/ConfigurationContext.java // public class ConfigurationContext { // private static String yamlBaseFilePath = "yaml"; // // public static ConcurrentHashMap<String, Object> propMap = new ConcurrentHashMap<String, Object>(); // // /** // * need to adapt to different registry framework. below just be customized to zookeeper // * @throws FileNotFoundException // * @throws IOException // */ // public static void loadYamlServerConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("yaml\\monica.yaml"); // //YamlMonica yamlMonica = yaml.loadAs(new FileInputStream(path), YamlMonica.class); // YamlMonica yamlMonica = yaml.loadAs(Utils.loadResources("yaml/monica.yaml").openStream(), YamlMonica.class); // propMap.putIfAbsent("yamlMonica", yamlMonica); // propMap.putIfAbsent("serverString", yamlMonica.toServerString()); // propMap.putIfAbsent("storage", yamlMonica.getStorage()); // } // // // public static void loadYamlClientConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\client.yaml"); // //YamlClient yamlClient = yaml.loadAs(new FileInputStream(path), YamlClient.class); // YamlClient yamlClient = yaml.loadAs(Utils.loadResources("yaml/client.yaml").openStream(), YamlClient.class); // propMap.putIfAbsent("client", yamlClient); // propMap.putIfAbsent("serverString", yamlClient.toServerString()); // } // // public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\router.yaml"); // //YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class); // YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class); // return yamlRouter.toStringList(); // } // // // private static ClassLoader getClassLoader(){ // return ConfigurationContext.class.getClassLoader(); // } // // public static void main(String args[]){ // try { // //loadYamlServerConfig(); // //YamlMonica monica = (YamlMonica)propMap.get("yamlMonica"); // List<String> rules = loadYamlRouterConfig(); // System.out.println("zk -------- "+rules.get(0)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // // Path: monica-framework/src/main/java/monica/framework/Storage.java // public interface Storage { // public void storage(TransportFile file); // // } // // Path: monica-framework/src/main/java/monica/framework/storage/AbstractStorageFactory.java // public abstract class AbstractStorageFactory { // public abstract Storage newStorageInstance(); // } // // Path: monica-framework/src/main/java/monica/framework/transport/TransportFile.java // public class TransportFile implements Serializable{ // // private static final long serialVersionUID = 1L; // private String fileName; // private byte[] content; // // // public String getFileName() { // return fileName; // } // public void setFileName(String fileName) { // this.fileName = fileName; // } // public byte[] getContent() { // return content; // } // public void setContent(byte[] content) { // this.content = content; // } // // // }
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import monica.configuration.context.ConfigurationContext; import monica.framework.Storage; import monica.framework.storage.AbstractStorageFactory; import monica.framework.transport.TransportFile; import io.netty.channel.ChannelHandler.Sharable;
/* * Copyright 2014 The Netty Project * * The Netty Project 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 monica.files.socket; /** * * @author [email protected] * * 2017-08-29 */ @Sharable public class FileServerHandler extends SimpleChannelInboundHandler<Object> { private String STORAGE_CONFIG_KEY = "storage"; private final int poolSize=20; @Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { ExecutorService storageService = Executors.newFixedThreadPool(poolSize);
// Path: monica-configuration/src/main/java/monica/configuration/context/ConfigurationContext.java // public class ConfigurationContext { // private static String yamlBaseFilePath = "yaml"; // // public static ConcurrentHashMap<String, Object> propMap = new ConcurrentHashMap<String, Object>(); // // /** // * need to adapt to different registry framework. below just be customized to zookeeper // * @throws FileNotFoundException // * @throws IOException // */ // public static void loadYamlServerConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("yaml\\monica.yaml"); // //YamlMonica yamlMonica = yaml.loadAs(new FileInputStream(path), YamlMonica.class); // YamlMonica yamlMonica = yaml.loadAs(Utils.loadResources("yaml/monica.yaml").openStream(), YamlMonica.class); // propMap.putIfAbsent("yamlMonica", yamlMonica); // propMap.putIfAbsent("serverString", yamlMonica.toServerString()); // propMap.putIfAbsent("storage", yamlMonica.getStorage()); // } // // // public static void loadYamlClientConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\client.yaml"); // //YamlClient yamlClient = yaml.loadAs(new FileInputStream(path), YamlClient.class); // YamlClient yamlClient = yaml.loadAs(Utils.loadResources("yaml/client.yaml").openStream(), YamlClient.class); // propMap.putIfAbsent("client", yamlClient); // propMap.putIfAbsent("serverString", yamlClient.toServerString()); // } // // public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\router.yaml"); // //YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class); // YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class); // return yamlRouter.toStringList(); // } // // // private static ClassLoader getClassLoader(){ // return ConfigurationContext.class.getClassLoader(); // } // // public static void main(String args[]){ // try { // //loadYamlServerConfig(); // //YamlMonica monica = (YamlMonica)propMap.get("yamlMonica"); // List<String> rules = loadYamlRouterConfig(); // System.out.println("zk -------- "+rules.get(0)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // // Path: monica-framework/src/main/java/monica/framework/Storage.java // public interface Storage { // public void storage(TransportFile file); // // } // // Path: monica-framework/src/main/java/monica/framework/storage/AbstractStorageFactory.java // public abstract class AbstractStorageFactory { // public abstract Storage newStorageInstance(); // } // // Path: monica-framework/src/main/java/monica/framework/transport/TransportFile.java // public class TransportFile implements Serializable{ // // private static final long serialVersionUID = 1L; // private String fileName; // private byte[] content; // // // public String getFileName() { // return fileName; // } // public void setFileName(String fileName) { // this.fileName = fileName; // } // public byte[] getContent() { // return content; // } // public void setContent(byte[] content) { // this.content = content; // } // // // } // Path: monica-files/monica-files-socket/src/main/java/monica/files/socket/FileServerHandler.java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import monica.configuration.context.ConfigurationContext; import monica.framework.Storage; import monica.framework.storage.AbstractStorageFactory; import monica.framework.transport.TransportFile; import io.netty.channel.ChannelHandler.Sharable; /* * Copyright 2014 The Netty Project * * The Netty Project 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 monica.files.socket; /** * * @author [email protected] * * 2017-08-29 */ @Sharable public class FileServerHandler extends SimpleChannelInboundHandler<Object> { private String STORAGE_CONFIG_KEY = "storage"; private final int poolSize=20; @Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { ExecutorService storageService = Executors.newFixedThreadPool(poolSize);
String storageFactoryName = String.valueOf(ConfigurationContext.propMap.get(STORAGE_CONFIG_KEY));
polarcoral/monica
monica-files/monica-files-socket/src/main/java/monica/files/socket/FileServerHandler.java
// Path: monica-configuration/src/main/java/monica/configuration/context/ConfigurationContext.java // public class ConfigurationContext { // private static String yamlBaseFilePath = "yaml"; // // public static ConcurrentHashMap<String, Object> propMap = new ConcurrentHashMap<String, Object>(); // // /** // * need to adapt to different registry framework. below just be customized to zookeeper // * @throws FileNotFoundException // * @throws IOException // */ // public static void loadYamlServerConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("yaml\\monica.yaml"); // //YamlMonica yamlMonica = yaml.loadAs(new FileInputStream(path), YamlMonica.class); // YamlMonica yamlMonica = yaml.loadAs(Utils.loadResources("yaml/monica.yaml").openStream(), YamlMonica.class); // propMap.putIfAbsent("yamlMonica", yamlMonica); // propMap.putIfAbsent("serverString", yamlMonica.toServerString()); // propMap.putIfAbsent("storage", yamlMonica.getStorage()); // } // // // public static void loadYamlClientConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\client.yaml"); // //YamlClient yamlClient = yaml.loadAs(new FileInputStream(path), YamlClient.class); // YamlClient yamlClient = yaml.loadAs(Utils.loadResources("yaml/client.yaml").openStream(), YamlClient.class); // propMap.putIfAbsent("client", yamlClient); // propMap.putIfAbsent("serverString", yamlClient.toServerString()); // } // // public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\router.yaml"); // //YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class); // YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class); // return yamlRouter.toStringList(); // } // // // private static ClassLoader getClassLoader(){ // return ConfigurationContext.class.getClassLoader(); // } // // public static void main(String args[]){ // try { // //loadYamlServerConfig(); // //YamlMonica monica = (YamlMonica)propMap.get("yamlMonica"); // List<String> rules = loadYamlRouterConfig(); // System.out.println("zk -------- "+rules.get(0)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // // Path: monica-framework/src/main/java/monica/framework/Storage.java // public interface Storage { // public void storage(TransportFile file); // // } // // Path: monica-framework/src/main/java/monica/framework/storage/AbstractStorageFactory.java // public abstract class AbstractStorageFactory { // public abstract Storage newStorageInstance(); // } // // Path: monica-framework/src/main/java/monica/framework/transport/TransportFile.java // public class TransportFile implements Serializable{ // // private static final long serialVersionUID = 1L; // private String fileName; // private byte[] content; // // // public String getFileName() { // return fileName; // } // public void setFileName(String fileName) { // this.fileName = fileName; // } // public byte[] getContent() { // return content; // } // public void setContent(byte[] content) { // this.content = content; // } // // // }
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import monica.configuration.context.ConfigurationContext; import monica.framework.Storage; import monica.framework.storage.AbstractStorageFactory; import monica.framework.transport.TransportFile; import io.netty.channel.ChannelHandler.Sharable;
/* * Copyright 2014 The Netty Project * * The Netty Project 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 monica.files.socket; /** * * @author [email protected] * * 2017-08-29 */ @Sharable public class FileServerHandler extends SimpleChannelInboundHandler<Object> { private String STORAGE_CONFIG_KEY = "storage"; private final int poolSize=20; @Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { ExecutorService storageService = Executors.newFixedThreadPool(poolSize); String storageFactoryName = String.valueOf(ConfigurationContext.propMap.get(STORAGE_CONFIG_KEY)); Object o = this.getClass().getClassLoader().loadClass(storageFactoryName).newInstance();
// Path: monica-configuration/src/main/java/monica/configuration/context/ConfigurationContext.java // public class ConfigurationContext { // private static String yamlBaseFilePath = "yaml"; // // public static ConcurrentHashMap<String, Object> propMap = new ConcurrentHashMap<String, Object>(); // // /** // * need to adapt to different registry framework. below just be customized to zookeeper // * @throws FileNotFoundException // * @throws IOException // */ // public static void loadYamlServerConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("yaml\\monica.yaml"); // //YamlMonica yamlMonica = yaml.loadAs(new FileInputStream(path), YamlMonica.class); // YamlMonica yamlMonica = yaml.loadAs(Utils.loadResources("yaml/monica.yaml").openStream(), YamlMonica.class); // propMap.putIfAbsent("yamlMonica", yamlMonica); // propMap.putIfAbsent("serverString", yamlMonica.toServerString()); // propMap.putIfAbsent("storage", yamlMonica.getStorage()); // } // // // public static void loadYamlClientConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\client.yaml"); // //YamlClient yamlClient = yaml.loadAs(new FileInputStream(path), YamlClient.class); // YamlClient yamlClient = yaml.loadAs(Utils.loadResources("yaml/client.yaml").openStream(), YamlClient.class); // propMap.putIfAbsent("client", yamlClient); // propMap.putIfAbsent("serverString", yamlClient.toServerString()); // } // // public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\router.yaml"); // //YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class); // YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class); // return yamlRouter.toStringList(); // } // // // private static ClassLoader getClassLoader(){ // return ConfigurationContext.class.getClassLoader(); // } // // public static void main(String args[]){ // try { // //loadYamlServerConfig(); // //YamlMonica monica = (YamlMonica)propMap.get("yamlMonica"); // List<String> rules = loadYamlRouterConfig(); // System.out.println("zk -------- "+rules.get(0)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // // Path: monica-framework/src/main/java/monica/framework/Storage.java // public interface Storage { // public void storage(TransportFile file); // // } // // Path: monica-framework/src/main/java/monica/framework/storage/AbstractStorageFactory.java // public abstract class AbstractStorageFactory { // public abstract Storage newStorageInstance(); // } // // Path: monica-framework/src/main/java/monica/framework/transport/TransportFile.java // public class TransportFile implements Serializable{ // // private static final long serialVersionUID = 1L; // private String fileName; // private byte[] content; // // // public String getFileName() { // return fileName; // } // public void setFileName(String fileName) { // this.fileName = fileName; // } // public byte[] getContent() { // return content; // } // public void setContent(byte[] content) { // this.content = content; // } // // // } // Path: monica-files/monica-files-socket/src/main/java/monica/files/socket/FileServerHandler.java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import monica.configuration.context.ConfigurationContext; import monica.framework.Storage; import monica.framework.storage.AbstractStorageFactory; import monica.framework.transport.TransportFile; import io.netty.channel.ChannelHandler.Sharable; /* * Copyright 2014 The Netty Project * * The Netty Project 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 monica.files.socket; /** * * @author [email protected] * * 2017-08-29 */ @Sharable public class FileServerHandler extends SimpleChannelInboundHandler<Object> { private String STORAGE_CONFIG_KEY = "storage"; private final int poolSize=20; @Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { ExecutorService storageService = Executors.newFixedThreadPool(poolSize); String storageFactoryName = String.valueOf(ConfigurationContext.propMap.get(STORAGE_CONFIG_KEY)); Object o = this.getClass().getClassLoader().loadClass(storageFactoryName).newInstance();
Storage storage = ((AbstractStorageFactory)o).newStorageInstance();
polarcoral/monica
monica-files/monica-files-socket/src/main/java/monica/files/socket/FileServerHandler.java
// Path: monica-configuration/src/main/java/monica/configuration/context/ConfigurationContext.java // public class ConfigurationContext { // private static String yamlBaseFilePath = "yaml"; // // public static ConcurrentHashMap<String, Object> propMap = new ConcurrentHashMap<String, Object>(); // // /** // * need to adapt to different registry framework. below just be customized to zookeeper // * @throws FileNotFoundException // * @throws IOException // */ // public static void loadYamlServerConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("yaml\\monica.yaml"); // //YamlMonica yamlMonica = yaml.loadAs(new FileInputStream(path), YamlMonica.class); // YamlMonica yamlMonica = yaml.loadAs(Utils.loadResources("yaml/monica.yaml").openStream(), YamlMonica.class); // propMap.putIfAbsent("yamlMonica", yamlMonica); // propMap.putIfAbsent("serverString", yamlMonica.toServerString()); // propMap.putIfAbsent("storage", yamlMonica.getStorage()); // } // // // public static void loadYamlClientConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\client.yaml"); // //YamlClient yamlClient = yaml.loadAs(new FileInputStream(path), YamlClient.class); // YamlClient yamlClient = yaml.loadAs(Utils.loadResources("yaml/client.yaml").openStream(), YamlClient.class); // propMap.putIfAbsent("client", yamlClient); // propMap.putIfAbsent("serverString", yamlClient.toServerString()); // } // // public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\router.yaml"); // //YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class); // YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class); // return yamlRouter.toStringList(); // } // // // private static ClassLoader getClassLoader(){ // return ConfigurationContext.class.getClassLoader(); // } // // public static void main(String args[]){ // try { // //loadYamlServerConfig(); // //YamlMonica monica = (YamlMonica)propMap.get("yamlMonica"); // List<String> rules = loadYamlRouterConfig(); // System.out.println("zk -------- "+rules.get(0)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // // Path: monica-framework/src/main/java/monica/framework/Storage.java // public interface Storage { // public void storage(TransportFile file); // // } // // Path: monica-framework/src/main/java/monica/framework/storage/AbstractStorageFactory.java // public abstract class AbstractStorageFactory { // public abstract Storage newStorageInstance(); // } // // Path: monica-framework/src/main/java/monica/framework/transport/TransportFile.java // public class TransportFile implements Serializable{ // // private static final long serialVersionUID = 1L; // private String fileName; // private byte[] content; // // // public String getFileName() { // return fileName; // } // public void setFileName(String fileName) { // this.fileName = fileName; // } // public byte[] getContent() { // return content; // } // public void setContent(byte[] content) { // this.content = content; // } // // // }
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import monica.configuration.context.ConfigurationContext; import monica.framework.Storage; import monica.framework.storage.AbstractStorageFactory; import monica.framework.transport.TransportFile; import io.netty.channel.ChannelHandler.Sharable;
/* * Copyright 2014 The Netty Project * * The Netty Project 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 monica.files.socket; /** * * @author [email protected] * * 2017-08-29 */ @Sharable public class FileServerHandler extends SimpleChannelInboundHandler<Object> { private String STORAGE_CONFIG_KEY = "storage"; private final int poolSize=20; @Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { ExecutorService storageService = Executors.newFixedThreadPool(poolSize); String storageFactoryName = String.valueOf(ConfigurationContext.propMap.get(STORAGE_CONFIG_KEY)); Object o = this.getClass().getClassLoader().loadClass(storageFactoryName).newInstance();
// Path: monica-configuration/src/main/java/monica/configuration/context/ConfigurationContext.java // public class ConfigurationContext { // private static String yamlBaseFilePath = "yaml"; // // public static ConcurrentHashMap<String, Object> propMap = new ConcurrentHashMap<String, Object>(); // // /** // * need to adapt to different registry framework. below just be customized to zookeeper // * @throws FileNotFoundException // * @throws IOException // */ // public static void loadYamlServerConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("yaml\\monica.yaml"); // //YamlMonica yamlMonica = yaml.loadAs(new FileInputStream(path), YamlMonica.class); // YamlMonica yamlMonica = yaml.loadAs(Utils.loadResources("yaml/monica.yaml").openStream(), YamlMonica.class); // propMap.putIfAbsent("yamlMonica", yamlMonica); // propMap.putIfAbsent("serverString", yamlMonica.toServerString()); // propMap.putIfAbsent("storage", yamlMonica.getStorage()); // } // // // public static void loadYamlClientConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\client.yaml"); // //YamlClient yamlClient = yaml.loadAs(new FileInputStream(path), YamlClient.class); // YamlClient yamlClient = yaml.loadAs(Utils.loadResources("yaml/client.yaml").openStream(), YamlClient.class); // propMap.putIfAbsent("client", yamlClient); // propMap.putIfAbsent("serverString", yamlClient.toServerString()); // } // // public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\router.yaml"); // //YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class); // YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class); // return yamlRouter.toStringList(); // } // // // private static ClassLoader getClassLoader(){ // return ConfigurationContext.class.getClassLoader(); // } // // public static void main(String args[]){ // try { // //loadYamlServerConfig(); // //YamlMonica monica = (YamlMonica)propMap.get("yamlMonica"); // List<String> rules = loadYamlRouterConfig(); // System.out.println("zk -------- "+rules.get(0)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // // Path: monica-framework/src/main/java/monica/framework/Storage.java // public interface Storage { // public void storage(TransportFile file); // // } // // Path: monica-framework/src/main/java/monica/framework/storage/AbstractStorageFactory.java // public abstract class AbstractStorageFactory { // public abstract Storage newStorageInstance(); // } // // Path: monica-framework/src/main/java/monica/framework/transport/TransportFile.java // public class TransportFile implements Serializable{ // // private static final long serialVersionUID = 1L; // private String fileName; // private byte[] content; // // // public String getFileName() { // return fileName; // } // public void setFileName(String fileName) { // this.fileName = fileName; // } // public byte[] getContent() { // return content; // } // public void setContent(byte[] content) { // this.content = content; // } // // // } // Path: monica-files/monica-files-socket/src/main/java/monica/files/socket/FileServerHandler.java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import monica.configuration.context.ConfigurationContext; import monica.framework.Storage; import monica.framework.storage.AbstractStorageFactory; import monica.framework.transport.TransportFile; import io.netty.channel.ChannelHandler.Sharable; /* * Copyright 2014 The Netty Project * * The Netty Project 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 monica.files.socket; /** * * @author [email protected] * * 2017-08-29 */ @Sharable public class FileServerHandler extends SimpleChannelInboundHandler<Object> { private String STORAGE_CONFIG_KEY = "storage"; private final int poolSize=20; @Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { ExecutorService storageService = Executors.newFixedThreadPool(poolSize); String storageFactoryName = String.valueOf(ConfigurationContext.propMap.get(STORAGE_CONFIG_KEY)); Object o = this.getClass().getClassLoader().loadClass(storageFactoryName).newInstance();
Storage storage = ((AbstractStorageFactory)o).newStorageInstance();
polarcoral/monica
monica-files/monica-files-socket/src/main/java/monica/files/socket/FileServerHandler.java
// Path: monica-configuration/src/main/java/monica/configuration/context/ConfigurationContext.java // public class ConfigurationContext { // private static String yamlBaseFilePath = "yaml"; // // public static ConcurrentHashMap<String, Object> propMap = new ConcurrentHashMap<String, Object>(); // // /** // * need to adapt to different registry framework. below just be customized to zookeeper // * @throws FileNotFoundException // * @throws IOException // */ // public static void loadYamlServerConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("yaml\\monica.yaml"); // //YamlMonica yamlMonica = yaml.loadAs(new FileInputStream(path), YamlMonica.class); // YamlMonica yamlMonica = yaml.loadAs(Utils.loadResources("yaml/monica.yaml").openStream(), YamlMonica.class); // propMap.putIfAbsent("yamlMonica", yamlMonica); // propMap.putIfAbsent("serverString", yamlMonica.toServerString()); // propMap.putIfAbsent("storage", yamlMonica.getStorage()); // } // // // public static void loadYamlClientConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\client.yaml"); // //YamlClient yamlClient = yaml.loadAs(new FileInputStream(path), YamlClient.class); // YamlClient yamlClient = yaml.loadAs(Utils.loadResources("yaml/client.yaml").openStream(), YamlClient.class); // propMap.putIfAbsent("client", yamlClient); // propMap.putIfAbsent("serverString", yamlClient.toServerString()); // } // // public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\router.yaml"); // //YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class); // YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class); // return yamlRouter.toStringList(); // } // // // private static ClassLoader getClassLoader(){ // return ConfigurationContext.class.getClassLoader(); // } // // public static void main(String args[]){ // try { // //loadYamlServerConfig(); // //YamlMonica monica = (YamlMonica)propMap.get("yamlMonica"); // List<String> rules = loadYamlRouterConfig(); // System.out.println("zk -------- "+rules.get(0)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // // Path: monica-framework/src/main/java/monica/framework/Storage.java // public interface Storage { // public void storage(TransportFile file); // // } // // Path: monica-framework/src/main/java/monica/framework/storage/AbstractStorageFactory.java // public abstract class AbstractStorageFactory { // public abstract Storage newStorageInstance(); // } // // Path: monica-framework/src/main/java/monica/framework/transport/TransportFile.java // public class TransportFile implements Serializable{ // // private static final long serialVersionUID = 1L; // private String fileName; // private byte[] content; // // // public String getFileName() { // return fileName; // } // public void setFileName(String fileName) { // this.fileName = fileName; // } // public byte[] getContent() { // return content; // } // public void setContent(byte[] content) { // this.content = content; // } // // // }
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import monica.configuration.context.ConfigurationContext; import monica.framework.Storage; import monica.framework.storage.AbstractStorageFactory; import monica.framework.transport.TransportFile; import io.netty.channel.ChannelHandler.Sharable;
/* * Copyright 2014 The Netty Project * * The Netty Project 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 monica.files.socket; /** * * @author [email protected] * * 2017-08-29 */ @Sharable public class FileServerHandler extends SimpleChannelInboundHandler<Object> { private String STORAGE_CONFIG_KEY = "storage"; private final int poolSize=20; @Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { ExecutorService storageService = Executors.newFixedThreadPool(poolSize); String storageFactoryName = String.valueOf(ConfigurationContext.propMap.get(STORAGE_CONFIG_KEY)); Object o = this.getClass().getClassLoader().loadClass(storageFactoryName).newInstance(); Storage storage = ((AbstractStorageFactory)o).newStorageInstance(); storageService.execute(new Runnable(){ @Override public void run() {
// Path: monica-configuration/src/main/java/monica/configuration/context/ConfigurationContext.java // public class ConfigurationContext { // private static String yamlBaseFilePath = "yaml"; // // public static ConcurrentHashMap<String, Object> propMap = new ConcurrentHashMap<String, Object>(); // // /** // * need to adapt to different registry framework. below just be customized to zookeeper // * @throws FileNotFoundException // * @throws IOException // */ // public static void loadYamlServerConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("yaml\\monica.yaml"); // //YamlMonica yamlMonica = yaml.loadAs(new FileInputStream(path), YamlMonica.class); // YamlMonica yamlMonica = yaml.loadAs(Utils.loadResources("yaml/monica.yaml").openStream(), YamlMonica.class); // propMap.putIfAbsent("yamlMonica", yamlMonica); // propMap.putIfAbsent("serverString", yamlMonica.toServerString()); // propMap.putIfAbsent("storage", yamlMonica.getStorage()); // } // // // public static void loadYamlClientConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\client.yaml"); // //YamlClient yamlClient = yaml.loadAs(new FileInputStream(path), YamlClient.class); // YamlClient yamlClient = yaml.loadAs(Utils.loadResources("yaml/client.yaml").openStream(), YamlClient.class); // propMap.putIfAbsent("client", yamlClient); // propMap.putIfAbsent("serverString", yamlClient.toServerString()); // } // // public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\router.yaml"); // //YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class); // YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class); // return yamlRouter.toStringList(); // } // // // private static ClassLoader getClassLoader(){ // return ConfigurationContext.class.getClassLoader(); // } // // public static void main(String args[]){ // try { // //loadYamlServerConfig(); // //YamlMonica monica = (YamlMonica)propMap.get("yamlMonica"); // List<String> rules = loadYamlRouterConfig(); // System.out.println("zk -------- "+rules.get(0)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // // Path: monica-framework/src/main/java/monica/framework/Storage.java // public interface Storage { // public void storage(TransportFile file); // // } // // Path: monica-framework/src/main/java/monica/framework/storage/AbstractStorageFactory.java // public abstract class AbstractStorageFactory { // public abstract Storage newStorageInstance(); // } // // Path: monica-framework/src/main/java/monica/framework/transport/TransportFile.java // public class TransportFile implements Serializable{ // // private static final long serialVersionUID = 1L; // private String fileName; // private byte[] content; // // // public String getFileName() { // return fileName; // } // public void setFileName(String fileName) { // this.fileName = fileName; // } // public byte[] getContent() { // return content; // } // public void setContent(byte[] content) { // this.content = content; // } // // // } // Path: monica-files/monica-files-socket/src/main/java/monica/files/socket/FileServerHandler.java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import monica.configuration.context.ConfigurationContext; import monica.framework.Storage; import monica.framework.storage.AbstractStorageFactory; import monica.framework.transport.TransportFile; import io.netty.channel.ChannelHandler.Sharable; /* * Copyright 2014 The Netty Project * * The Netty Project 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 monica.files.socket; /** * * @author [email protected] * * 2017-08-29 */ @Sharable public class FileServerHandler extends SimpleChannelInboundHandler<Object> { private String STORAGE_CONFIG_KEY = "storage"; private final int poolSize=20; @Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { ExecutorService storageService = Executors.newFixedThreadPool(poolSize); String storageFactoryName = String.valueOf(ConfigurationContext.propMap.get(STORAGE_CONFIG_KEY)); Object o = this.getClass().getClassLoader().loadClass(storageFactoryName).newInstance(); Storage storage = ((AbstractStorageFactory)o).newStorageInstance(); storageService.execute(new Runnable(){ @Override public void run() {
storage.storage((TransportFile)msg);
polarcoral/monica
monica-coordinator/src/main/java/monica/coordinator/impl/ConfigServiceFactory.java
// Path: monica-coordinator/src/main/java/monica/coordinator/ConfigService.java // @SPI(ZookeeperConfigService.NAME) // public interface ConfigService { // public void initService() throws Exception; // // public void rulesStore(List<String> rules) throws Exception; // // public void rulesStore() throws Exception; // } // // Path: monica-framework/src/main/java/monica/framework/extension/ExtensionProvider.java // public class ExtensionProvider { // private static final String basePath = "META-INF/monica/internal"; // // public static Class<?> getDefaultExtension(Class<?> c) throws ClassNotFoundException { // SPI cSpi = c.getAnnotation(SPI.class); // String spiValue = cSpi.value(); // String fileName = c.getName(); // String className = loadFile(fileName, spiValue); // return getClassLoader().loadClass(className); // } // // private static String loadFile(String fileName, String key) { // URL url = getClassLoader().getResource(basePath + "/" + fileName); // if (null != url) { // try { // BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); // String line = ""; // // while ((line = reader.readLine()) != null) { // int index = line.trim().indexOf("="); // if (index > 0 && line.substring(0, index).equals(key)) { // return line.substring(index + 1); // } // } // // } catch (UnsupportedEncodingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return null; // } // // private static ClassLoader getClassLoader() { // return ExtensionProvider.class.getClassLoader(); // } // // public static void main(String args[]) { // ExtensionProvider provider = new ExtensionProvider(); // //provider.getDefaultExtension(ConfigService.class); // } // }
import monica.coordinator.ConfigService; import monica.framework.extension.ExtensionProvider;
package monica.coordinator.impl; /** * * @author [email protected] * * 2017-08-29 */ public class ConfigServiceFactory { public static ConfigService getConfigService() throws InstantiationException, ClassNotFoundException, IllegalAccessException {
// Path: monica-coordinator/src/main/java/monica/coordinator/ConfigService.java // @SPI(ZookeeperConfigService.NAME) // public interface ConfigService { // public void initService() throws Exception; // // public void rulesStore(List<String> rules) throws Exception; // // public void rulesStore() throws Exception; // } // // Path: monica-framework/src/main/java/monica/framework/extension/ExtensionProvider.java // public class ExtensionProvider { // private static final String basePath = "META-INF/monica/internal"; // // public static Class<?> getDefaultExtension(Class<?> c) throws ClassNotFoundException { // SPI cSpi = c.getAnnotation(SPI.class); // String spiValue = cSpi.value(); // String fileName = c.getName(); // String className = loadFile(fileName, spiValue); // return getClassLoader().loadClass(className); // } // // private static String loadFile(String fileName, String key) { // URL url = getClassLoader().getResource(basePath + "/" + fileName); // if (null != url) { // try { // BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); // String line = ""; // // while ((line = reader.readLine()) != null) { // int index = line.trim().indexOf("="); // if (index > 0 && line.substring(0, index).equals(key)) { // return line.substring(index + 1); // } // } // // } catch (UnsupportedEncodingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return null; // } // // private static ClassLoader getClassLoader() { // return ExtensionProvider.class.getClassLoader(); // } // // public static void main(String args[]) { // ExtensionProvider provider = new ExtensionProvider(); // //provider.getDefaultExtension(ConfigService.class); // } // } // Path: monica-coordinator/src/main/java/monica/coordinator/impl/ConfigServiceFactory.java import monica.coordinator.ConfigService; import monica.framework.extension.ExtensionProvider; package monica.coordinator.impl; /** * * @author [email protected] * * 2017-08-29 */ public class ConfigServiceFactory { public static ConfigService getConfigService() throws InstantiationException, ClassNotFoundException, IllegalAccessException {
ConfigService service = (ConfigService) ExtensionProvider.getDefaultExtension(ConfigService.class)
polarcoral/monica
monica-cluster/src/main/java/monica/cluster/router/parse/BlockedParser.java
// Path: monica-cluster/src/main/java/monica/cluster/Parser.java // public interface Parser { // public void doParse(Rule rule); // // public boolean isExpected(); // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Rule.java // public class Rule implements Comparable<Rule> { // private Host source; // private Host destination; // private int priority; // // public Host getSource() { // return source; // } // // public void setSource(Host source) { // this.source = source; // } // // public Host getDestination() { // return destination; // } // // public void setDestination(Host destination) { // this.destination = destination; // } // // public int getPriority() { // return priority; // } // // public void setPriority(int priority) { // // this.priority = priority; // } // // public String toString() { // if (null != source && null != destination) { // return source + "=>" + destination; // } else if (null != source && null == destination) { // return source + "=>"; // } else if (null == source && null != destination) { // return "=>" + destination; // } else { // return ""; // } // // } // // public int compareTo(Rule o) { // if (this.priority < o.priority) // return -1; // return 1; // } // // }
import monica.cluster.Parser; import monica.cluster.router.parse.object.Rule;
package monica.cluster.router.parse; /** * * @author [email protected] * * 2017-08-29 */ public class BlockedParser implements Parser { private volatile boolean parseResult = false;
// Path: monica-cluster/src/main/java/monica/cluster/Parser.java // public interface Parser { // public void doParse(Rule rule); // // public boolean isExpected(); // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Rule.java // public class Rule implements Comparable<Rule> { // private Host source; // private Host destination; // private int priority; // // public Host getSource() { // return source; // } // // public void setSource(Host source) { // this.source = source; // } // // public Host getDestination() { // return destination; // } // // public void setDestination(Host destination) { // this.destination = destination; // } // // public int getPriority() { // return priority; // } // // public void setPriority(int priority) { // // this.priority = priority; // } // // public String toString() { // if (null != source && null != destination) { // return source + "=>" + destination; // } else if (null != source && null == destination) { // return source + "=>"; // } else if (null == source && null != destination) { // return "=>" + destination; // } else { // return ""; // } // // } // // public int compareTo(Rule o) { // if (this.priority < o.priority) // return -1; // return 1; // } // // } // Path: monica-cluster/src/main/java/monica/cluster/router/parse/BlockedParser.java import monica.cluster.Parser; import monica.cluster.router.parse.object.Rule; package monica.cluster.router.parse; /** * * @author [email protected] * * 2017-08-29 */ public class BlockedParser implements Parser { private volatile boolean parseResult = false;
public void doParse(Rule rule) {
polarcoral/monica
monica-cluster/src/main/java/monica/cluster/router/parse/StringToObjectParser.java
// Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Host.java // public class Host { // private List<String> ips; // private Operator ops; // // public List<String> getIps() { // return ips; // } // // public void setIps(List<String> ips) { // this.ips = ips; // } // // public Operator getOps() { // return ops; // } // // public void setOps(Operator ops) { // this.ops = ops; // } // // public String toString() { // StringBuilder stringBuilder = new StringBuilder(); // stringBuilder.append("host"); // if (ops.equals(Operator.INCLUDE)) { // stringBuilder.append("="); // } else { // stringBuilder.append("!="); // } // for (String s : ips) { // if (ips.indexOf(s) != (ips.size() - 1)) { // stringBuilder.append(s + ","); // } else { // stringBuilder.append(s); // } // } // return stringBuilder.toString(); // } // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Operator.java // public enum Operator { // INCLUDE, EXCLUDE // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Rule.java // public class Rule implements Comparable<Rule> { // private Host source; // private Host destination; // private int priority; // // public Host getSource() { // return source; // } // // public void setSource(Host source) { // this.source = source; // } // // public Host getDestination() { // return destination; // } // // public void setDestination(Host destination) { // this.destination = destination; // } // // public int getPriority() { // return priority; // } // // public void setPriority(int priority) { // // this.priority = priority; // } // // public String toString() { // if (null != source && null != destination) { // return source + "=>" + destination; // } else if (null != source && null == destination) { // return source + "=>"; // } else if (null == source && null != destination) { // return "=>" + destination; // } else { // return ""; // } // // } // // public int compareTo(Rule o) { // if (this.priority < o.priority) // return -1; // return 1; // } // // }
import java.util.Arrays; import monica.cluster.router.parse.object.Host; import monica.cluster.router.parse.object.Operator; import monica.cluster.router.parse.object.Rule;
package monica.cluster.router.parse; /** * * @author [email protected] * * 2017-08-29 */ public class StringToObjectParser { public Rule parseRuleStringToRule(String rule) { int index = rule.lastIndexOf(","); int priorityIndex = rule.lastIndexOf("="); String hostString = rule.trim().substring(rule.indexOf("['") + 2, index - 1).trim(); String[] hosts = hostString.split("=>"); Rule r = new Rule(); if (hostString.trim().indexOf("=>") == 0 && hosts.length > 0) { r.setDestination(this.parseHostStringToHost(hosts[0])); } else if (hostString.trim().indexOf("=>") == (hostString.trim().length() - 2) && hosts.length > 0) { r.setSource(this.parseHostStringToHost(hosts[0])); } else { r.setSource(this.parseHostStringToHost(hosts[0])); r.setSource(this.parseHostStringToHost(hosts[1])); } /* * List<Rule> rList = new ArrayList<Rule>(); rList.sort(new * Comparator<Rule>(){ public int compare(Rule o1, Rule o2) { return * o1.compareTo(o2); } * * }); */ r.setPriority(Integer.valueOf(rule.substring(priorityIndex + 1, rule.length() - 1))); return r; }
// Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Host.java // public class Host { // private List<String> ips; // private Operator ops; // // public List<String> getIps() { // return ips; // } // // public void setIps(List<String> ips) { // this.ips = ips; // } // // public Operator getOps() { // return ops; // } // // public void setOps(Operator ops) { // this.ops = ops; // } // // public String toString() { // StringBuilder stringBuilder = new StringBuilder(); // stringBuilder.append("host"); // if (ops.equals(Operator.INCLUDE)) { // stringBuilder.append("="); // } else { // stringBuilder.append("!="); // } // for (String s : ips) { // if (ips.indexOf(s) != (ips.size() - 1)) { // stringBuilder.append(s + ","); // } else { // stringBuilder.append(s); // } // } // return stringBuilder.toString(); // } // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Operator.java // public enum Operator { // INCLUDE, EXCLUDE // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Rule.java // public class Rule implements Comparable<Rule> { // private Host source; // private Host destination; // private int priority; // // public Host getSource() { // return source; // } // // public void setSource(Host source) { // this.source = source; // } // // public Host getDestination() { // return destination; // } // // public void setDestination(Host destination) { // this.destination = destination; // } // // public int getPriority() { // return priority; // } // // public void setPriority(int priority) { // // this.priority = priority; // } // // public String toString() { // if (null != source && null != destination) { // return source + "=>" + destination; // } else if (null != source && null == destination) { // return source + "=>"; // } else if (null == source && null != destination) { // return "=>" + destination; // } else { // return ""; // } // // } // // public int compareTo(Rule o) { // if (this.priority < o.priority) // return -1; // return 1; // } // // } // Path: monica-cluster/src/main/java/monica/cluster/router/parse/StringToObjectParser.java import java.util.Arrays; import monica.cluster.router.parse.object.Host; import monica.cluster.router.parse.object.Operator; import monica.cluster.router.parse.object.Rule; package monica.cluster.router.parse; /** * * @author [email protected] * * 2017-08-29 */ public class StringToObjectParser { public Rule parseRuleStringToRule(String rule) { int index = rule.lastIndexOf(","); int priorityIndex = rule.lastIndexOf("="); String hostString = rule.trim().substring(rule.indexOf("['") + 2, index - 1).trim(); String[] hosts = hostString.split("=>"); Rule r = new Rule(); if (hostString.trim().indexOf("=>") == 0 && hosts.length > 0) { r.setDestination(this.parseHostStringToHost(hosts[0])); } else if (hostString.trim().indexOf("=>") == (hostString.trim().length() - 2) && hosts.length > 0) { r.setSource(this.parseHostStringToHost(hosts[0])); } else { r.setSource(this.parseHostStringToHost(hosts[0])); r.setSource(this.parseHostStringToHost(hosts[1])); } /* * List<Rule> rList = new ArrayList<Rule>(); rList.sort(new * Comparator<Rule>(){ public int compare(Rule o1, Rule o2) { return * o1.compareTo(o2); } * * }); */ r.setPriority(Integer.valueOf(rule.substring(priorityIndex + 1, rule.length() - 1))); return r; }
private Host parseHostStringToHost(String host) {
polarcoral/monica
monica-cluster/src/main/java/monica/cluster/router/parse/StringToObjectParser.java
// Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Host.java // public class Host { // private List<String> ips; // private Operator ops; // // public List<String> getIps() { // return ips; // } // // public void setIps(List<String> ips) { // this.ips = ips; // } // // public Operator getOps() { // return ops; // } // // public void setOps(Operator ops) { // this.ops = ops; // } // // public String toString() { // StringBuilder stringBuilder = new StringBuilder(); // stringBuilder.append("host"); // if (ops.equals(Operator.INCLUDE)) { // stringBuilder.append("="); // } else { // stringBuilder.append("!="); // } // for (String s : ips) { // if (ips.indexOf(s) != (ips.size() - 1)) { // stringBuilder.append(s + ","); // } else { // stringBuilder.append(s); // } // } // return stringBuilder.toString(); // } // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Operator.java // public enum Operator { // INCLUDE, EXCLUDE // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Rule.java // public class Rule implements Comparable<Rule> { // private Host source; // private Host destination; // private int priority; // // public Host getSource() { // return source; // } // // public void setSource(Host source) { // this.source = source; // } // // public Host getDestination() { // return destination; // } // // public void setDestination(Host destination) { // this.destination = destination; // } // // public int getPriority() { // return priority; // } // // public void setPriority(int priority) { // // this.priority = priority; // } // // public String toString() { // if (null != source && null != destination) { // return source + "=>" + destination; // } else if (null != source && null == destination) { // return source + "=>"; // } else if (null == source && null != destination) { // return "=>" + destination; // } else { // return ""; // } // // } // // public int compareTo(Rule o) { // if (this.priority < o.priority) // return -1; // return 1; // } // // }
import java.util.Arrays; import monica.cluster.router.parse.object.Host; import monica.cluster.router.parse.object.Operator; import monica.cluster.router.parse.object.Rule;
package monica.cluster.router.parse; /** * * @author [email protected] * * 2017-08-29 */ public class StringToObjectParser { public Rule parseRuleStringToRule(String rule) { int index = rule.lastIndexOf(","); int priorityIndex = rule.lastIndexOf("="); String hostString = rule.trim().substring(rule.indexOf("['") + 2, index - 1).trim(); String[] hosts = hostString.split("=>"); Rule r = new Rule(); if (hostString.trim().indexOf("=>") == 0 && hosts.length > 0) { r.setDestination(this.parseHostStringToHost(hosts[0])); } else if (hostString.trim().indexOf("=>") == (hostString.trim().length() - 2) && hosts.length > 0) { r.setSource(this.parseHostStringToHost(hosts[0])); } else { r.setSource(this.parseHostStringToHost(hosts[0])); r.setSource(this.parseHostStringToHost(hosts[1])); } /* * List<Rule> rList = new ArrayList<Rule>(); rList.sort(new * Comparator<Rule>(){ public int compare(Rule o1, Rule o2) { return * o1.compareTo(o2); } * * }); */ r.setPriority(Integer.valueOf(rule.substring(priorityIndex + 1, rule.length() - 1))); return r; } private Host parseHostStringToHost(String host) { Host h; if (null != host && !host.trim().equals("")) { h = new Host(); if (host.indexOf("=") != -1) { if (host.indexOf("!") != -1) { h.setIps(Arrays.asList(host.substring(host.indexOf("!=")).split(",")));
// Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Host.java // public class Host { // private List<String> ips; // private Operator ops; // // public List<String> getIps() { // return ips; // } // // public void setIps(List<String> ips) { // this.ips = ips; // } // // public Operator getOps() { // return ops; // } // // public void setOps(Operator ops) { // this.ops = ops; // } // // public String toString() { // StringBuilder stringBuilder = new StringBuilder(); // stringBuilder.append("host"); // if (ops.equals(Operator.INCLUDE)) { // stringBuilder.append("="); // } else { // stringBuilder.append("!="); // } // for (String s : ips) { // if (ips.indexOf(s) != (ips.size() - 1)) { // stringBuilder.append(s + ","); // } else { // stringBuilder.append(s); // } // } // return stringBuilder.toString(); // } // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Operator.java // public enum Operator { // INCLUDE, EXCLUDE // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Rule.java // public class Rule implements Comparable<Rule> { // private Host source; // private Host destination; // private int priority; // // public Host getSource() { // return source; // } // // public void setSource(Host source) { // this.source = source; // } // // public Host getDestination() { // return destination; // } // // public void setDestination(Host destination) { // this.destination = destination; // } // // public int getPriority() { // return priority; // } // // public void setPriority(int priority) { // // this.priority = priority; // } // // public String toString() { // if (null != source && null != destination) { // return source + "=>" + destination; // } else if (null != source && null == destination) { // return source + "=>"; // } else if (null == source && null != destination) { // return "=>" + destination; // } else { // return ""; // } // // } // // public int compareTo(Rule o) { // if (this.priority < o.priority) // return -1; // return 1; // } // // } // Path: monica-cluster/src/main/java/monica/cluster/router/parse/StringToObjectParser.java import java.util.Arrays; import monica.cluster.router.parse.object.Host; import monica.cluster.router.parse.object.Operator; import monica.cluster.router.parse.object.Rule; package monica.cluster.router.parse; /** * * @author [email protected] * * 2017-08-29 */ public class StringToObjectParser { public Rule parseRuleStringToRule(String rule) { int index = rule.lastIndexOf(","); int priorityIndex = rule.lastIndexOf("="); String hostString = rule.trim().substring(rule.indexOf("['") + 2, index - 1).trim(); String[] hosts = hostString.split("=>"); Rule r = new Rule(); if (hostString.trim().indexOf("=>") == 0 && hosts.length > 0) { r.setDestination(this.parseHostStringToHost(hosts[0])); } else if (hostString.trim().indexOf("=>") == (hostString.trim().length() - 2) && hosts.length > 0) { r.setSource(this.parseHostStringToHost(hosts[0])); } else { r.setSource(this.parseHostStringToHost(hosts[0])); r.setSource(this.parseHostStringToHost(hosts[1])); } /* * List<Rule> rList = new ArrayList<Rule>(); rList.sort(new * Comparator<Rule>(){ public int compare(Rule o1, Rule o2) { return * o1.compareTo(o2); } * * }); */ r.setPriority(Integer.valueOf(rule.substring(priorityIndex + 1, rule.length() - 1))); return r; } private Host parseHostStringToHost(String host) { Host h; if (null != host && !host.trim().equals("")) { h = new Host(); if (host.indexOf("=") != -1) { if (host.indexOf("!") != -1) { h.setIps(Arrays.asList(host.substring(host.indexOf("!=")).split(",")));
h.setOps(Operator.EXCLUDE);
polarcoral/monica
monica-examples/src/main/java/monica/examples/storage/StorageOnDisk.java
// Path: monica-framework/src/main/java/monica/framework/Storage.java // public interface Storage { // public void storage(TransportFile file); // // } // // Path: monica-framework/src/main/java/monica/framework/transport/TransportFile.java // public class TransportFile implements Serializable{ // // private static final long serialVersionUID = 1L; // private String fileName; // private byte[] content; // // // public String getFileName() { // return fileName; // } // public void setFileName(String fileName) { // this.fileName = fileName; // } // public byte[] getContent() { // return content; // } // public void setContent(byte[] content) { // this.content = content; // } // // // }
import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.StandardOpenOption; import monica.framework.Storage; import monica.framework.transport.TransportFile;
package monica.examples.storage; public class StorageOnDisk implements Storage { @Override
// Path: monica-framework/src/main/java/monica/framework/Storage.java // public interface Storage { // public void storage(TransportFile file); // // } // // Path: monica-framework/src/main/java/monica/framework/transport/TransportFile.java // public class TransportFile implements Serializable{ // // private static final long serialVersionUID = 1L; // private String fileName; // private byte[] content; // // // public String getFileName() { // return fileName; // } // public void setFileName(String fileName) { // this.fileName = fileName; // } // public byte[] getContent() { // return content; // } // public void setContent(byte[] content) { // this.content = content; // } // // // } // Path: monica-examples/src/main/java/monica/examples/storage/StorageOnDisk.java import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.StandardOpenOption; import monica.framework.Storage; import monica.framework.transport.TransportFile; package monica.examples.storage; public class StorageOnDisk implements Storage { @Override
public void storage(TransportFile receivedFile) {
polarcoral/monica
monica-coordinator/src/main/java/monica/coordinator/config/ConfigServiceInit.java
// Path: monica-coordinator/src/main/java/monica/coordinator/ConfigService.java // @SPI(ZookeeperConfigService.NAME) // public interface ConfigService { // public void initService() throws Exception; // // public void rulesStore(List<String> rules) throws Exception; // // public void rulesStore() throws Exception; // } // // Path: monica-framework/src/main/java/monica/framework/extension/ExtensionProvider.java // public class ExtensionProvider { // private static final String basePath = "META-INF/monica/internal"; // // public static Class<?> getDefaultExtension(Class<?> c) throws ClassNotFoundException { // SPI cSpi = c.getAnnotation(SPI.class); // String spiValue = cSpi.value(); // String fileName = c.getName(); // String className = loadFile(fileName, spiValue); // return getClassLoader().loadClass(className); // } // // private static String loadFile(String fileName, String key) { // URL url = getClassLoader().getResource(basePath + "/" + fileName); // if (null != url) { // try { // BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); // String line = ""; // // while ((line = reader.readLine()) != null) { // int index = line.trim().indexOf("="); // if (index > 0 && line.substring(0, index).equals(key)) { // return line.substring(index + 1); // } // } // // } catch (UnsupportedEncodingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return null; // } // // private static ClassLoader getClassLoader() { // return ExtensionProvider.class.getClassLoader(); // } // // public static void main(String args[]) { // ExtensionProvider provider = new ExtensionProvider(); // //provider.getDefaultExtension(ConfigService.class); // } // }
import monica.coordinator.ConfigService; import monica.framework.extension.ExtensionProvider;
package monica.coordinator.config; /** * * @author [email protected] * * 2017-08-29 */ public class ConfigServiceInit { public static void init() { try {
// Path: monica-coordinator/src/main/java/monica/coordinator/ConfigService.java // @SPI(ZookeeperConfigService.NAME) // public interface ConfigService { // public void initService() throws Exception; // // public void rulesStore(List<String> rules) throws Exception; // // public void rulesStore() throws Exception; // } // // Path: monica-framework/src/main/java/monica/framework/extension/ExtensionProvider.java // public class ExtensionProvider { // private static final String basePath = "META-INF/monica/internal"; // // public static Class<?> getDefaultExtension(Class<?> c) throws ClassNotFoundException { // SPI cSpi = c.getAnnotation(SPI.class); // String spiValue = cSpi.value(); // String fileName = c.getName(); // String className = loadFile(fileName, spiValue); // return getClassLoader().loadClass(className); // } // // private static String loadFile(String fileName, String key) { // URL url = getClassLoader().getResource(basePath + "/" + fileName); // if (null != url) { // try { // BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); // String line = ""; // // while ((line = reader.readLine()) != null) { // int index = line.trim().indexOf("="); // if (index > 0 && line.substring(0, index).equals(key)) { // return line.substring(index + 1); // } // } // // } catch (UnsupportedEncodingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return null; // } // // private static ClassLoader getClassLoader() { // return ExtensionProvider.class.getClassLoader(); // } // // public static void main(String args[]) { // ExtensionProvider provider = new ExtensionProvider(); // //provider.getDefaultExtension(ConfigService.class); // } // } // Path: monica-coordinator/src/main/java/monica/coordinator/config/ConfigServiceInit.java import monica.coordinator.ConfigService; import monica.framework.extension.ExtensionProvider; package monica.coordinator.config; /** * * @author [email protected] * * 2017-08-29 */ public class ConfigServiceInit { public static void init() { try {
ConfigService configService = (ConfigService) ExtensionProvider.getDefaultExtension(ConfigService.class)
polarcoral/monica
monica-coordinator/src/main/java/monica/coordinator/config/ConfigServiceInit.java
// Path: monica-coordinator/src/main/java/monica/coordinator/ConfigService.java // @SPI(ZookeeperConfigService.NAME) // public interface ConfigService { // public void initService() throws Exception; // // public void rulesStore(List<String> rules) throws Exception; // // public void rulesStore() throws Exception; // } // // Path: monica-framework/src/main/java/monica/framework/extension/ExtensionProvider.java // public class ExtensionProvider { // private static final String basePath = "META-INF/monica/internal"; // // public static Class<?> getDefaultExtension(Class<?> c) throws ClassNotFoundException { // SPI cSpi = c.getAnnotation(SPI.class); // String spiValue = cSpi.value(); // String fileName = c.getName(); // String className = loadFile(fileName, spiValue); // return getClassLoader().loadClass(className); // } // // private static String loadFile(String fileName, String key) { // URL url = getClassLoader().getResource(basePath + "/" + fileName); // if (null != url) { // try { // BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); // String line = ""; // // while ((line = reader.readLine()) != null) { // int index = line.trim().indexOf("="); // if (index > 0 && line.substring(0, index).equals(key)) { // return line.substring(index + 1); // } // } // // } catch (UnsupportedEncodingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return null; // } // // private static ClassLoader getClassLoader() { // return ExtensionProvider.class.getClassLoader(); // } // // public static void main(String args[]) { // ExtensionProvider provider = new ExtensionProvider(); // //provider.getDefaultExtension(ConfigService.class); // } // }
import monica.coordinator.ConfigService; import monica.framework.extension.ExtensionProvider;
package monica.coordinator.config; /** * * @author [email protected] * * 2017-08-29 */ public class ConfigServiceInit { public static void init() { try {
// Path: monica-coordinator/src/main/java/monica/coordinator/ConfigService.java // @SPI(ZookeeperConfigService.NAME) // public interface ConfigService { // public void initService() throws Exception; // // public void rulesStore(List<String> rules) throws Exception; // // public void rulesStore() throws Exception; // } // // Path: monica-framework/src/main/java/monica/framework/extension/ExtensionProvider.java // public class ExtensionProvider { // private static final String basePath = "META-INF/monica/internal"; // // public static Class<?> getDefaultExtension(Class<?> c) throws ClassNotFoundException { // SPI cSpi = c.getAnnotation(SPI.class); // String spiValue = cSpi.value(); // String fileName = c.getName(); // String className = loadFile(fileName, spiValue); // return getClassLoader().loadClass(className); // } // // private static String loadFile(String fileName, String key) { // URL url = getClassLoader().getResource(basePath + "/" + fileName); // if (null != url) { // try { // BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); // String line = ""; // // while ((line = reader.readLine()) != null) { // int index = line.trim().indexOf("="); // if (index > 0 && line.substring(0, index).equals(key)) { // return line.substring(index + 1); // } // } // // } catch (UnsupportedEncodingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return null; // } // // private static ClassLoader getClassLoader() { // return ExtensionProvider.class.getClassLoader(); // } // // public static void main(String args[]) { // ExtensionProvider provider = new ExtensionProvider(); // //provider.getDefaultExtension(ConfigService.class); // } // } // Path: monica-coordinator/src/main/java/monica/coordinator/config/ConfigServiceInit.java import monica.coordinator.ConfigService; import monica.framework.extension.ExtensionProvider; package monica.coordinator.config; /** * * @author [email protected] * * 2017-08-29 */ public class ConfigServiceInit { public static void init() { try {
ConfigService configService = (ConfigService) ExtensionProvider.getDefaultExtension(ConfigService.class)
polarcoral/monica
monica-files/monica-files-socket/src/main/java/monica/files/socket/SocketClient.java
// Path: monica-configuration/src/main/java/monica/configuration/context/ConfigurationContext.java // public class ConfigurationContext { // private static String yamlBaseFilePath = "yaml"; // // public static ConcurrentHashMap<String, Object> propMap = new ConcurrentHashMap<String, Object>(); // // /** // * need to adapt to different registry framework. below just be customized to zookeeper // * @throws FileNotFoundException // * @throws IOException // */ // public static void loadYamlServerConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("yaml\\monica.yaml"); // //YamlMonica yamlMonica = yaml.loadAs(new FileInputStream(path), YamlMonica.class); // YamlMonica yamlMonica = yaml.loadAs(Utils.loadResources("yaml/monica.yaml").openStream(), YamlMonica.class); // propMap.putIfAbsent("yamlMonica", yamlMonica); // propMap.putIfAbsent("serverString", yamlMonica.toServerString()); // propMap.putIfAbsent("storage", yamlMonica.getStorage()); // } // // // public static void loadYamlClientConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\client.yaml"); // //YamlClient yamlClient = yaml.loadAs(new FileInputStream(path), YamlClient.class); // YamlClient yamlClient = yaml.loadAs(Utils.loadResources("yaml/client.yaml").openStream(), YamlClient.class); // propMap.putIfAbsent("client", yamlClient); // propMap.putIfAbsent("serverString", yamlClient.toServerString()); // } // // public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\router.yaml"); // //YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class); // YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class); // return yamlRouter.toStringList(); // } // // // private static ClassLoader getClassLoader(){ // return ConfigurationContext.class.getClassLoader(); // } // // public static void main(String args[]){ // try { // //loadYamlServerConfig(); // //YamlMonica monica = (YamlMonica)propMap.get("yamlMonica"); // List<String> rules = loadYamlRouterConfig(); // System.out.println("zk -------- "+rules.get(0)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // // Path: monica-framework/src/main/java/monica/framework/Client.java // public interface Client { // public void start(String ip, int port) throws Exception; // public boolean isStarted(); // }
import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.util.InsecureTrustManagerFactory; import monica.configuration.context.ConfigurationContext; import monica.framework.Client;
package monica.files.socket; /** * * @author [email protected] * * 2017-08-29 */ public class SocketClient implements Client { public final static String NAME = "socket"; private final String SOCKET_CHANNEL = "channel"; private volatile boolean isStarted = false; static final boolean SSL = System.getProperty("ssl") != null; public void start(String ip, int port) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new FileClientInitializer(sslCtx)); Channel ch = b.connect(ip, port).sync().channel();
// Path: monica-configuration/src/main/java/monica/configuration/context/ConfigurationContext.java // public class ConfigurationContext { // private static String yamlBaseFilePath = "yaml"; // // public static ConcurrentHashMap<String, Object> propMap = new ConcurrentHashMap<String, Object>(); // // /** // * need to adapt to different registry framework. below just be customized to zookeeper // * @throws FileNotFoundException // * @throws IOException // */ // public static void loadYamlServerConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("yaml\\monica.yaml"); // //YamlMonica yamlMonica = yaml.loadAs(new FileInputStream(path), YamlMonica.class); // YamlMonica yamlMonica = yaml.loadAs(Utils.loadResources("yaml/monica.yaml").openStream(), YamlMonica.class); // propMap.putIfAbsent("yamlMonica", yamlMonica); // propMap.putIfAbsent("serverString", yamlMonica.toServerString()); // propMap.putIfAbsent("storage", yamlMonica.getStorage()); // } // // // public static void loadYamlClientConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\client.yaml"); // //YamlClient yamlClient = yaml.loadAs(new FileInputStream(path), YamlClient.class); // YamlClient yamlClient = yaml.loadAs(Utils.loadResources("yaml/client.yaml").openStream(), YamlClient.class); // propMap.putIfAbsent("client", yamlClient); // propMap.putIfAbsent("serverString", yamlClient.toServerString()); // } // // public static List<String> loadYamlRouterConfig() throws FileNotFoundException, IOException{ // Yaml yaml = new Yaml(); // File path = Utils.getPropertiesPath("\\yaml\\router.yaml"); // //YamlRouter yamlRouter = yaml.loadAs(new FileInputStream(path), YamlRouter.class); // YamlRouter yamlRouter = yaml.loadAs(Utils.loadResources("yaml/router.yaml").openStream(), YamlRouter.class); // return yamlRouter.toStringList(); // } // // // private static ClassLoader getClassLoader(){ // return ConfigurationContext.class.getClassLoader(); // } // // public static void main(String args[]){ // try { // //loadYamlServerConfig(); // //YamlMonica monica = (YamlMonica)propMap.get("yamlMonica"); // List<String> rules = loadYamlRouterConfig(); // System.out.println("zk -------- "+rules.get(0)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // // Path: monica-framework/src/main/java/monica/framework/Client.java // public interface Client { // public void start(String ip, int port) throws Exception; // public boolean isStarted(); // } // Path: monica-files/monica-files-socket/src/main/java/monica/files/socket/SocketClient.java import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.util.InsecureTrustManagerFactory; import monica.configuration.context.ConfigurationContext; import monica.framework.Client; package monica.files.socket; /** * * @author [email protected] * * 2017-08-29 */ public class SocketClient implements Client { public final static String NAME = "socket"; private final String SOCKET_CHANNEL = "channel"; private volatile boolean isStarted = false; static final boolean SSL = System.getProperty("ssl") != null; public void start(String ip, int port) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new FileClientInitializer(sslCtx)); Channel ch = b.connect(ip, port).sync().channel();
ConfigurationContext.propMap.putIfAbsent(SOCKET_CHANNEL, ch);
polarcoral/monica
monica-examples/src/main/java/monica/examples/MonicaClient.java
// Path: monica-framework/src/main/java/monica/framework/tools/Utils.java // public class Utils { // public static File getPropertiesPath(String propertiesName) { // String[] pathArray = System.getProperty("java.class.path").split(";"); // for (String s : pathArray) { // File newFile = new File(s + File.separator + propertiesName); // if (newFile.exists()) { // return newFile; // } // } // return null; // } // // public static URL loadResources(String propertiesName) throws IOException { // String[] pathArray = System.getProperty("java.class.path").split(";"); // URL inURL = Utils.class.getClassLoader().getResource(propertiesName); // if (null !=inURL) { // return inURL; // } // return null; // } // // } // // Path: monica-framework/src/main/java/monica/framework/transport/TransportFile.java // public class TransportFile implements Serializable{ // // private static final long serialVersionUID = 1L; // private String fileName; // private byte[] content; // // // public String getFileName() { // return fileName; // } // public void setFileName(String fileName) { // this.fileName = fileName; // } // public byte[] getContent() { // return content; // } // public void setContent(byte[] content) { // this.content = content; // } // // // } // // Path: monica-starter/src/main/java/monica/starter/client/ClientStarter.java // public class ClientStarter { // private final Logger log = LoggerFactory.getLogger(getClass()); // private final String SERVER_IP_CACHE = "server_ip"; // private final String SERVER_PORT_CACHE = "server_port"; // private final String SOCKET_CHANNEL = "channel"; // // public void start() throws Exception { // ConfigurationContext.loadYamlClientConfig(); // new ZookeeperMonicaClient().start(); // new ServiceBuilder().servicesInit().route().loadbalance().build(); // String ip = (String) RegistryContext.clientCache.get(SERVER_IP_CACHE); // int port = Integer.valueOf((String) RegistryContext.clientCache.get(SERVER_PORT_CACHE)); // Client client = ClientFactory.newFactory().getConsumerClient(); // Executors.newSingleThreadExecutor().execute(new NettyRunnable(client, ip, port)); // for (;;) { // if (client.isStarted()) { // new RegistryCentre().setUri(createUri()).setType(RegistryType.CLIENT).start(); // if (RegistryCentre.registryFinished()) { // log.info("monica client start successfully!"); // } // break; // } // } // // } // // // register the consumer // private UriSpec createUri() { // return new UriSpec(); // } // // // public Channel getSocketChannel(){ // return (Channel)ConfigurationContext.propMap.get(SOCKET_CHANNEL); // } // // public static void main(String args[]) { // ClientStarter container = new ClientStarter(); // try { // container.start(); // } catch (Exception e) { // e.printStackTrace(); // } // } // }
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Properties; import java.util.concurrent.Executors; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import monica.framework.tools.Utils; import monica.framework.transport.TransportFile; import monica.starter.client.ClientStarter;
/* * Copyright 2017 The Monica Project * * The Monica Project 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 monica.examples; /** * * @author [email protected] * * 2017-08-29 */ public class MonicaClient { public static void main(String args[]) throws FileNotFoundException, IOException { Properties pps = new Properties();
// Path: monica-framework/src/main/java/monica/framework/tools/Utils.java // public class Utils { // public static File getPropertiesPath(String propertiesName) { // String[] pathArray = System.getProperty("java.class.path").split(";"); // for (String s : pathArray) { // File newFile = new File(s + File.separator + propertiesName); // if (newFile.exists()) { // return newFile; // } // } // return null; // } // // public static URL loadResources(String propertiesName) throws IOException { // String[] pathArray = System.getProperty("java.class.path").split(";"); // URL inURL = Utils.class.getClassLoader().getResource(propertiesName); // if (null !=inURL) { // return inURL; // } // return null; // } // // } // // Path: monica-framework/src/main/java/monica/framework/transport/TransportFile.java // public class TransportFile implements Serializable{ // // private static final long serialVersionUID = 1L; // private String fileName; // private byte[] content; // // // public String getFileName() { // return fileName; // } // public void setFileName(String fileName) { // this.fileName = fileName; // } // public byte[] getContent() { // return content; // } // public void setContent(byte[] content) { // this.content = content; // } // // // } // // Path: monica-starter/src/main/java/monica/starter/client/ClientStarter.java // public class ClientStarter { // private final Logger log = LoggerFactory.getLogger(getClass()); // private final String SERVER_IP_CACHE = "server_ip"; // private final String SERVER_PORT_CACHE = "server_port"; // private final String SOCKET_CHANNEL = "channel"; // // public void start() throws Exception { // ConfigurationContext.loadYamlClientConfig(); // new ZookeeperMonicaClient().start(); // new ServiceBuilder().servicesInit().route().loadbalance().build(); // String ip = (String) RegistryContext.clientCache.get(SERVER_IP_CACHE); // int port = Integer.valueOf((String) RegistryContext.clientCache.get(SERVER_PORT_CACHE)); // Client client = ClientFactory.newFactory().getConsumerClient(); // Executors.newSingleThreadExecutor().execute(new NettyRunnable(client, ip, port)); // for (;;) { // if (client.isStarted()) { // new RegistryCentre().setUri(createUri()).setType(RegistryType.CLIENT).start(); // if (RegistryCentre.registryFinished()) { // log.info("monica client start successfully!"); // } // break; // } // } // // } // // // register the consumer // private UriSpec createUri() { // return new UriSpec(); // } // // // public Channel getSocketChannel(){ // return (Channel)ConfigurationContext.propMap.get(SOCKET_CHANNEL); // } // // public static void main(String args[]) { // ClientStarter container = new ClientStarter(); // try { // container.start(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // Path: monica-examples/src/main/java/monica/examples/MonicaClient.java import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Properties; import java.util.concurrent.Executors; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import monica.framework.tools.Utils; import monica.framework.transport.TransportFile; import monica.starter.client.ClientStarter; /* * Copyright 2017 The Monica Project * * The Monica Project 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 monica.examples; /** * * @author [email protected] * * 2017-08-29 */ public class MonicaClient { public static void main(String args[]) throws FileNotFoundException, IOException { Properties pps = new Properties();
File file = Utils.getPropertiesPath("path.properties");
polarcoral/monica
monica-examples/src/main/java/monica/examples/MonicaClient.java
// Path: monica-framework/src/main/java/monica/framework/tools/Utils.java // public class Utils { // public static File getPropertiesPath(String propertiesName) { // String[] pathArray = System.getProperty("java.class.path").split(";"); // for (String s : pathArray) { // File newFile = new File(s + File.separator + propertiesName); // if (newFile.exists()) { // return newFile; // } // } // return null; // } // // public static URL loadResources(String propertiesName) throws IOException { // String[] pathArray = System.getProperty("java.class.path").split(";"); // URL inURL = Utils.class.getClassLoader().getResource(propertiesName); // if (null !=inURL) { // return inURL; // } // return null; // } // // } // // Path: monica-framework/src/main/java/monica/framework/transport/TransportFile.java // public class TransportFile implements Serializable{ // // private static final long serialVersionUID = 1L; // private String fileName; // private byte[] content; // // // public String getFileName() { // return fileName; // } // public void setFileName(String fileName) { // this.fileName = fileName; // } // public byte[] getContent() { // return content; // } // public void setContent(byte[] content) { // this.content = content; // } // // // } // // Path: monica-starter/src/main/java/monica/starter/client/ClientStarter.java // public class ClientStarter { // private final Logger log = LoggerFactory.getLogger(getClass()); // private final String SERVER_IP_CACHE = "server_ip"; // private final String SERVER_PORT_CACHE = "server_port"; // private final String SOCKET_CHANNEL = "channel"; // // public void start() throws Exception { // ConfigurationContext.loadYamlClientConfig(); // new ZookeeperMonicaClient().start(); // new ServiceBuilder().servicesInit().route().loadbalance().build(); // String ip = (String) RegistryContext.clientCache.get(SERVER_IP_CACHE); // int port = Integer.valueOf((String) RegistryContext.clientCache.get(SERVER_PORT_CACHE)); // Client client = ClientFactory.newFactory().getConsumerClient(); // Executors.newSingleThreadExecutor().execute(new NettyRunnable(client, ip, port)); // for (;;) { // if (client.isStarted()) { // new RegistryCentre().setUri(createUri()).setType(RegistryType.CLIENT).start(); // if (RegistryCentre.registryFinished()) { // log.info("monica client start successfully!"); // } // break; // } // } // // } // // // register the consumer // private UriSpec createUri() { // return new UriSpec(); // } // // // public Channel getSocketChannel(){ // return (Channel)ConfigurationContext.propMap.get(SOCKET_CHANNEL); // } // // public static void main(String args[]) { // ClientStarter container = new ClientStarter(); // try { // container.start(); // } catch (Exception e) { // e.printStackTrace(); // } // } // }
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Properties; import java.util.concurrent.Executors; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import monica.framework.tools.Utils; import monica.framework.transport.TransportFile; import monica.starter.client.ClientStarter;
/* * Copyright 2017 The Monica Project * * The Monica Project 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 monica.examples; /** * * @author [email protected] * * 2017-08-29 */ public class MonicaClient { public static void main(String args[]) throws FileNotFoundException, IOException { Properties pps = new Properties(); File file = Utils.getPropertiesPath("path.properties"); pps.load(new FileInputStream(file)); String filePath = pps.getProperty("client.path");
// Path: monica-framework/src/main/java/monica/framework/tools/Utils.java // public class Utils { // public static File getPropertiesPath(String propertiesName) { // String[] pathArray = System.getProperty("java.class.path").split(";"); // for (String s : pathArray) { // File newFile = new File(s + File.separator + propertiesName); // if (newFile.exists()) { // return newFile; // } // } // return null; // } // // public static URL loadResources(String propertiesName) throws IOException { // String[] pathArray = System.getProperty("java.class.path").split(";"); // URL inURL = Utils.class.getClassLoader().getResource(propertiesName); // if (null !=inURL) { // return inURL; // } // return null; // } // // } // // Path: monica-framework/src/main/java/monica/framework/transport/TransportFile.java // public class TransportFile implements Serializable{ // // private static final long serialVersionUID = 1L; // private String fileName; // private byte[] content; // // // public String getFileName() { // return fileName; // } // public void setFileName(String fileName) { // this.fileName = fileName; // } // public byte[] getContent() { // return content; // } // public void setContent(byte[] content) { // this.content = content; // } // // // } // // Path: monica-starter/src/main/java/monica/starter/client/ClientStarter.java // public class ClientStarter { // private final Logger log = LoggerFactory.getLogger(getClass()); // private final String SERVER_IP_CACHE = "server_ip"; // private final String SERVER_PORT_CACHE = "server_port"; // private final String SOCKET_CHANNEL = "channel"; // // public void start() throws Exception { // ConfigurationContext.loadYamlClientConfig(); // new ZookeeperMonicaClient().start(); // new ServiceBuilder().servicesInit().route().loadbalance().build(); // String ip = (String) RegistryContext.clientCache.get(SERVER_IP_CACHE); // int port = Integer.valueOf((String) RegistryContext.clientCache.get(SERVER_PORT_CACHE)); // Client client = ClientFactory.newFactory().getConsumerClient(); // Executors.newSingleThreadExecutor().execute(new NettyRunnable(client, ip, port)); // for (;;) { // if (client.isStarted()) { // new RegistryCentre().setUri(createUri()).setType(RegistryType.CLIENT).start(); // if (RegistryCentre.registryFinished()) { // log.info("monica client start successfully!"); // } // break; // } // } // // } // // // register the consumer // private UriSpec createUri() { // return new UriSpec(); // } // // // public Channel getSocketChannel(){ // return (Channel)ConfigurationContext.propMap.get(SOCKET_CHANNEL); // } // // public static void main(String args[]) { // ClientStarter container = new ClientStarter(); // try { // container.start(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // Path: monica-examples/src/main/java/monica/examples/MonicaClient.java import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Properties; import java.util.concurrent.Executors; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import monica.framework.tools.Utils; import monica.framework.transport.TransportFile; import monica.starter.client.ClientStarter; /* * Copyright 2017 The Monica Project * * The Monica Project 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 monica.examples; /** * * @author [email protected] * * 2017-08-29 */ public class MonicaClient { public static void main(String args[]) throws FileNotFoundException, IOException { Properties pps = new Properties(); File file = Utils.getPropertiesPath("path.properties"); pps.load(new FileInputStream(file)); String filePath = pps.getProperty("client.path");
ClientStarter clientContainer = new ClientStarter();
polarcoral/monica
monica-examples/src/main/java/monica/examples/MonicaClient.java
// Path: monica-framework/src/main/java/monica/framework/tools/Utils.java // public class Utils { // public static File getPropertiesPath(String propertiesName) { // String[] pathArray = System.getProperty("java.class.path").split(";"); // for (String s : pathArray) { // File newFile = new File(s + File.separator + propertiesName); // if (newFile.exists()) { // return newFile; // } // } // return null; // } // // public static URL loadResources(String propertiesName) throws IOException { // String[] pathArray = System.getProperty("java.class.path").split(";"); // URL inURL = Utils.class.getClassLoader().getResource(propertiesName); // if (null !=inURL) { // return inURL; // } // return null; // } // // } // // Path: monica-framework/src/main/java/monica/framework/transport/TransportFile.java // public class TransportFile implements Serializable{ // // private static final long serialVersionUID = 1L; // private String fileName; // private byte[] content; // // // public String getFileName() { // return fileName; // } // public void setFileName(String fileName) { // this.fileName = fileName; // } // public byte[] getContent() { // return content; // } // public void setContent(byte[] content) { // this.content = content; // } // // // } // // Path: monica-starter/src/main/java/monica/starter/client/ClientStarter.java // public class ClientStarter { // private final Logger log = LoggerFactory.getLogger(getClass()); // private final String SERVER_IP_CACHE = "server_ip"; // private final String SERVER_PORT_CACHE = "server_port"; // private final String SOCKET_CHANNEL = "channel"; // // public void start() throws Exception { // ConfigurationContext.loadYamlClientConfig(); // new ZookeeperMonicaClient().start(); // new ServiceBuilder().servicesInit().route().loadbalance().build(); // String ip = (String) RegistryContext.clientCache.get(SERVER_IP_CACHE); // int port = Integer.valueOf((String) RegistryContext.clientCache.get(SERVER_PORT_CACHE)); // Client client = ClientFactory.newFactory().getConsumerClient(); // Executors.newSingleThreadExecutor().execute(new NettyRunnable(client, ip, port)); // for (;;) { // if (client.isStarted()) { // new RegistryCentre().setUri(createUri()).setType(RegistryType.CLIENT).start(); // if (RegistryCentre.registryFinished()) { // log.info("monica client start successfully!"); // } // break; // } // } // // } // // // register the consumer // private UriSpec createUri() { // return new UriSpec(); // } // // // public Channel getSocketChannel(){ // return (Channel)ConfigurationContext.propMap.get(SOCKET_CHANNEL); // } // // public static void main(String args[]) { // ClientStarter container = new ClientStarter(); // try { // container.start(); // } catch (Exception e) { // e.printStackTrace(); // } // } // }
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Properties; import java.util.concurrent.Executors; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import monica.framework.tools.Utils; import monica.framework.transport.TransportFile; import monica.starter.client.ClientStarter;
pps.load(new FileInputStream(file)); String filePath = pps.getProperty("client.path"); ClientStarter clientContainer = new ClientStarter(); Channel ch; Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { try { clientContainer.start(); } catch (Exception e) { e.printStackTrace(); } } }); for (;;) { ch = clientContainer.getSocketChannel(); if (null != ch) { break; } } try { File[] fileList = new File(filePath).listFiles(); for (int i = 0; i < fileList.length; i++) { FileChannel channel = (new FileInputStream(fileList[i])).getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size()); while (channel.read(byteBuffer) > 0) ;
// Path: monica-framework/src/main/java/monica/framework/tools/Utils.java // public class Utils { // public static File getPropertiesPath(String propertiesName) { // String[] pathArray = System.getProperty("java.class.path").split(";"); // for (String s : pathArray) { // File newFile = new File(s + File.separator + propertiesName); // if (newFile.exists()) { // return newFile; // } // } // return null; // } // // public static URL loadResources(String propertiesName) throws IOException { // String[] pathArray = System.getProperty("java.class.path").split(";"); // URL inURL = Utils.class.getClassLoader().getResource(propertiesName); // if (null !=inURL) { // return inURL; // } // return null; // } // // } // // Path: monica-framework/src/main/java/monica/framework/transport/TransportFile.java // public class TransportFile implements Serializable{ // // private static final long serialVersionUID = 1L; // private String fileName; // private byte[] content; // // // public String getFileName() { // return fileName; // } // public void setFileName(String fileName) { // this.fileName = fileName; // } // public byte[] getContent() { // return content; // } // public void setContent(byte[] content) { // this.content = content; // } // // // } // // Path: monica-starter/src/main/java/monica/starter/client/ClientStarter.java // public class ClientStarter { // private final Logger log = LoggerFactory.getLogger(getClass()); // private final String SERVER_IP_CACHE = "server_ip"; // private final String SERVER_PORT_CACHE = "server_port"; // private final String SOCKET_CHANNEL = "channel"; // // public void start() throws Exception { // ConfigurationContext.loadYamlClientConfig(); // new ZookeeperMonicaClient().start(); // new ServiceBuilder().servicesInit().route().loadbalance().build(); // String ip = (String) RegistryContext.clientCache.get(SERVER_IP_CACHE); // int port = Integer.valueOf((String) RegistryContext.clientCache.get(SERVER_PORT_CACHE)); // Client client = ClientFactory.newFactory().getConsumerClient(); // Executors.newSingleThreadExecutor().execute(new NettyRunnable(client, ip, port)); // for (;;) { // if (client.isStarted()) { // new RegistryCentre().setUri(createUri()).setType(RegistryType.CLIENT).start(); // if (RegistryCentre.registryFinished()) { // log.info("monica client start successfully!"); // } // break; // } // } // // } // // // register the consumer // private UriSpec createUri() { // return new UriSpec(); // } // // // public Channel getSocketChannel(){ // return (Channel)ConfigurationContext.propMap.get(SOCKET_CHANNEL); // } // // public static void main(String args[]) { // ClientStarter container = new ClientStarter(); // try { // container.start(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // Path: monica-examples/src/main/java/monica/examples/MonicaClient.java import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Properties; import java.util.concurrent.Executors; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import monica.framework.tools.Utils; import monica.framework.transport.TransportFile; import monica.starter.client.ClientStarter; pps.load(new FileInputStream(file)); String filePath = pps.getProperty("client.path"); ClientStarter clientContainer = new ClientStarter(); Channel ch; Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { try { clientContainer.start(); } catch (Exception e) { e.printStackTrace(); } } }); for (;;) { ch = clientContainer.getSocketChannel(); if (null != ch) { break; } } try { File[] fileList = new File(filePath).listFiles(); for (int i = 0; i < fileList.length; i++) { FileChannel channel = (new FileInputStream(fileList[i])).getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size()); while (channel.read(byteBuffer) > 0) ;
TransportFile transportFile = new TransportFile();
polarcoral/monica
monica-cluster/src/main/java/monica/cluster/AbstractParser.java
// Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Operator.java // public enum Operator { // INCLUDE, EXCLUDE // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Rule.java // public class Rule implements Comparable<Rule> { // private Host source; // private Host destination; // private int priority; // // public Host getSource() { // return source; // } // // public void setSource(Host source) { // this.source = source; // } // // public Host getDestination() { // return destination; // } // // public void setDestination(Host destination) { // this.destination = destination; // } // // public int getPriority() { // return priority; // } // // public void setPriority(int priority) { // // this.priority = priority; // } // // public String toString() { // if (null != source && null != destination) { // return source + "=>" + destination; // } else if (null != source && null == destination) { // return source + "=>"; // } else if (null == source && null != destination) { // return "=>" + destination; // } else { // return ""; // } // // } // // public int compareTo(Rule o) { // if (this.priority < o.priority) // return -1; // return 1; // } // // }
import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import monica.cluster.router.parse.object.Operator; import monica.cluster.router.parse.object.Rule;
package monica.cluster; /** * * @author [email protected] * * 2017-08-29 */ public class AbstractParser { public void routeToIps(Rule rule, List<String> temp_providers) {
// Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Operator.java // public enum Operator { // INCLUDE, EXCLUDE // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Rule.java // public class Rule implements Comparable<Rule> { // private Host source; // private Host destination; // private int priority; // // public Host getSource() { // return source; // } // // public void setSource(Host source) { // this.source = source; // } // // public Host getDestination() { // return destination; // } // // public void setDestination(Host destination) { // this.destination = destination; // } // // public int getPriority() { // return priority; // } // // public void setPriority(int priority) { // // this.priority = priority; // } // // public String toString() { // if (null != source && null != destination) { // return source + "=>" + destination; // } else if (null != source && null == destination) { // return source + "=>"; // } else if (null == source && null != destination) { // return "=>" + destination; // } else { // return ""; // } // // } // // public int compareTo(Rule o) { // if (this.priority < o.priority) // return -1; // return 1; // } // // } // Path: monica-cluster/src/main/java/monica/cluster/AbstractParser.java import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import monica.cluster.router.parse.object.Operator; import monica.cluster.router.parse.object.Rule; package monica.cluster; /** * * @author [email protected] * * 2017-08-29 */ public class AbstractParser { public void routeToIps(Rule rule, List<String> temp_providers) {
if (rule.getDestination().getOps().equals(Operator.INCLUDE)) {
polarcoral/monica
monica-registry/src/main/java/monica/registry/centre/RegistryCentre.java
// Path: monica-registry/src/main/java/monica/registry/Registration.java // @SPI(ZookeeperRegistration.NAME) // public interface Registration { // final Logger log = Logger.getLogger(Registration.class); // // public void register(UriSpec uri, RegistryType type) throws Exception; // // public boolean done(); // // } // // Path: monica-registry/src/main/java/monica/registry/base/RegistryType.java // public enum RegistryType { // SERVER, CLIENT // } // // Path: monica-registry/src/main/java/monica/registry/base/UriSpec.java // public class UriSpec { // private String scheme; // private String ip; // private String port; // // public String getScheme() { // return scheme; // } // // public void setScheme(String scheme) { // this.scheme = scheme; // } // // public String getIp() { // return ip; // } // // public void setIp(String ip) { // this.ip = ip; // } // // public String getPort() { // return port; // } // // public void setPort(String port) { // this.port = port; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // if (null == scheme || scheme.equals("")) { // sb.append("monica://"); // } else { // sb.append(scheme); // } // if (null != ip && !ip.equals("")) { // sb.append(ip); // } // sb.append(":"); // if (null != port && !port.equals("")) { // sb.append(port); // } // return sb.toString(); // } // // } // // Path: monica-registry/src/main/java/monica/registry/service/RegistrationFactory.java // public class RegistrationFactory { // // public static Registration getRegistryService() // throws InstantiationException, ClassNotFoundException, IllegalAccessException { // Registration service = (Registration) ExtensionProvider.getDefaultExtension(Registration.class).newInstance(); // // return service; // } // // }
import monica.registry.Registration; import monica.registry.base.RegistryType; import monica.registry.base.UriSpec; import monica.registry.service.RegistrationFactory;
package monica.registry.centre; /** * * @author [email protected] * * 2017-08-29 */ public class RegistryCentre { public void start() throws Exception {
// Path: monica-registry/src/main/java/monica/registry/Registration.java // @SPI(ZookeeperRegistration.NAME) // public interface Registration { // final Logger log = Logger.getLogger(Registration.class); // // public void register(UriSpec uri, RegistryType type) throws Exception; // // public boolean done(); // // } // // Path: monica-registry/src/main/java/monica/registry/base/RegistryType.java // public enum RegistryType { // SERVER, CLIENT // } // // Path: monica-registry/src/main/java/monica/registry/base/UriSpec.java // public class UriSpec { // private String scheme; // private String ip; // private String port; // // public String getScheme() { // return scheme; // } // // public void setScheme(String scheme) { // this.scheme = scheme; // } // // public String getIp() { // return ip; // } // // public void setIp(String ip) { // this.ip = ip; // } // // public String getPort() { // return port; // } // // public void setPort(String port) { // this.port = port; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // if (null == scheme || scheme.equals("")) { // sb.append("monica://"); // } else { // sb.append(scheme); // } // if (null != ip && !ip.equals("")) { // sb.append(ip); // } // sb.append(":"); // if (null != port && !port.equals("")) { // sb.append(port); // } // return sb.toString(); // } // // } // // Path: monica-registry/src/main/java/monica/registry/service/RegistrationFactory.java // public class RegistrationFactory { // // public static Registration getRegistryService() // throws InstantiationException, ClassNotFoundException, IllegalAccessException { // Registration service = (Registration) ExtensionProvider.getDefaultExtension(Registration.class).newInstance(); // // return service; // } // // } // Path: monica-registry/src/main/java/monica/registry/centre/RegistryCentre.java import monica.registry.Registration; import monica.registry.base.RegistryType; import monica.registry.base.UriSpec; import monica.registry.service.RegistrationFactory; package monica.registry.centre; /** * * @author [email protected] * * 2017-08-29 */ public class RegistryCentre { public void start() throws Exception {
Registration service = RegistrationFactory.getRegistryService();
polarcoral/monica
monica-registry/src/main/java/monica/registry/centre/RegistryCentre.java
// Path: monica-registry/src/main/java/monica/registry/Registration.java // @SPI(ZookeeperRegistration.NAME) // public interface Registration { // final Logger log = Logger.getLogger(Registration.class); // // public void register(UriSpec uri, RegistryType type) throws Exception; // // public boolean done(); // // } // // Path: monica-registry/src/main/java/monica/registry/base/RegistryType.java // public enum RegistryType { // SERVER, CLIENT // } // // Path: monica-registry/src/main/java/monica/registry/base/UriSpec.java // public class UriSpec { // private String scheme; // private String ip; // private String port; // // public String getScheme() { // return scheme; // } // // public void setScheme(String scheme) { // this.scheme = scheme; // } // // public String getIp() { // return ip; // } // // public void setIp(String ip) { // this.ip = ip; // } // // public String getPort() { // return port; // } // // public void setPort(String port) { // this.port = port; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // if (null == scheme || scheme.equals("")) { // sb.append("monica://"); // } else { // sb.append(scheme); // } // if (null != ip && !ip.equals("")) { // sb.append(ip); // } // sb.append(":"); // if (null != port && !port.equals("")) { // sb.append(port); // } // return sb.toString(); // } // // } // // Path: monica-registry/src/main/java/monica/registry/service/RegistrationFactory.java // public class RegistrationFactory { // // public static Registration getRegistryService() // throws InstantiationException, ClassNotFoundException, IllegalAccessException { // Registration service = (Registration) ExtensionProvider.getDefaultExtension(Registration.class).newInstance(); // // return service; // } // // }
import monica.registry.Registration; import monica.registry.base.RegistryType; import monica.registry.base.UriSpec; import monica.registry.service.RegistrationFactory;
package monica.registry.centre; /** * * @author [email protected] * * 2017-08-29 */ public class RegistryCentre { public void start() throws Exception {
// Path: monica-registry/src/main/java/monica/registry/Registration.java // @SPI(ZookeeperRegistration.NAME) // public interface Registration { // final Logger log = Logger.getLogger(Registration.class); // // public void register(UriSpec uri, RegistryType type) throws Exception; // // public boolean done(); // // } // // Path: monica-registry/src/main/java/monica/registry/base/RegistryType.java // public enum RegistryType { // SERVER, CLIENT // } // // Path: monica-registry/src/main/java/monica/registry/base/UriSpec.java // public class UriSpec { // private String scheme; // private String ip; // private String port; // // public String getScheme() { // return scheme; // } // // public void setScheme(String scheme) { // this.scheme = scheme; // } // // public String getIp() { // return ip; // } // // public void setIp(String ip) { // this.ip = ip; // } // // public String getPort() { // return port; // } // // public void setPort(String port) { // this.port = port; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // if (null == scheme || scheme.equals("")) { // sb.append("monica://"); // } else { // sb.append(scheme); // } // if (null != ip && !ip.equals("")) { // sb.append(ip); // } // sb.append(":"); // if (null != port && !port.equals("")) { // sb.append(port); // } // return sb.toString(); // } // // } // // Path: monica-registry/src/main/java/monica/registry/service/RegistrationFactory.java // public class RegistrationFactory { // // public static Registration getRegistryService() // throws InstantiationException, ClassNotFoundException, IllegalAccessException { // Registration service = (Registration) ExtensionProvider.getDefaultExtension(Registration.class).newInstance(); // // return service; // } // // } // Path: monica-registry/src/main/java/monica/registry/centre/RegistryCentre.java import monica.registry.Registration; import monica.registry.base.RegistryType; import monica.registry.base.UriSpec; import monica.registry.service.RegistrationFactory; package monica.registry.centre; /** * * @author [email protected] * * 2017-08-29 */ public class RegistryCentre { public void start() throws Exception {
Registration service = RegistrationFactory.getRegistryService();
polarcoral/monica
monica-registry/src/main/java/monica/registry/centre/RegistryCentre.java
// Path: monica-registry/src/main/java/monica/registry/Registration.java // @SPI(ZookeeperRegistration.NAME) // public interface Registration { // final Logger log = Logger.getLogger(Registration.class); // // public void register(UriSpec uri, RegistryType type) throws Exception; // // public boolean done(); // // } // // Path: monica-registry/src/main/java/monica/registry/base/RegistryType.java // public enum RegistryType { // SERVER, CLIENT // } // // Path: monica-registry/src/main/java/monica/registry/base/UriSpec.java // public class UriSpec { // private String scheme; // private String ip; // private String port; // // public String getScheme() { // return scheme; // } // // public void setScheme(String scheme) { // this.scheme = scheme; // } // // public String getIp() { // return ip; // } // // public void setIp(String ip) { // this.ip = ip; // } // // public String getPort() { // return port; // } // // public void setPort(String port) { // this.port = port; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // if (null == scheme || scheme.equals("")) { // sb.append("monica://"); // } else { // sb.append(scheme); // } // if (null != ip && !ip.equals("")) { // sb.append(ip); // } // sb.append(":"); // if (null != port && !port.equals("")) { // sb.append(port); // } // return sb.toString(); // } // // } // // Path: monica-registry/src/main/java/monica/registry/service/RegistrationFactory.java // public class RegistrationFactory { // // public static Registration getRegistryService() // throws InstantiationException, ClassNotFoundException, IllegalAccessException { // Registration service = (Registration) ExtensionProvider.getDefaultExtension(Registration.class).newInstance(); // // return service; // } // // }
import monica.registry.Registration; import monica.registry.base.RegistryType; import monica.registry.base.UriSpec; import monica.registry.service.RegistrationFactory;
package monica.registry.centre; /** * * @author [email protected] * * 2017-08-29 */ public class RegistryCentre { public void start() throws Exception { Registration service = RegistrationFactory.getRegistryService(); service.register(getUri(), getType()); } public static boolean registryFinished() { return true; }
// Path: monica-registry/src/main/java/monica/registry/Registration.java // @SPI(ZookeeperRegistration.NAME) // public interface Registration { // final Logger log = Logger.getLogger(Registration.class); // // public void register(UriSpec uri, RegistryType type) throws Exception; // // public boolean done(); // // } // // Path: monica-registry/src/main/java/monica/registry/base/RegistryType.java // public enum RegistryType { // SERVER, CLIENT // } // // Path: monica-registry/src/main/java/monica/registry/base/UriSpec.java // public class UriSpec { // private String scheme; // private String ip; // private String port; // // public String getScheme() { // return scheme; // } // // public void setScheme(String scheme) { // this.scheme = scheme; // } // // public String getIp() { // return ip; // } // // public void setIp(String ip) { // this.ip = ip; // } // // public String getPort() { // return port; // } // // public void setPort(String port) { // this.port = port; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // if (null == scheme || scheme.equals("")) { // sb.append("monica://"); // } else { // sb.append(scheme); // } // if (null != ip && !ip.equals("")) { // sb.append(ip); // } // sb.append(":"); // if (null != port && !port.equals("")) { // sb.append(port); // } // return sb.toString(); // } // // } // // Path: monica-registry/src/main/java/monica/registry/service/RegistrationFactory.java // public class RegistrationFactory { // // public static Registration getRegistryService() // throws InstantiationException, ClassNotFoundException, IllegalAccessException { // Registration service = (Registration) ExtensionProvider.getDefaultExtension(Registration.class).newInstance(); // // return service; // } // // } // Path: monica-registry/src/main/java/monica/registry/centre/RegistryCentre.java import monica.registry.Registration; import monica.registry.base.RegistryType; import monica.registry.base.UriSpec; import monica.registry.service.RegistrationFactory; package monica.registry.centre; /** * * @author [email protected] * * 2017-08-29 */ public class RegistryCentre { public void start() throws Exception { Registration service = RegistrationFactory.getRegistryService(); service.register(getUri(), getType()); } public static boolean registryFinished() { return true; }
private UriSpec uri;
polarcoral/monica
monica-registry/src/main/java/monica/registry/centre/RegistryCentre.java
// Path: monica-registry/src/main/java/monica/registry/Registration.java // @SPI(ZookeeperRegistration.NAME) // public interface Registration { // final Logger log = Logger.getLogger(Registration.class); // // public void register(UriSpec uri, RegistryType type) throws Exception; // // public boolean done(); // // } // // Path: monica-registry/src/main/java/monica/registry/base/RegistryType.java // public enum RegistryType { // SERVER, CLIENT // } // // Path: monica-registry/src/main/java/monica/registry/base/UriSpec.java // public class UriSpec { // private String scheme; // private String ip; // private String port; // // public String getScheme() { // return scheme; // } // // public void setScheme(String scheme) { // this.scheme = scheme; // } // // public String getIp() { // return ip; // } // // public void setIp(String ip) { // this.ip = ip; // } // // public String getPort() { // return port; // } // // public void setPort(String port) { // this.port = port; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // if (null == scheme || scheme.equals("")) { // sb.append("monica://"); // } else { // sb.append(scheme); // } // if (null != ip && !ip.equals("")) { // sb.append(ip); // } // sb.append(":"); // if (null != port && !port.equals("")) { // sb.append(port); // } // return sb.toString(); // } // // } // // Path: monica-registry/src/main/java/monica/registry/service/RegistrationFactory.java // public class RegistrationFactory { // // public static Registration getRegistryService() // throws InstantiationException, ClassNotFoundException, IllegalAccessException { // Registration service = (Registration) ExtensionProvider.getDefaultExtension(Registration.class).newInstance(); // // return service; // } // // }
import monica.registry.Registration; import monica.registry.base.RegistryType; import monica.registry.base.UriSpec; import monica.registry.service.RegistrationFactory;
package monica.registry.centre; /** * * @author [email protected] * * 2017-08-29 */ public class RegistryCentre { public void start() throws Exception { Registration service = RegistrationFactory.getRegistryService(); service.register(getUri(), getType()); } public static boolean registryFinished() { return true; } private UriSpec uri;
// Path: monica-registry/src/main/java/monica/registry/Registration.java // @SPI(ZookeeperRegistration.NAME) // public interface Registration { // final Logger log = Logger.getLogger(Registration.class); // // public void register(UriSpec uri, RegistryType type) throws Exception; // // public boolean done(); // // } // // Path: monica-registry/src/main/java/monica/registry/base/RegistryType.java // public enum RegistryType { // SERVER, CLIENT // } // // Path: monica-registry/src/main/java/monica/registry/base/UriSpec.java // public class UriSpec { // private String scheme; // private String ip; // private String port; // // public String getScheme() { // return scheme; // } // // public void setScheme(String scheme) { // this.scheme = scheme; // } // // public String getIp() { // return ip; // } // // public void setIp(String ip) { // this.ip = ip; // } // // public String getPort() { // return port; // } // // public void setPort(String port) { // this.port = port; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // if (null == scheme || scheme.equals("")) { // sb.append("monica://"); // } else { // sb.append(scheme); // } // if (null != ip && !ip.equals("")) { // sb.append(ip); // } // sb.append(":"); // if (null != port && !port.equals("")) { // sb.append(port); // } // return sb.toString(); // } // // } // // Path: monica-registry/src/main/java/monica/registry/service/RegistrationFactory.java // public class RegistrationFactory { // // public static Registration getRegistryService() // throws InstantiationException, ClassNotFoundException, IllegalAccessException { // Registration service = (Registration) ExtensionProvider.getDefaultExtension(Registration.class).newInstance(); // // return service; // } // // } // Path: monica-registry/src/main/java/monica/registry/centre/RegistryCentre.java import monica.registry.Registration; import monica.registry.base.RegistryType; import monica.registry.base.UriSpec; import monica.registry.service.RegistrationFactory; package monica.registry.centre; /** * * @author [email protected] * * 2017-08-29 */ public class RegistryCentre { public void start() throws Exception { Registration service = RegistrationFactory.getRegistryService(); service.register(getUri(), getType()); } public static boolean registryFinished() { return true; } private UriSpec uri;
private RegistryType type;
polarcoral/monica
monica-cluster/src/main/java/monica/cluster/router/parse/UnblockedParser.java
// Path: monica-cluster/src/main/java/monica/cluster/Parser.java // public interface Parser { // public void doParse(Rule rule); // // public boolean isExpected(); // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Operator.java // public enum Operator { // INCLUDE, EXCLUDE // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Rule.java // public class Rule implements Comparable<Rule> { // private Host source; // private Host destination; // private int priority; // // public Host getSource() { // return source; // } // // public void setSource(Host source) { // this.source = source; // } // // public Host getDestination() { // return destination; // } // // public void setDestination(Host destination) { // this.destination = destination; // } // // public int getPriority() { // return priority; // } // // public void setPriority(int priority) { // // this.priority = priority; // } // // public String toString() { // if (null != source && null != destination) { // return source + "=>" + destination; // } else if (null != source && null == destination) { // return source + "=>"; // } else if (null == source && null != destination) { // return "=>" + destination; // } else { // return ""; // } // // } // // public int compareTo(Rule o) { // if (this.priority < o.priority) // return -1; // return 1; // } // // }
import monica.cluster.Parser; import monica.cluster.router.parse.object.Operator; import monica.cluster.router.parse.object.Rule;
package monica.cluster.router.parse; /** * * @author [email protected] * * 2017-08-29 */ public class UnblockedParser implements Parser { private volatile boolean parseResult = false;
// Path: monica-cluster/src/main/java/monica/cluster/Parser.java // public interface Parser { // public void doParse(Rule rule); // // public boolean isExpected(); // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Operator.java // public enum Operator { // INCLUDE, EXCLUDE // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Rule.java // public class Rule implements Comparable<Rule> { // private Host source; // private Host destination; // private int priority; // // public Host getSource() { // return source; // } // // public void setSource(Host source) { // this.source = source; // } // // public Host getDestination() { // return destination; // } // // public void setDestination(Host destination) { // this.destination = destination; // } // // public int getPriority() { // return priority; // } // // public void setPriority(int priority) { // // this.priority = priority; // } // // public String toString() { // if (null != source && null != destination) { // return source + "=>" + destination; // } else if (null != source && null == destination) { // return source + "=>"; // } else if (null == source && null != destination) { // return "=>" + destination; // } else { // return ""; // } // // } // // public int compareTo(Rule o) { // if (this.priority < o.priority) // return -1; // return 1; // } // // } // Path: monica-cluster/src/main/java/monica/cluster/router/parse/UnblockedParser.java import monica.cluster.Parser; import monica.cluster.router.parse.object.Operator; import monica.cluster.router.parse.object.Rule; package monica.cluster.router.parse; /** * * @author [email protected] * * 2017-08-29 */ public class UnblockedParser implements Parser { private volatile boolean parseResult = false;
public void doParse(Rule rule) {
polarcoral/monica
monica-cluster/src/main/java/monica/cluster/router/parse/UnblockedParser.java
// Path: monica-cluster/src/main/java/monica/cluster/Parser.java // public interface Parser { // public void doParse(Rule rule); // // public boolean isExpected(); // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Operator.java // public enum Operator { // INCLUDE, EXCLUDE // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Rule.java // public class Rule implements Comparable<Rule> { // private Host source; // private Host destination; // private int priority; // // public Host getSource() { // return source; // } // // public void setSource(Host source) { // this.source = source; // } // // public Host getDestination() { // return destination; // } // // public void setDestination(Host destination) { // this.destination = destination; // } // // public int getPriority() { // return priority; // } // // public void setPriority(int priority) { // // this.priority = priority; // } // // public String toString() { // if (null != source && null != destination) { // return source + "=>" + destination; // } else if (null != source && null == destination) { // return source + "=>"; // } else if (null == source && null != destination) { // return "=>" + destination; // } else { // return ""; // } // // } // // public int compareTo(Rule o) { // if (this.priority < o.priority) // return -1; // return 1; // } // // }
import monica.cluster.Parser; import monica.cluster.router.parse.object.Operator; import monica.cluster.router.parse.object.Rule;
package monica.cluster.router.parse; /** * * @author [email protected] * * 2017-08-29 */ public class UnblockedParser implements Parser { private volatile boolean parseResult = false; public void doParse(Rule rule) {
// Path: monica-cluster/src/main/java/monica/cluster/Parser.java // public interface Parser { // public void doParse(Rule rule); // // public boolean isExpected(); // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Operator.java // public enum Operator { // INCLUDE, EXCLUDE // } // // Path: monica-cluster/src/main/java/monica/cluster/router/parse/object/Rule.java // public class Rule implements Comparable<Rule> { // private Host source; // private Host destination; // private int priority; // // public Host getSource() { // return source; // } // // public void setSource(Host source) { // this.source = source; // } // // public Host getDestination() { // return destination; // } // // public void setDestination(Host destination) { // this.destination = destination; // } // // public int getPriority() { // return priority; // } // // public void setPriority(int priority) { // // this.priority = priority; // } // // public String toString() { // if (null != source && null != destination) { // return source + "=>" + destination; // } else if (null != source && null == destination) { // return source + "=>"; // } else if (null == source && null != destination) { // return "=>" + destination; // } else { // return ""; // } // // } // // public int compareTo(Rule o) { // if (this.priority < o.priority) // return -1; // return 1; // } // // } // Path: monica-cluster/src/main/java/monica/cluster/router/parse/UnblockedParser.java import monica.cluster.Parser; import monica.cluster.router.parse.object.Operator; import monica.cluster.router.parse.object.Rule; package monica.cluster.router.parse; /** * * @author [email protected] * * 2017-08-29 */ public class UnblockedParser implements Parser { private volatile boolean parseResult = false; public void doParse(Rule rule) {
if (null == rule.getDestination() && rule.getSource().getOps().equals(Operator.EXCLUDE)) {
polarcoral/monica
monica-configuration/src/main/java/monica/configuration/ConfigServiceBuilder.java
// Path: monica-configuration/src/main/java/monica/configuration/api/Config.java // public interface Config { // public void load(File file) throws Exception; // // public void reLoad(File file) throws Exception; // }
import java.io.File; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import monica.configuration.api.Config;
package monica.configuration; /** * * @author [email protected] * * 2017-08-29 */ public class ConfigServiceBuilder { public static void build() throws NotFoundException, Exception { File newfile = new File(""); if (null != newfile && newfile.exists()) {
// Path: monica-configuration/src/main/java/monica/configuration/api/Config.java // public interface Config { // public void load(File file) throws Exception; // // public void reLoad(File file) throws Exception; // } // Path: monica-configuration/src/main/java/monica/configuration/ConfigServiceBuilder.java import java.io.File; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import monica.configuration.api.Config; package monica.configuration; /** * * @author [email protected] * * 2017-08-29 */ public class ConfigServiceBuilder { public static void build() throws NotFoundException, Exception { File newfile = new File(""); if (null != newfile && newfile.exists()) {
String clazzname = newfile.getName().substring(newfile.getName().indexOf(".")) + "Config";
polarcoral/monica
monica-registry/src/main/java/monica/registry/Registration.java
// Path: monica-registry/src/main/java/monica/registry/base/RegistryType.java // public enum RegistryType { // SERVER, CLIENT // } // // Path: monica-registry/src/main/java/monica/registry/base/UriSpec.java // public class UriSpec { // private String scheme; // private String ip; // private String port; // // public String getScheme() { // return scheme; // } // // public void setScheme(String scheme) { // this.scheme = scheme; // } // // public String getIp() { // return ip; // } // // public void setIp(String ip) { // this.ip = ip; // } // // public String getPort() { // return port; // } // // public void setPort(String port) { // this.port = port; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // if (null == scheme || scheme.equals("")) { // sb.append("monica://"); // } else { // sb.append(scheme); // } // if (null != ip && !ip.equals("")) { // sb.append(ip); // } // sb.append(":"); // if (null != port && !port.equals("")) { // sb.append(port); // } // return sb.toString(); // } // // } // // Path: monica-registry/src/main/java/monica/registry/service/ZookeeperRegistration.java // public class ZookeeperRegistration implements Registration { // public final static String NAME = "zookeeper"; // public final String ZK_NAMESPACE = "monica"; // // public void register(UriSpec uri, RegistryType type) throws Exception { // CuratorFramework client = (CuratorFramework) RegistryContext.clientCache.get("curatorClient"); // try { // CuratorWatcher watcher = new CuratorWatcher() { // public void process(WatchedEvent event) { // handleChildrenChange("", event.getPath()); // } // }; // String s = URLEncoder.encode(uri.toString(), "UTF-8"); // if (null == client.checkExists().forPath("/" + type.toString())) { // client.create().forPath("/" + type.toString()); // } // client.getChildren().usingWatcher(watcher).forPath("/SERVER"); // if (null == client.checkExists().forPath("/SERVER/" + s)) { // client.create().withMode(CreateMode.EPHEMERAL).forPath("/SERVER/" + s); // } // // /* // * List<String> batch = batchCreate(); for (String ss : batch) { if // * (null == client.checkExists().forPath("/SERVER/" + ss)) { // * client.create().forPath("/SERVER/" + ss); } } // */ // // client.getChildren().usingWatcher(new CuratorWatcher() { // // public void process(WatchedEvent event) throws Exception { // // handleRoutersChildrenChange("", event.getType()); // } // // }).forPath("/SERVER"); // // // Assert.assertEquals("", "/SERVER"); // } finally { // // CloseableUtils.closeQuietly(client); // // } // } // // private void handleChildrenChange(String name, Object value) { // log.info("/socket/SERVER NodeChildren changed !"); // // ServiceContext.hashmap.put(name, value); // } // // private void handleRoutersChildrenChange(String name, Object value) { // // } // // public boolean done() { // return true; // } // // public List<String> batchCreate() { // List<String> batchUri = new ArrayList(); // for (int i = 0; i < 2; i++) { // String b = "monica://192.168.1.10"; // String e = ":8023"; // try { // batchUri.add(URLEncoder.encode(b + i + e, "UTF-8")); // System.out.println("batchString[" + i + "] ---- " + (b + i + e)); // } catch (UnsupportedEncodingException e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // } // } // return batchUri; // } // }
import org.apache.log4j.Logger; import monica.framework.SPI; import monica.registry.base.RegistryType; import monica.registry.base.UriSpec; import monica.registry.service.ZookeeperRegistration;
package monica.registry; /** * * plugin point for user to extend the registry-discovery way using the * different tech framework. * * @author [email protected] * * 2017-08-29 */ @SPI(ZookeeperRegistration.NAME) public interface Registration { final Logger log = Logger.getLogger(Registration.class);
// Path: monica-registry/src/main/java/monica/registry/base/RegistryType.java // public enum RegistryType { // SERVER, CLIENT // } // // Path: monica-registry/src/main/java/monica/registry/base/UriSpec.java // public class UriSpec { // private String scheme; // private String ip; // private String port; // // public String getScheme() { // return scheme; // } // // public void setScheme(String scheme) { // this.scheme = scheme; // } // // public String getIp() { // return ip; // } // // public void setIp(String ip) { // this.ip = ip; // } // // public String getPort() { // return port; // } // // public void setPort(String port) { // this.port = port; // } // // public String toString() { // StringBuilder sb = new StringBuilder(); // if (null == scheme || scheme.equals("")) { // sb.append("monica://"); // } else { // sb.append(scheme); // } // if (null != ip && !ip.equals("")) { // sb.append(ip); // } // sb.append(":"); // if (null != port && !port.equals("")) { // sb.append(port); // } // return sb.toString(); // } // // } // // Path: monica-registry/src/main/java/monica/registry/service/ZookeeperRegistration.java // public class ZookeeperRegistration implements Registration { // public final static String NAME = "zookeeper"; // public final String ZK_NAMESPACE = "monica"; // // public void register(UriSpec uri, RegistryType type) throws Exception { // CuratorFramework client = (CuratorFramework) RegistryContext.clientCache.get("curatorClient"); // try { // CuratorWatcher watcher = new CuratorWatcher() { // public void process(WatchedEvent event) { // handleChildrenChange("", event.getPath()); // } // }; // String s = URLEncoder.encode(uri.toString(), "UTF-8"); // if (null == client.checkExists().forPath("/" + type.toString())) { // client.create().forPath("/" + type.toString()); // } // client.getChildren().usingWatcher(watcher).forPath("/SERVER"); // if (null == client.checkExists().forPath("/SERVER/" + s)) { // client.create().withMode(CreateMode.EPHEMERAL).forPath("/SERVER/" + s); // } // // /* // * List<String> batch = batchCreate(); for (String ss : batch) { if // * (null == client.checkExists().forPath("/SERVER/" + ss)) { // * client.create().forPath("/SERVER/" + ss); } } // */ // // client.getChildren().usingWatcher(new CuratorWatcher() { // // public void process(WatchedEvent event) throws Exception { // // handleRoutersChildrenChange("", event.getType()); // } // // }).forPath("/SERVER"); // // // Assert.assertEquals("", "/SERVER"); // } finally { // // CloseableUtils.closeQuietly(client); // // } // } // // private void handleChildrenChange(String name, Object value) { // log.info("/socket/SERVER NodeChildren changed !"); // // ServiceContext.hashmap.put(name, value); // } // // private void handleRoutersChildrenChange(String name, Object value) { // // } // // public boolean done() { // return true; // } // // public List<String> batchCreate() { // List<String> batchUri = new ArrayList(); // for (int i = 0; i < 2; i++) { // String b = "monica://192.168.1.10"; // String e = ":8023"; // try { // batchUri.add(URLEncoder.encode(b + i + e, "UTF-8")); // System.out.println("batchString[" + i + "] ---- " + (b + i + e)); // } catch (UnsupportedEncodingException e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // } // } // return batchUri; // } // } // Path: monica-registry/src/main/java/monica/registry/Registration.java import org.apache.log4j.Logger; import monica.framework.SPI; import monica.registry.base.RegistryType; import monica.registry.base.UriSpec; import monica.registry.service.ZookeeperRegistration; package monica.registry; /** * * plugin point for user to extend the registry-discovery way using the * different tech framework. * * @author [email protected] * * 2017-08-29 */ @SPI(ZookeeperRegistration.NAME) public interface Registration { final Logger log = Logger.getLogger(Registration.class);
public void register(UriSpec uri, RegistryType type) throws Exception;