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
kpavlov/fixio
core/src/test/java/fixio/fixprotocol/fields/FieldFactoryTest.java
// Path: core/src/main/java/fixio/fixprotocol/DataType.java // public enum DataType { // INT, // CHAR, // MULTIPLECHARVALUE, // STRING, // FLOAT, // BOOLEAN, // AMT, // QTY, // PRICE, // PRICEOFFSET, // SEQNUM, // LENGTH, // NUMINGROUP, // MONTHYEAR, // UTCTIMESTAMP, // UTCDATEONLY, // UTCTIMEONLY, // PERCENTAGE, // CURRENCY, // COUNTRY, // LANGUAGE, // EXCHANGE, // LOCALMKTDATE, // MULTIPLESTRINGVALUE, // TZTIMEONLY, // TZTIMESTAMP, // XMLDATA, // DATA // } // // Path: core/src/main/java/fixio/netty/pipeline/FixClock.java // public static FixClock systemUTC() { // return INSTANCE; // }
import fixio.fixprotocol.DataType; import fixio.fixprotocol.FieldType; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.junit.Test; import org.junit.runner.RunWith; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZonedDateTime; import java.util.Random; import java.util.concurrent.TimeUnit; import static fixio.netty.pipeline.FixClock.systemUTC; import static java.nio.charset.StandardCharsets.US_ASCII; import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; import static org.apache.commons.lang3.RandomStringUtils.randomAscii; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue;
} @Test(expected = IllegalArgumentException.class) @Parameters({"XXX", "", "-"}) public void testFailValueOfIncorrectBoolean(String value) { FieldFactory.valueOf(FieldType.PossDupFlag.tag(), value.getBytes(US_ASCII)); } @Test public void testValueOfUtcTimestampWithMillis() { String value = "19980604-08:03:31.537"; UTCTimestampField field = FieldFactory.valueOf(FieldType.OrigTime.tag(), value.getBytes(US_ASCII)); assertEquals("tagnum", FieldType.OrigTime.tag(), field.getTagNum()); assertEquals("value", ZonedDateTime.of(LocalDate.of(1998, 6, 4), LocalTime.of(8, 3, 31, (int) TimeUnit.MILLISECONDS.toNanos(537)), systemUTC().getZone()).toInstant().toEpochMilli(), field.getValue().toInstant().toEpochMilli()); } @Test public void testValueOfUtcTimestampNoMillis() { String value = "19980604-08:03:31"; UTCTimestampField field = FieldFactory.valueOf(FieldType.OrigTime.tag(), value.getBytes(US_ASCII)); assertEquals("tagnum", FieldType.OrigTime.tag(), field.getTagNum()); assertEquals("value", ZonedDateTime.of(LocalDate.of(1998, 6, 4), LocalTime.of(8, 3, 31), systemUTC().getZone()).toInstant().toEpochMilli(), field.getValue().toInstant().toEpochMilli()); } @Test @Parameters({"200303", "20030320", "200303w2"}) public void testFromStringValueMonthYear(final String value) { final int tag = FieldType.MaturityMonthYear.tag();
// Path: core/src/main/java/fixio/fixprotocol/DataType.java // public enum DataType { // INT, // CHAR, // MULTIPLECHARVALUE, // STRING, // FLOAT, // BOOLEAN, // AMT, // QTY, // PRICE, // PRICEOFFSET, // SEQNUM, // LENGTH, // NUMINGROUP, // MONTHYEAR, // UTCTIMESTAMP, // UTCDATEONLY, // UTCTIMEONLY, // PERCENTAGE, // CURRENCY, // COUNTRY, // LANGUAGE, // EXCHANGE, // LOCALMKTDATE, // MULTIPLESTRINGVALUE, // TZTIMEONLY, // TZTIMESTAMP, // XMLDATA, // DATA // } // // Path: core/src/main/java/fixio/netty/pipeline/FixClock.java // public static FixClock systemUTC() { // return INSTANCE; // } // Path: core/src/test/java/fixio/fixprotocol/fields/FieldFactoryTest.java import fixio.fixprotocol.DataType; import fixio.fixprotocol.FieldType; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.junit.Test; import org.junit.runner.RunWith; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZonedDateTime; import java.util.Random; import java.util.concurrent.TimeUnit; import static fixio.netty.pipeline.FixClock.systemUTC; import static java.nio.charset.StandardCharsets.US_ASCII; import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; import static org.apache.commons.lang3.RandomStringUtils.randomAscii; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; } @Test(expected = IllegalArgumentException.class) @Parameters({"XXX", "", "-"}) public void testFailValueOfIncorrectBoolean(String value) { FieldFactory.valueOf(FieldType.PossDupFlag.tag(), value.getBytes(US_ASCII)); } @Test public void testValueOfUtcTimestampWithMillis() { String value = "19980604-08:03:31.537"; UTCTimestampField field = FieldFactory.valueOf(FieldType.OrigTime.tag(), value.getBytes(US_ASCII)); assertEquals("tagnum", FieldType.OrigTime.tag(), field.getTagNum()); assertEquals("value", ZonedDateTime.of(LocalDate.of(1998, 6, 4), LocalTime.of(8, 3, 31, (int) TimeUnit.MILLISECONDS.toNanos(537)), systemUTC().getZone()).toInstant().toEpochMilli(), field.getValue().toInstant().toEpochMilli()); } @Test public void testValueOfUtcTimestampNoMillis() { String value = "19980604-08:03:31"; UTCTimestampField field = FieldFactory.valueOf(FieldType.OrigTime.tag(), value.getBytes(US_ASCII)); assertEquals("tagnum", FieldType.OrigTime.tag(), field.getTagNum()); assertEquals("value", ZonedDateTime.of(LocalDate.of(1998, 6, 4), LocalTime.of(8, 3, 31), systemUTC().getZone()).toInstant().toEpochMilli(), field.getValue().toInstant().toEpochMilli()); } @Test @Parameters({"200303", "20030320", "200303w2"}) public void testFromStringValueMonthYear(final String value) { final int tag = FieldType.MaturityMonthYear.tag();
StringField field = FieldFactory.fromStringValue(DataType.MONTHYEAR, tag, value);
kpavlov/fixio
examples/src/main/java/fixio/examples/quickfix/QuickFixStreamingApp.java
// Path: examples/src/main/java/fixio/examples/common/AbstractQuoteStreamingWorker.java // public abstract class AbstractQuoteStreamingWorker implements Runnable { // // private static final int BUFFER_LENGTH = 32; // // private final BlockingQueue<Quote> quoteQueue; // // public AbstractQuoteStreamingWorker(BlockingQueue<Quote> quoteQueue) { // this.quoteQueue = quoteQueue; // } // // protected abstract void sendQuotes(List<Quote> buffer); // // @Override // public void run() { // final List<Quote> buffer = new ArrayList<>(BUFFER_LENGTH); // //noinspection InfiniteLoopStatement // while (true) { // quoteQueue.drainTo(buffer, BUFFER_LENGTH); // sendQuotes(buffer); // buffer.clear(); // } // } // // } // // Path: examples/src/main/java/fixio/examples/common/Quote.java // public class Quote { // // private final double bid; // private final double offer; // // public Quote(double bid, double offer) { // this.bid = bid; // this.offer = offer; // } // // public double getBid() { // return bid; // } // // public double getOffer() { // return offer; // } // }
import fixio.examples.common.AbstractQuoteStreamingWorker; import fixio.examples.common.Quote; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import quickfix.Application; import quickfix.DoubleField; import quickfix.FieldNotFound; import quickfix.Message; import quickfix.Session; import quickfix.SessionID; import quickfix.SessionNotFound; import quickfix.field.MktBidPx; import quickfix.field.MktOfferPx; import quickfix.field.MsgType; import quickfix.field.QuoteReqID; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors;
/* * Copyright 2014 The FIX.io Project * * The FIX.io 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 fixio.examples.quickfix; public class QuickFixStreamingApp implements Application { private static final Logger LOGGER = LoggerFactory.getLogger(QuickFixStreamingApp.class); private static final MsgType QUOTE_MSG_TYPE = new MsgType(MsgType.QUOTE); private final Map<String, SessionID> subscriptions = new ConcurrentHashMap<>();
// Path: examples/src/main/java/fixio/examples/common/AbstractQuoteStreamingWorker.java // public abstract class AbstractQuoteStreamingWorker implements Runnable { // // private static final int BUFFER_LENGTH = 32; // // private final BlockingQueue<Quote> quoteQueue; // // public AbstractQuoteStreamingWorker(BlockingQueue<Quote> quoteQueue) { // this.quoteQueue = quoteQueue; // } // // protected abstract void sendQuotes(List<Quote> buffer); // // @Override // public void run() { // final List<Quote> buffer = new ArrayList<>(BUFFER_LENGTH); // //noinspection InfiniteLoopStatement // while (true) { // quoteQueue.drainTo(buffer, BUFFER_LENGTH); // sendQuotes(buffer); // buffer.clear(); // } // } // // } // // Path: examples/src/main/java/fixio/examples/common/Quote.java // public class Quote { // // private final double bid; // private final double offer; // // public Quote(double bid, double offer) { // this.bid = bid; // this.offer = offer; // } // // public double getBid() { // return bid; // } // // public double getOffer() { // return offer; // } // } // Path: examples/src/main/java/fixio/examples/quickfix/QuickFixStreamingApp.java import fixio.examples.common.AbstractQuoteStreamingWorker; import fixio.examples.common.Quote; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import quickfix.Application; import quickfix.DoubleField; import quickfix.FieldNotFound; import quickfix.Message; import quickfix.Session; import quickfix.SessionID; import quickfix.SessionNotFound; import quickfix.field.MktBidPx; import quickfix.field.MktOfferPx; import quickfix.field.MsgType; import quickfix.field.QuoteReqID; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; /* * Copyright 2014 The FIX.io Project * * The FIX.io 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 fixio.examples.quickfix; public class QuickFixStreamingApp implements Application { private static final Logger LOGGER = LoggerFactory.getLogger(QuickFixStreamingApp.class); private static final MsgType QUOTE_MSG_TYPE = new MsgType(MsgType.QUOTE); private final Map<String, SessionID> subscriptions = new ConcurrentHashMap<>();
public QuickFixStreamingApp(BlockingQueue<Quote> quoteQueue) {
kpavlov/fixio
examples/src/main/java/fixio/examples/quickfix/QuickFixStreamingApp.java
// Path: examples/src/main/java/fixio/examples/common/AbstractQuoteStreamingWorker.java // public abstract class AbstractQuoteStreamingWorker implements Runnable { // // private static final int BUFFER_LENGTH = 32; // // private final BlockingQueue<Quote> quoteQueue; // // public AbstractQuoteStreamingWorker(BlockingQueue<Quote> quoteQueue) { // this.quoteQueue = quoteQueue; // } // // protected abstract void sendQuotes(List<Quote> buffer); // // @Override // public void run() { // final List<Quote> buffer = new ArrayList<>(BUFFER_LENGTH); // //noinspection InfiniteLoopStatement // while (true) { // quoteQueue.drainTo(buffer, BUFFER_LENGTH); // sendQuotes(buffer); // buffer.clear(); // } // } // // } // // Path: examples/src/main/java/fixio/examples/common/Quote.java // public class Quote { // // private final double bid; // private final double offer; // // public Quote(double bid, double offer) { // this.bid = bid; // this.offer = offer; // } // // public double getBid() { // return bid; // } // // public double getOffer() { // return offer; // } // }
import fixio.examples.common.AbstractQuoteStreamingWorker; import fixio.examples.common.Quote; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import quickfix.Application; import quickfix.DoubleField; import quickfix.FieldNotFound; import quickfix.Message; import quickfix.Session; import quickfix.SessionID; import quickfix.SessionNotFound; import quickfix.field.MktBidPx; import quickfix.field.MktOfferPx; import quickfix.field.MsgType; import quickfix.field.QuoteReqID; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors;
@Override public void fromApp(Message message, SessionID sessionID) { try { String msgType = message.getHeader().getString(35); switch (msgType) { case MsgType.QUOTE_REQUEST: String reqId = message.getString(QuoteReqID.FIELD); subscriptions.put(reqId, sessionID); LOGGER.debug("Subscribed with QuoteReqID={}", reqId); break; case MsgType.QUOTE_CANCEL: reqId = message.getString(QuoteReqID.FIELD); subscriptions.remove(reqId); LOGGER.debug("Unsubscribed with QuoteReqID={}", reqId); break; } } catch (FieldNotFound fieldNotFound) { fieldNotFound.printStackTrace(); } } private void stopStreaming(SessionID sessionID) { ArrayList<String> requestsToCancel = new ArrayList<>(subscriptions.size()); requestsToCancel.addAll(subscriptions.entrySet().stream().filter(entry -> entry.getValue() == sessionID).map(Map.Entry::getKey).collect(Collectors.toList())); requestsToCancel.forEach(subscriptions::remove); LOGGER.info("Streaming Stopped for {}", sessionID); }
// Path: examples/src/main/java/fixio/examples/common/AbstractQuoteStreamingWorker.java // public abstract class AbstractQuoteStreamingWorker implements Runnable { // // private static final int BUFFER_LENGTH = 32; // // private final BlockingQueue<Quote> quoteQueue; // // public AbstractQuoteStreamingWorker(BlockingQueue<Quote> quoteQueue) { // this.quoteQueue = quoteQueue; // } // // protected abstract void sendQuotes(List<Quote> buffer); // // @Override // public void run() { // final List<Quote> buffer = new ArrayList<>(BUFFER_LENGTH); // //noinspection InfiniteLoopStatement // while (true) { // quoteQueue.drainTo(buffer, BUFFER_LENGTH); // sendQuotes(buffer); // buffer.clear(); // } // } // // } // // Path: examples/src/main/java/fixio/examples/common/Quote.java // public class Quote { // // private final double bid; // private final double offer; // // public Quote(double bid, double offer) { // this.bid = bid; // this.offer = offer; // } // // public double getBid() { // return bid; // } // // public double getOffer() { // return offer; // } // } // Path: examples/src/main/java/fixio/examples/quickfix/QuickFixStreamingApp.java import fixio.examples.common.AbstractQuoteStreamingWorker; import fixio.examples.common.Quote; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import quickfix.Application; import quickfix.DoubleField; import quickfix.FieldNotFound; import quickfix.Message; import quickfix.Session; import quickfix.SessionID; import quickfix.SessionNotFound; import quickfix.field.MktBidPx; import quickfix.field.MktOfferPx; import quickfix.field.MsgType; import quickfix.field.QuoteReqID; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; @Override public void fromApp(Message message, SessionID sessionID) { try { String msgType = message.getHeader().getString(35); switch (msgType) { case MsgType.QUOTE_REQUEST: String reqId = message.getString(QuoteReqID.FIELD); subscriptions.put(reqId, sessionID); LOGGER.debug("Subscribed with QuoteReqID={}", reqId); break; case MsgType.QUOTE_CANCEL: reqId = message.getString(QuoteReqID.FIELD); subscriptions.remove(reqId); LOGGER.debug("Unsubscribed with QuoteReqID={}", reqId); break; } } catch (FieldNotFound fieldNotFound) { fieldNotFound.printStackTrace(); } } private void stopStreaming(SessionID sessionID) { ArrayList<String> requestsToCancel = new ArrayList<>(subscriptions.size()); requestsToCancel.addAll(subscriptions.entrySet().stream().filter(entry -> entry.getValue() == sessionID).map(Map.Entry::getKey).collect(Collectors.toList())); requestsToCancel.forEach(subscriptions::remove); LOGGER.info("Streaming Stopped for {}", sessionID); }
private class StreamingWorker extends AbstractQuoteStreamingWorker {
kpavlov/fixio
core/src/main/java/fixio/fixprotocol/FieldListBuilder.java
// Path: core/src/main/java/fixio/fixprotocol/fields/FixedPointNumber.java // public class FixedPointNumber extends Number { // // /** // * Negative or positive scaled value decimal value: <code>scaledValue := value * (10^scale)</code> // */ // private final long scaledValue; // // /** // * If zero or positive, the scale is the number of digits to the right of the decimal point. // */ // private final byte scale; // // protected FixedPointNumber(byte[] bytes, int offset, int length) { // int index = offset; // long scaled = 0; // int sign = 1; // switch (bytes[offset]) { // case '-': // sign = -1; // index++; // break; // case '+': // sign = +1; // index++; // break; // default: // } // boolean hasScale = false; // byte scale = 0; // for (int i = index; i < offset + length; i++) { // if (bytes[index] == '.') { // hasScale = true; // } else { // int digit = (bytes[index] - '0'); // scaled = scaled * 10 + digit; // if (hasScale) { // scale++; // } // } // index++; // } // // scaledValue = scaled * sign; // this.scale = scale; // } // // public FixedPointNumber(long scaledValue) { // this.scaledValue = scaledValue; // this.scale = 0; // } // // public FixedPointNumber(long scaledValue, byte scale) { // assert (scale >= 0) : "Scale should not be negative"; // this.scaledValue = scaledValue; // this.scale = scale; // } // // public FixedPointNumber(double value, int precision) { // this.scale = (byte) precision; // long factor = (long) Math.pow(10.0, scale); // scaledValue = Math.round(value * factor); // } // // public FixedPointNumber(String s) { // this(s.getBytes(), 0, s.length()); // } // // @Override // public int intValue() { // return (int) (longValue()); // } // // @Override // public long longValue() { // if (scale == 0) { // return scaledValue; // } // return scaledValue / ((long) Math.pow(10.0, scale)); // } // // @Override // @Deprecated // public float floatValue() { // return (float) doubleValue(); // } // // @Override // public double doubleValue() { // double factor = Math.pow(10.0, scale); // return scaledValue / factor; // } // // public long getScaledValue() { // return scaledValue; // } // // public byte getScale() { // return scale; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || !(o instanceof FixedPointNumber)) // return false; // final FixedPointNumber that = (FixedPointNumber) o; // return scale == that.scale && scaledValue == that.scaledValue; // } // // @Override // public int hashCode() { // int result = (int) (scaledValue ^ (scaledValue >>> 32)); // result = 31 * result + (int) scale; // return result; // } // // private String insertPointBefore(int idx) { // StringBuilder sb = new StringBuilder("0."); // for (int i = idx; i < 0; i++) { // sb.append("0"); // } // return sb.toString(); // } // // @Override // public String toString() { // if (scale == 0 || scaledValue == 0) { // return String.valueOf(scaledValue); // } // int factor = (int) Math.pow(10.0, scale); // long beforePoint = scaledValue / factor; // // long afterPoint = Math.abs(scaledValue - beforePoint * factor); // if (beforePoint == 0 && scaledValue < 0) { // return "-0." + afterPoint; // } else { // String scaledStr = String.valueOf(scaledValue); // int idx = scaledStr.length() - scale; // String insertPoint; // if (idx <= 0) { // insertPoint = insertPointBefore(idx); // idx = 0; // } else { // insertPoint = "."; // } // return new StringBuilder(scaledStr) // .insert(idx, insertPoint) // .toString(); // } // } // }
import fixio.fixprotocol.fields.FixedPointNumber;
/* * Copyright 2014 The FIX.io Project * * The FIX.io 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 fixio.fixprotocol; /** * Represent a ordered list of fields. * <p> * Provides methods to add new fields. * </p> */ interface FieldListBuilder<T> { T add(FieldType field, String value); T add(FieldType field, char value); T add(int tagNum, String value); T add(DataType type, int tagNum, String value); T add(FieldType field, int value); T add(int tagNum, int value); T add(DataType type, int tagNum, int value); T add(FieldType field, long value); T add(int tagNum, long value); T add(DataType type, int tagNum, long value);
// Path: core/src/main/java/fixio/fixprotocol/fields/FixedPointNumber.java // public class FixedPointNumber extends Number { // // /** // * Negative or positive scaled value decimal value: <code>scaledValue := value * (10^scale)</code> // */ // private final long scaledValue; // // /** // * If zero or positive, the scale is the number of digits to the right of the decimal point. // */ // private final byte scale; // // protected FixedPointNumber(byte[] bytes, int offset, int length) { // int index = offset; // long scaled = 0; // int sign = 1; // switch (bytes[offset]) { // case '-': // sign = -1; // index++; // break; // case '+': // sign = +1; // index++; // break; // default: // } // boolean hasScale = false; // byte scale = 0; // for (int i = index; i < offset + length; i++) { // if (bytes[index] == '.') { // hasScale = true; // } else { // int digit = (bytes[index] - '0'); // scaled = scaled * 10 + digit; // if (hasScale) { // scale++; // } // } // index++; // } // // scaledValue = scaled * sign; // this.scale = scale; // } // // public FixedPointNumber(long scaledValue) { // this.scaledValue = scaledValue; // this.scale = 0; // } // // public FixedPointNumber(long scaledValue, byte scale) { // assert (scale >= 0) : "Scale should not be negative"; // this.scaledValue = scaledValue; // this.scale = scale; // } // // public FixedPointNumber(double value, int precision) { // this.scale = (byte) precision; // long factor = (long) Math.pow(10.0, scale); // scaledValue = Math.round(value * factor); // } // // public FixedPointNumber(String s) { // this(s.getBytes(), 0, s.length()); // } // // @Override // public int intValue() { // return (int) (longValue()); // } // // @Override // public long longValue() { // if (scale == 0) { // return scaledValue; // } // return scaledValue / ((long) Math.pow(10.0, scale)); // } // // @Override // @Deprecated // public float floatValue() { // return (float) doubleValue(); // } // // @Override // public double doubleValue() { // double factor = Math.pow(10.0, scale); // return scaledValue / factor; // } // // public long getScaledValue() { // return scaledValue; // } // // public byte getScale() { // return scale; // } // // @Override // public boolean equals(Object o) { // if (this == o) // return true; // if (o == null || !(o instanceof FixedPointNumber)) // return false; // final FixedPointNumber that = (FixedPointNumber) o; // return scale == that.scale && scaledValue == that.scaledValue; // } // // @Override // public int hashCode() { // int result = (int) (scaledValue ^ (scaledValue >>> 32)); // result = 31 * result + (int) scale; // return result; // } // // private String insertPointBefore(int idx) { // StringBuilder sb = new StringBuilder("0."); // for (int i = idx; i < 0; i++) { // sb.append("0"); // } // return sb.toString(); // } // // @Override // public String toString() { // if (scale == 0 || scaledValue == 0) { // return String.valueOf(scaledValue); // } // int factor = (int) Math.pow(10.0, scale); // long beforePoint = scaledValue / factor; // // long afterPoint = Math.abs(scaledValue - beforePoint * factor); // if (beforePoint == 0 && scaledValue < 0) { // return "-0." + afterPoint; // } else { // String scaledStr = String.valueOf(scaledValue); // int idx = scaledStr.length() - scale; // String insertPoint; // if (idx <= 0) { // insertPoint = insertPointBefore(idx); // idx = 0; // } else { // insertPoint = "."; // } // return new StringBuilder(scaledStr) // .insert(idx, insertPoint) // .toString(); // } // } // } // Path: core/src/main/java/fixio/fixprotocol/FieldListBuilder.java import fixio.fixprotocol.fields.FixedPointNumber; /* * Copyright 2014 The FIX.io Project * * The FIX.io 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 fixio.fixprotocol; /** * Represent a ordered list of fields. * <p> * Provides methods to add new fields. * </p> */ interface FieldListBuilder<T> { T add(FieldType field, String value); T add(FieldType field, char value); T add(int tagNum, String value); T add(DataType type, int tagNum, String value); T add(FieldType field, int value); T add(int tagNum, int value); T add(DataType type, int tagNum, int value); T add(FieldType field, long value); T add(int tagNum, long value); T add(DataType type, int tagNum, long value);
T add(FieldType field, FixedPointNumber value);
kpavlov/fixio
core/src/main/java/fixio/handlers/CompositeFixApplicationAdapter.java
// Path: core/src/main/java/fixio/fixprotocol/FixMessage.java // public interface FixMessage { // // String FIX_4_0 = "FIX.4.0"; // String FIX_4_1 = "FIX.4.1"; // String FIX_4_2 = "FIX.4.2"; // String FIX_4_3 = "FIX.4.3"; // String FIX_4_4 = "FIX.4.4"; // String FIX_5_0 = "FIXT.1.1"; // // FixMessageHeader getHeader(); // // List<FixMessageFragment> getBody(); // // Integer getInt(int tagNum); // // Integer getInt(FieldType field); // // String getString(int tagNum); // // @SuppressWarnings("unchecked") // <T> T getValue(int tagNum); // // String getString(FieldType field); // // <T> T getValue(FieldType field); // // Character getChar(int tagNum); // // Character getChar(FieldType fieldType); // // String getMessageType(); // // default FixMessageFragment getFirst(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // default List<FixMessageFragment> getAll(int tagNum) { // final List<FixMessageFragment> body = getBody(); // List<FixMessageFragment> result = new ArrayList<>(8); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // result.add(item); // } // } // return result; // } // // default FixMessageFragment getLast(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = body.size() - 1; i >= 0; i--) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // } // // Path: core/src/main/java/fixio/fixprotocol/FixMessageBuilder.java // public interface FixMessageBuilder extends FieldListBuilder<FixMessageBuilder> { // FixMessageHeader getHeader(); // // void copyHeader(FixMessageHeader header); // // List<? extends FixMessageFragment> getBody(); // // void copyBody(List<? extends FixMessageFragment> body); // } // // Path: core/src/main/java/fixio/validator/BusinessRejectException.java // public class BusinessRejectException extends Exception { // // /** // * MsgSeqNum of rejected message // */ // private final int refSeqNum; // // /** // * The MsgType of the FIX message being referenced. // */ // private final String refMsgType; // // /** // * The value of the business-level "ID" field on the message being referenced. // * Required unless the corresponding ID field (see list above) was not specified. // */ // private final int businessRejectReason; // // /** // * Where possible, message to explain reason for rejection. // */ // private final String text; // // public BusinessRejectException(int refSeqNum, String refMsgType, int businessRejectReason, String text) { // super(text); // this.refSeqNum = refSeqNum; // this.refMsgType = refMsgType; // this.businessRejectReason = businessRejectReason; // this.text = text; // } // // public int getRefSeqNum() { // return refSeqNum; // } // // public String getRefMsgType() { // return refMsgType; // } // // public int getBusinessRejectReason() { // return businessRejectReason; // } // // public String getText() { // return text; // } // } // // Path: core/src/main/java/fixio/validator/FixMessageValidator.java // public interface FixMessageValidator { // // void validate(ChannelHandlerContext ctx, FixMessage msg); // }
import fixio.fixprotocol.FixMessage; import fixio.fixprotocol.FixMessageBuilder; import fixio.validator.BusinessRejectException; import fixio.validator.FixMessageValidator; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List;
/* * Copyright 2014 The FIX.io Project * * The FIX.io 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 fixio.handlers; @ChannelHandler.Sharable public class CompositeFixApplicationAdapter extends FixApplicationAdapter { private static final Logger LOGGER = LoggerFactory.getLogger(CompositeFixApplicationAdapter.class); private final List<FixMessageHandler> handlers;
// Path: core/src/main/java/fixio/fixprotocol/FixMessage.java // public interface FixMessage { // // String FIX_4_0 = "FIX.4.0"; // String FIX_4_1 = "FIX.4.1"; // String FIX_4_2 = "FIX.4.2"; // String FIX_4_3 = "FIX.4.3"; // String FIX_4_4 = "FIX.4.4"; // String FIX_5_0 = "FIXT.1.1"; // // FixMessageHeader getHeader(); // // List<FixMessageFragment> getBody(); // // Integer getInt(int tagNum); // // Integer getInt(FieldType field); // // String getString(int tagNum); // // @SuppressWarnings("unchecked") // <T> T getValue(int tagNum); // // String getString(FieldType field); // // <T> T getValue(FieldType field); // // Character getChar(int tagNum); // // Character getChar(FieldType fieldType); // // String getMessageType(); // // default FixMessageFragment getFirst(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // default List<FixMessageFragment> getAll(int tagNum) { // final List<FixMessageFragment> body = getBody(); // List<FixMessageFragment> result = new ArrayList<>(8); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // result.add(item); // } // } // return result; // } // // default FixMessageFragment getLast(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = body.size() - 1; i >= 0; i--) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // } // // Path: core/src/main/java/fixio/fixprotocol/FixMessageBuilder.java // public interface FixMessageBuilder extends FieldListBuilder<FixMessageBuilder> { // FixMessageHeader getHeader(); // // void copyHeader(FixMessageHeader header); // // List<? extends FixMessageFragment> getBody(); // // void copyBody(List<? extends FixMessageFragment> body); // } // // Path: core/src/main/java/fixio/validator/BusinessRejectException.java // public class BusinessRejectException extends Exception { // // /** // * MsgSeqNum of rejected message // */ // private final int refSeqNum; // // /** // * The MsgType of the FIX message being referenced. // */ // private final String refMsgType; // // /** // * The value of the business-level "ID" field on the message being referenced. // * Required unless the corresponding ID field (see list above) was not specified. // */ // private final int businessRejectReason; // // /** // * Where possible, message to explain reason for rejection. // */ // private final String text; // // public BusinessRejectException(int refSeqNum, String refMsgType, int businessRejectReason, String text) { // super(text); // this.refSeqNum = refSeqNum; // this.refMsgType = refMsgType; // this.businessRejectReason = businessRejectReason; // this.text = text; // } // // public int getRefSeqNum() { // return refSeqNum; // } // // public String getRefMsgType() { // return refMsgType; // } // // public int getBusinessRejectReason() { // return businessRejectReason; // } // // public String getText() { // return text; // } // } // // Path: core/src/main/java/fixio/validator/FixMessageValidator.java // public interface FixMessageValidator { // // void validate(ChannelHandlerContext ctx, FixMessage msg); // } // Path: core/src/main/java/fixio/handlers/CompositeFixApplicationAdapter.java import fixio.fixprotocol.FixMessage; import fixio.fixprotocol.FixMessageBuilder; import fixio.validator.BusinessRejectException; import fixio.validator.FixMessageValidator; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List; /* * Copyright 2014 The FIX.io Project * * The FIX.io 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 fixio.handlers; @ChannelHandler.Sharable public class CompositeFixApplicationAdapter extends FixApplicationAdapter { private static final Logger LOGGER = LoggerFactory.getLogger(CompositeFixApplicationAdapter.class); private final List<FixMessageHandler> handlers;
private final List<FixMessageValidator> validators;
kpavlov/fixio
core/src/main/java/fixio/handlers/CompositeFixApplicationAdapter.java
// Path: core/src/main/java/fixio/fixprotocol/FixMessage.java // public interface FixMessage { // // String FIX_4_0 = "FIX.4.0"; // String FIX_4_1 = "FIX.4.1"; // String FIX_4_2 = "FIX.4.2"; // String FIX_4_3 = "FIX.4.3"; // String FIX_4_4 = "FIX.4.4"; // String FIX_5_0 = "FIXT.1.1"; // // FixMessageHeader getHeader(); // // List<FixMessageFragment> getBody(); // // Integer getInt(int tagNum); // // Integer getInt(FieldType field); // // String getString(int tagNum); // // @SuppressWarnings("unchecked") // <T> T getValue(int tagNum); // // String getString(FieldType field); // // <T> T getValue(FieldType field); // // Character getChar(int tagNum); // // Character getChar(FieldType fieldType); // // String getMessageType(); // // default FixMessageFragment getFirst(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // default List<FixMessageFragment> getAll(int tagNum) { // final List<FixMessageFragment> body = getBody(); // List<FixMessageFragment> result = new ArrayList<>(8); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // result.add(item); // } // } // return result; // } // // default FixMessageFragment getLast(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = body.size() - 1; i >= 0; i--) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // } // // Path: core/src/main/java/fixio/fixprotocol/FixMessageBuilder.java // public interface FixMessageBuilder extends FieldListBuilder<FixMessageBuilder> { // FixMessageHeader getHeader(); // // void copyHeader(FixMessageHeader header); // // List<? extends FixMessageFragment> getBody(); // // void copyBody(List<? extends FixMessageFragment> body); // } // // Path: core/src/main/java/fixio/validator/BusinessRejectException.java // public class BusinessRejectException extends Exception { // // /** // * MsgSeqNum of rejected message // */ // private final int refSeqNum; // // /** // * The MsgType of the FIX message being referenced. // */ // private final String refMsgType; // // /** // * The value of the business-level "ID" field on the message being referenced. // * Required unless the corresponding ID field (see list above) was not specified. // */ // private final int businessRejectReason; // // /** // * Where possible, message to explain reason for rejection. // */ // private final String text; // // public BusinessRejectException(int refSeqNum, String refMsgType, int businessRejectReason, String text) { // super(text); // this.refSeqNum = refSeqNum; // this.refMsgType = refMsgType; // this.businessRejectReason = businessRejectReason; // this.text = text; // } // // public int getRefSeqNum() { // return refSeqNum; // } // // public String getRefMsgType() { // return refMsgType; // } // // public int getBusinessRejectReason() { // return businessRejectReason; // } // // public String getText() { // return text; // } // } // // Path: core/src/main/java/fixio/validator/FixMessageValidator.java // public interface FixMessageValidator { // // void validate(ChannelHandlerContext ctx, FixMessage msg); // }
import fixio.fixprotocol.FixMessage; import fixio.fixprotocol.FixMessageBuilder; import fixio.validator.BusinessRejectException; import fixio.validator.FixMessageValidator; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List;
/* * Copyright 2014 The FIX.io Project * * The FIX.io 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 fixio.handlers; @ChannelHandler.Sharable public class CompositeFixApplicationAdapter extends FixApplicationAdapter { private static final Logger LOGGER = LoggerFactory.getLogger(CompositeFixApplicationAdapter.class); private final List<FixMessageHandler> handlers; private final List<FixMessageValidator> validators; public CompositeFixApplicationAdapter(List<FixMessageValidator> validators, List<FixMessageHandler> handlers) { assert (validators != null) : "FixMessageValidators expected"; assert (handlers != null) : "FixMessageHandlers expected"; this.validators = Collections.unmodifiableList(validators); this.handlers = Collections.unmodifiableList(handlers); } @Override
// Path: core/src/main/java/fixio/fixprotocol/FixMessage.java // public interface FixMessage { // // String FIX_4_0 = "FIX.4.0"; // String FIX_4_1 = "FIX.4.1"; // String FIX_4_2 = "FIX.4.2"; // String FIX_4_3 = "FIX.4.3"; // String FIX_4_4 = "FIX.4.4"; // String FIX_5_0 = "FIXT.1.1"; // // FixMessageHeader getHeader(); // // List<FixMessageFragment> getBody(); // // Integer getInt(int tagNum); // // Integer getInt(FieldType field); // // String getString(int tagNum); // // @SuppressWarnings("unchecked") // <T> T getValue(int tagNum); // // String getString(FieldType field); // // <T> T getValue(FieldType field); // // Character getChar(int tagNum); // // Character getChar(FieldType fieldType); // // String getMessageType(); // // default FixMessageFragment getFirst(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // default List<FixMessageFragment> getAll(int tagNum) { // final List<FixMessageFragment> body = getBody(); // List<FixMessageFragment> result = new ArrayList<>(8); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // result.add(item); // } // } // return result; // } // // default FixMessageFragment getLast(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = body.size() - 1; i >= 0; i--) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // } // // Path: core/src/main/java/fixio/fixprotocol/FixMessageBuilder.java // public interface FixMessageBuilder extends FieldListBuilder<FixMessageBuilder> { // FixMessageHeader getHeader(); // // void copyHeader(FixMessageHeader header); // // List<? extends FixMessageFragment> getBody(); // // void copyBody(List<? extends FixMessageFragment> body); // } // // Path: core/src/main/java/fixio/validator/BusinessRejectException.java // public class BusinessRejectException extends Exception { // // /** // * MsgSeqNum of rejected message // */ // private final int refSeqNum; // // /** // * The MsgType of the FIX message being referenced. // */ // private final String refMsgType; // // /** // * The value of the business-level "ID" field on the message being referenced. // * Required unless the corresponding ID field (see list above) was not specified. // */ // private final int businessRejectReason; // // /** // * Where possible, message to explain reason for rejection. // */ // private final String text; // // public BusinessRejectException(int refSeqNum, String refMsgType, int businessRejectReason, String text) { // super(text); // this.refSeqNum = refSeqNum; // this.refMsgType = refMsgType; // this.businessRejectReason = businessRejectReason; // this.text = text; // } // // public int getRefSeqNum() { // return refSeqNum; // } // // public String getRefMsgType() { // return refMsgType; // } // // public int getBusinessRejectReason() { // return businessRejectReason; // } // // public String getText() { // return text; // } // } // // Path: core/src/main/java/fixio/validator/FixMessageValidator.java // public interface FixMessageValidator { // // void validate(ChannelHandlerContext ctx, FixMessage msg); // } // Path: core/src/main/java/fixio/handlers/CompositeFixApplicationAdapter.java import fixio.fixprotocol.FixMessage; import fixio.fixprotocol.FixMessageBuilder; import fixio.validator.BusinessRejectException; import fixio.validator.FixMessageValidator; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List; /* * Copyright 2014 The FIX.io Project * * The FIX.io 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 fixio.handlers; @ChannelHandler.Sharable public class CompositeFixApplicationAdapter extends FixApplicationAdapter { private static final Logger LOGGER = LoggerFactory.getLogger(CompositeFixApplicationAdapter.class); private final List<FixMessageHandler> handlers; private final List<FixMessageValidator> validators; public CompositeFixApplicationAdapter(List<FixMessageValidator> validators, List<FixMessageHandler> handlers) { assert (validators != null) : "FixMessageValidators expected"; assert (handlers != null) : "FixMessageHandlers expected"; this.validators = Collections.unmodifiableList(validators); this.handlers = Collections.unmodifiableList(handlers); } @Override
public void onMessage(ChannelHandlerContext ctx, FixMessage msg, List<Object> out) throws BusinessRejectException {
kpavlov/fixio
core/src/main/java/fixio/handlers/CompositeFixApplicationAdapter.java
// Path: core/src/main/java/fixio/fixprotocol/FixMessage.java // public interface FixMessage { // // String FIX_4_0 = "FIX.4.0"; // String FIX_4_1 = "FIX.4.1"; // String FIX_4_2 = "FIX.4.2"; // String FIX_4_3 = "FIX.4.3"; // String FIX_4_4 = "FIX.4.4"; // String FIX_5_0 = "FIXT.1.1"; // // FixMessageHeader getHeader(); // // List<FixMessageFragment> getBody(); // // Integer getInt(int tagNum); // // Integer getInt(FieldType field); // // String getString(int tagNum); // // @SuppressWarnings("unchecked") // <T> T getValue(int tagNum); // // String getString(FieldType field); // // <T> T getValue(FieldType field); // // Character getChar(int tagNum); // // Character getChar(FieldType fieldType); // // String getMessageType(); // // default FixMessageFragment getFirst(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // default List<FixMessageFragment> getAll(int tagNum) { // final List<FixMessageFragment> body = getBody(); // List<FixMessageFragment> result = new ArrayList<>(8); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // result.add(item); // } // } // return result; // } // // default FixMessageFragment getLast(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = body.size() - 1; i >= 0; i--) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // } // // Path: core/src/main/java/fixio/fixprotocol/FixMessageBuilder.java // public interface FixMessageBuilder extends FieldListBuilder<FixMessageBuilder> { // FixMessageHeader getHeader(); // // void copyHeader(FixMessageHeader header); // // List<? extends FixMessageFragment> getBody(); // // void copyBody(List<? extends FixMessageFragment> body); // } // // Path: core/src/main/java/fixio/validator/BusinessRejectException.java // public class BusinessRejectException extends Exception { // // /** // * MsgSeqNum of rejected message // */ // private final int refSeqNum; // // /** // * The MsgType of the FIX message being referenced. // */ // private final String refMsgType; // // /** // * The value of the business-level "ID" field on the message being referenced. // * Required unless the corresponding ID field (see list above) was not specified. // */ // private final int businessRejectReason; // // /** // * Where possible, message to explain reason for rejection. // */ // private final String text; // // public BusinessRejectException(int refSeqNum, String refMsgType, int businessRejectReason, String text) { // super(text); // this.refSeqNum = refSeqNum; // this.refMsgType = refMsgType; // this.businessRejectReason = businessRejectReason; // this.text = text; // } // // public int getRefSeqNum() { // return refSeqNum; // } // // public String getRefMsgType() { // return refMsgType; // } // // public int getBusinessRejectReason() { // return businessRejectReason; // } // // public String getText() { // return text; // } // } // // Path: core/src/main/java/fixio/validator/FixMessageValidator.java // public interface FixMessageValidator { // // void validate(ChannelHandlerContext ctx, FixMessage msg); // }
import fixio.fixprotocol.FixMessage; import fixio.fixprotocol.FixMessageBuilder; import fixio.validator.BusinessRejectException; import fixio.validator.FixMessageValidator; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List;
/* * Copyright 2014 The FIX.io Project * * The FIX.io 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 fixio.handlers; @ChannelHandler.Sharable public class CompositeFixApplicationAdapter extends FixApplicationAdapter { private static final Logger LOGGER = LoggerFactory.getLogger(CompositeFixApplicationAdapter.class); private final List<FixMessageHandler> handlers; private final List<FixMessageValidator> validators; public CompositeFixApplicationAdapter(List<FixMessageValidator> validators, List<FixMessageHandler> handlers) { assert (validators != null) : "FixMessageValidators expected"; assert (handlers != null) : "FixMessageHandlers expected"; this.validators = Collections.unmodifiableList(validators); this.handlers = Collections.unmodifiableList(handlers); } @Override
// Path: core/src/main/java/fixio/fixprotocol/FixMessage.java // public interface FixMessage { // // String FIX_4_0 = "FIX.4.0"; // String FIX_4_1 = "FIX.4.1"; // String FIX_4_2 = "FIX.4.2"; // String FIX_4_3 = "FIX.4.3"; // String FIX_4_4 = "FIX.4.4"; // String FIX_5_0 = "FIXT.1.1"; // // FixMessageHeader getHeader(); // // List<FixMessageFragment> getBody(); // // Integer getInt(int tagNum); // // Integer getInt(FieldType field); // // String getString(int tagNum); // // @SuppressWarnings("unchecked") // <T> T getValue(int tagNum); // // String getString(FieldType field); // // <T> T getValue(FieldType field); // // Character getChar(int tagNum); // // Character getChar(FieldType fieldType); // // String getMessageType(); // // default FixMessageFragment getFirst(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // default List<FixMessageFragment> getAll(int tagNum) { // final List<FixMessageFragment> body = getBody(); // List<FixMessageFragment> result = new ArrayList<>(8); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // result.add(item); // } // } // return result; // } // // default FixMessageFragment getLast(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = body.size() - 1; i >= 0; i--) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // } // // Path: core/src/main/java/fixio/fixprotocol/FixMessageBuilder.java // public interface FixMessageBuilder extends FieldListBuilder<FixMessageBuilder> { // FixMessageHeader getHeader(); // // void copyHeader(FixMessageHeader header); // // List<? extends FixMessageFragment> getBody(); // // void copyBody(List<? extends FixMessageFragment> body); // } // // Path: core/src/main/java/fixio/validator/BusinessRejectException.java // public class BusinessRejectException extends Exception { // // /** // * MsgSeqNum of rejected message // */ // private final int refSeqNum; // // /** // * The MsgType of the FIX message being referenced. // */ // private final String refMsgType; // // /** // * The value of the business-level "ID" field on the message being referenced. // * Required unless the corresponding ID field (see list above) was not specified. // */ // private final int businessRejectReason; // // /** // * Where possible, message to explain reason for rejection. // */ // private final String text; // // public BusinessRejectException(int refSeqNum, String refMsgType, int businessRejectReason, String text) { // super(text); // this.refSeqNum = refSeqNum; // this.refMsgType = refMsgType; // this.businessRejectReason = businessRejectReason; // this.text = text; // } // // public int getRefSeqNum() { // return refSeqNum; // } // // public String getRefMsgType() { // return refMsgType; // } // // public int getBusinessRejectReason() { // return businessRejectReason; // } // // public String getText() { // return text; // } // } // // Path: core/src/main/java/fixio/validator/FixMessageValidator.java // public interface FixMessageValidator { // // void validate(ChannelHandlerContext ctx, FixMessage msg); // } // Path: core/src/main/java/fixio/handlers/CompositeFixApplicationAdapter.java import fixio.fixprotocol.FixMessage; import fixio.fixprotocol.FixMessageBuilder; import fixio.validator.BusinessRejectException; import fixio.validator.FixMessageValidator; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List; /* * Copyright 2014 The FIX.io Project * * The FIX.io 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 fixio.handlers; @ChannelHandler.Sharable public class CompositeFixApplicationAdapter extends FixApplicationAdapter { private static final Logger LOGGER = LoggerFactory.getLogger(CompositeFixApplicationAdapter.class); private final List<FixMessageHandler> handlers; private final List<FixMessageValidator> validators; public CompositeFixApplicationAdapter(List<FixMessageValidator> validators, List<FixMessageHandler> handlers) { assert (validators != null) : "FixMessageValidators expected"; assert (handlers != null) : "FixMessageHandlers expected"; this.validators = Collections.unmodifiableList(validators); this.handlers = Collections.unmodifiableList(handlers); } @Override
public void onMessage(ChannelHandlerContext ctx, FixMessage msg, List<Object> out) throws BusinessRejectException {
kpavlov/fixio
core/src/main/java/fixio/handlers/CompositeFixApplicationAdapter.java
// Path: core/src/main/java/fixio/fixprotocol/FixMessage.java // public interface FixMessage { // // String FIX_4_0 = "FIX.4.0"; // String FIX_4_1 = "FIX.4.1"; // String FIX_4_2 = "FIX.4.2"; // String FIX_4_3 = "FIX.4.3"; // String FIX_4_4 = "FIX.4.4"; // String FIX_5_0 = "FIXT.1.1"; // // FixMessageHeader getHeader(); // // List<FixMessageFragment> getBody(); // // Integer getInt(int tagNum); // // Integer getInt(FieldType field); // // String getString(int tagNum); // // @SuppressWarnings("unchecked") // <T> T getValue(int tagNum); // // String getString(FieldType field); // // <T> T getValue(FieldType field); // // Character getChar(int tagNum); // // Character getChar(FieldType fieldType); // // String getMessageType(); // // default FixMessageFragment getFirst(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // default List<FixMessageFragment> getAll(int tagNum) { // final List<FixMessageFragment> body = getBody(); // List<FixMessageFragment> result = new ArrayList<>(8); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // result.add(item); // } // } // return result; // } // // default FixMessageFragment getLast(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = body.size() - 1; i >= 0; i--) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // } // // Path: core/src/main/java/fixio/fixprotocol/FixMessageBuilder.java // public interface FixMessageBuilder extends FieldListBuilder<FixMessageBuilder> { // FixMessageHeader getHeader(); // // void copyHeader(FixMessageHeader header); // // List<? extends FixMessageFragment> getBody(); // // void copyBody(List<? extends FixMessageFragment> body); // } // // Path: core/src/main/java/fixio/validator/BusinessRejectException.java // public class BusinessRejectException extends Exception { // // /** // * MsgSeqNum of rejected message // */ // private final int refSeqNum; // // /** // * The MsgType of the FIX message being referenced. // */ // private final String refMsgType; // // /** // * The value of the business-level "ID" field on the message being referenced. // * Required unless the corresponding ID field (see list above) was not specified. // */ // private final int businessRejectReason; // // /** // * Where possible, message to explain reason for rejection. // */ // private final String text; // // public BusinessRejectException(int refSeqNum, String refMsgType, int businessRejectReason, String text) { // super(text); // this.refSeqNum = refSeqNum; // this.refMsgType = refMsgType; // this.businessRejectReason = businessRejectReason; // this.text = text; // } // // public int getRefSeqNum() { // return refSeqNum; // } // // public String getRefMsgType() { // return refMsgType; // } // // public int getBusinessRejectReason() { // return businessRejectReason; // } // // public String getText() { // return text; // } // } // // Path: core/src/main/java/fixio/validator/FixMessageValidator.java // public interface FixMessageValidator { // // void validate(ChannelHandlerContext ctx, FixMessage msg); // }
import fixio.fixprotocol.FixMessage; import fixio.fixprotocol.FixMessageBuilder; import fixio.validator.BusinessRejectException; import fixio.validator.FixMessageValidator; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List;
@Override public void onMessage(ChannelHandlerContext ctx, FixMessage msg, List<Object> out) throws BusinessRejectException { assert (msg != null) : "Message can't be null"; LOGGER.info("Received : {}", msg); //Validate for (FixMessageValidator validator : validators) { validator.validate(ctx, msg); } //Business handler if (handlers != null) { boolean isHandled = false; for (FixMessageHandler handler : handlers) { try { if (handler.handle(ctx, msg)) { isHandled = true; } } catch (Exception ex) { LOGGER.error("on {} ", handler.getClass(), ex); } } if (!isHandled) { LOGGER.warn("no handler for this message. {} ", msg); } } } @Override
// Path: core/src/main/java/fixio/fixprotocol/FixMessage.java // public interface FixMessage { // // String FIX_4_0 = "FIX.4.0"; // String FIX_4_1 = "FIX.4.1"; // String FIX_4_2 = "FIX.4.2"; // String FIX_4_3 = "FIX.4.3"; // String FIX_4_4 = "FIX.4.4"; // String FIX_5_0 = "FIXT.1.1"; // // FixMessageHeader getHeader(); // // List<FixMessageFragment> getBody(); // // Integer getInt(int tagNum); // // Integer getInt(FieldType field); // // String getString(int tagNum); // // @SuppressWarnings("unchecked") // <T> T getValue(int tagNum); // // String getString(FieldType field); // // <T> T getValue(FieldType field); // // Character getChar(int tagNum); // // Character getChar(FieldType fieldType); // // String getMessageType(); // // default FixMessageFragment getFirst(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // default List<FixMessageFragment> getAll(int tagNum) { // final List<FixMessageFragment> body = getBody(); // List<FixMessageFragment> result = new ArrayList<>(8); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // result.add(item); // } // } // return result; // } // // default FixMessageFragment getLast(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = body.size() - 1; i >= 0; i--) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // } // // Path: core/src/main/java/fixio/fixprotocol/FixMessageBuilder.java // public interface FixMessageBuilder extends FieldListBuilder<FixMessageBuilder> { // FixMessageHeader getHeader(); // // void copyHeader(FixMessageHeader header); // // List<? extends FixMessageFragment> getBody(); // // void copyBody(List<? extends FixMessageFragment> body); // } // // Path: core/src/main/java/fixio/validator/BusinessRejectException.java // public class BusinessRejectException extends Exception { // // /** // * MsgSeqNum of rejected message // */ // private final int refSeqNum; // // /** // * The MsgType of the FIX message being referenced. // */ // private final String refMsgType; // // /** // * The value of the business-level "ID" field on the message being referenced. // * Required unless the corresponding ID field (see list above) was not specified. // */ // private final int businessRejectReason; // // /** // * Where possible, message to explain reason for rejection. // */ // private final String text; // // public BusinessRejectException(int refSeqNum, String refMsgType, int businessRejectReason, String text) { // super(text); // this.refSeqNum = refSeqNum; // this.refMsgType = refMsgType; // this.businessRejectReason = businessRejectReason; // this.text = text; // } // // public int getRefSeqNum() { // return refSeqNum; // } // // public String getRefMsgType() { // return refMsgType; // } // // public int getBusinessRejectReason() { // return businessRejectReason; // } // // public String getText() { // return text; // } // } // // Path: core/src/main/java/fixio/validator/FixMessageValidator.java // public interface FixMessageValidator { // // void validate(ChannelHandlerContext ctx, FixMessage msg); // } // Path: core/src/main/java/fixio/handlers/CompositeFixApplicationAdapter.java import fixio.fixprotocol.FixMessage; import fixio.fixprotocol.FixMessageBuilder; import fixio.validator.BusinessRejectException; import fixio.validator.FixMessageValidator; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List; @Override public void onMessage(ChannelHandlerContext ctx, FixMessage msg, List<Object> out) throws BusinessRejectException { assert (msg != null) : "Message can't be null"; LOGGER.info("Received : {}", msg); //Validate for (FixMessageValidator validator : validators) { validator.validate(ctx, msg); } //Business handler if (handlers != null) { boolean isHandled = false; for (FixMessageHandler handler : handlers) { try { if (handler.handle(ctx, msg)) { isHandled = true; } } catch (Exception ex) { LOGGER.error("on {} ", handler.getClass(), ex); } } if (!isHandled) { LOGGER.warn("no handler for this message. {} ", msg); } } } @Override
public void beforeSendMessage(ChannelHandlerContext ctx, FixMessageBuilder msg) {
kpavlov/fixio
core/src/main/java/fixio/netty/pipeline/server/AcceptAllAuthenticator.java
// Path: core/src/main/java/fixio/fixprotocol/FixMessage.java // public interface FixMessage { // // String FIX_4_0 = "FIX.4.0"; // String FIX_4_1 = "FIX.4.1"; // String FIX_4_2 = "FIX.4.2"; // String FIX_4_3 = "FIX.4.3"; // String FIX_4_4 = "FIX.4.4"; // String FIX_5_0 = "FIXT.1.1"; // // FixMessageHeader getHeader(); // // List<FixMessageFragment> getBody(); // // Integer getInt(int tagNum); // // Integer getInt(FieldType field); // // String getString(int tagNum); // // @SuppressWarnings("unchecked") // <T> T getValue(int tagNum); // // String getString(FieldType field); // // <T> T getValue(FieldType field); // // Character getChar(int tagNum); // // Character getChar(FieldType fieldType); // // String getMessageType(); // // default FixMessageFragment getFirst(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // default List<FixMessageFragment> getAll(int tagNum) { // final List<FixMessageFragment> body = getBody(); // List<FixMessageFragment> result = new ArrayList<>(8); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // result.add(item); // } // } // return result; // } // // default FixMessageFragment getLast(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = body.size() - 1; i >= 0; i--) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // }
import fixio.fixprotocol.FixMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright 2013 The FIX.io Project * * The FIX.io 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 fixio.netty.pipeline.server; public class AcceptAllAuthenticator implements FixAuthenticator { private static final Logger LOGGER = LoggerFactory.getLogger(AcceptAllAuthenticator.class); @Override
// Path: core/src/main/java/fixio/fixprotocol/FixMessage.java // public interface FixMessage { // // String FIX_4_0 = "FIX.4.0"; // String FIX_4_1 = "FIX.4.1"; // String FIX_4_2 = "FIX.4.2"; // String FIX_4_3 = "FIX.4.3"; // String FIX_4_4 = "FIX.4.4"; // String FIX_5_0 = "FIXT.1.1"; // // FixMessageHeader getHeader(); // // List<FixMessageFragment> getBody(); // // Integer getInt(int tagNum); // // Integer getInt(FieldType field); // // String getString(int tagNum); // // @SuppressWarnings("unchecked") // <T> T getValue(int tagNum); // // String getString(FieldType field); // // <T> T getValue(FieldType field); // // Character getChar(int tagNum); // // Character getChar(FieldType fieldType); // // String getMessageType(); // // default FixMessageFragment getFirst(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // default List<FixMessageFragment> getAll(int tagNum) { // final List<FixMessageFragment> body = getBody(); // List<FixMessageFragment> result = new ArrayList<>(8); // for (int i = 0; i < body.size(); i++) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // result.add(item); // } // } // return result; // } // // default FixMessageFragment getLast(int tagNum) { // final List<FixMessageFragment> body = getBody(); // for (int i = body.size() - 1; i >= 0; i--) { // FixMessageFragment item = body.get(i); // if (item.getTagNum() == tagNum) { // return item; // } // } // return null; // } // // } // Path: core/src/main/java/fixio/netty/pipeline/server/AcceptAllAuthenticator.java import fixio.fixprotocol.FixMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Copyright 2013 The FIX.io Project * * The FIX.io 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 fixio.netty.pipeline.server; public class AcceptAllAuthenticator implements FixAuthenticator { private static final Logger LOGGER = LoggerFactory.getLogger(AcceptAllAuthenticator.class); @Override
public boolean authenticate(FixMessage logonMessage) {
lovro-i/apro
src/fr/lri/tao/apro/data/points/PointsProvider.java
// Path: src/fr/lri/tao/apro/data/DataProvider.java // public interface DataProvider { // // /** Similarity matrix as Java's array of arrays // * @return Similarity matrix with preferences on the main diagonal, in Colt format */ // public DoubleMatrix2D getMatrix(); // // /** Number of elements in the dataset, i.e. the size of the matrix (size x size) */ // public int size(); // // /** Add noise to the similarity matrix */ // public void addNoise(); // } // // Path: src/fr/lri/tao/apro/util/Utils.java // public class Utils { // // private static final double EPSILON = 1E-14; // private static final double REALMIN100 = 100 * Double.MIN_NORMAL; // // // public static String toString(double[][] a) { // int maxLength = 12; // StringBuilder sb = new StringBuilder(); // for (int i=0; i<a.length; i++) { // for (int j=0; j<a[i].length; j++) { // String val = String.valueOf(a[i][j]); // maxLength = Math.max(maxLength, val.length()); // while (val.length() < maxLength) val = " " + val; // sb.append(val); // } // sb.append("\n"); // } // return sb.toString(); // } // // public static String toString(double[][] a, int decimals) { // if (decimals < 0) throw new IllegalArgumentException("Number of decimals must be positive"); // StringBuilder decs = new StringBuilder("0."); // for (int i = 0; i < decimals; i++) decs.append("0"); // NumberFormat decimalsFormat = new DecimalFormat(decs.toString()); // // StringBuilder sb = new StringBuilder(); // for (int i=0; i<a.length; i++) { // for (int j=0; j<a[i].length; j++) { // sb.append(decimalsFormat.format(a[i][j])).append(" "); // } // sb.append("\n"); // } // return sb.toString(); // } // // public static void addNoise(double[][] s) { // for (int i=0; i<s.length; i++) { // for (int j=0; j<s[i].length; j++) { // s[i][j] = s[i][j] + (EPSILON * s[i][j] + REALMIN100) * Math.random(); // } // } // } // // public static void addNoise(DoubleMatrix2D s) { // IntArrayList is = new IntArrayList(); // IntArrayList ks = new IntArrayList(); // DoubleArrayList vs = new DoubleArrayList(); // s.getNonZeros(is, ks, vs); // // for (int j=0; j<is.size(); j++) { // int i = is.get(j); // int k = ks.get(j); // double v = vs.get(j); // v = v + (EPSILON * v + REALMIN100) * Math.random(); // s.setQuick(i, k, v); // } // } // // }
import cern.colt.matrix.DoubleMatrix2D; import cern.colt.matrix.impl.DenseDoubleMatrix2D; import fr.lri.tao.apro.data.DataProvider; import fr.lri.tao.apro.util.Utils; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer;
points.add(point); } reader.close(); return points; } public Points getPoints() { return points; } public SimilarityMeasure getSimilarityMeasure() { return measure; } @Override public DoubleMatrix2D getMatrix() { return new DenseDoubleMatrix2D(s); } public double[][] getS() { return s; } @Override public int size() { return points.size(); } @Override public void addNoise() {
// Path: src/fr/lri/tao/apro/data/DataProvider.java // public interface DataProvider { // // /** Similarity matrix as Java's array of arrays // * @return Similarity matrix with preferences on the main diagonal, in Colt format */ // public DoubleMatrix2D getMatrix(); // // /** Number of elements in the dataset, i.e. the size of the matrix (size x size) */ // public int size(); // // /** Add noise to the similarity matrix */ // public void addNoise(); // } // // Path: src/fr/lri/tao/apro/util/Utils.java // public class Utils { // // private static final double EPSILON = 1E-14; // private static final double REALMIN100 = 100 * Double.MIN_NORMAL; // // // public static String toString(double[][] a) { // int maxLength = 12; // StringBuilder sb = new StringBuilder(); // for (int i=0; i<a.length; i++) { // for (int j=0; j<a[i].length; j++) { // String val = String.valueOf(a[i][j]); // maxLength = Math.max(maxLength, val.length()); // while (val.length() < maxLength) val = " " + val; // sb.append(val); // } // sb.append("\n"); // } // return sb.toString(); // } // // public static String toString(double[][] a, int decimals) { // if (decimals < 0) throw new IllegalArgumentException("Number of decimals must be positive"); // StringBuilder decs = new StringBuilder("0."); // for (int i = 0; i < decimals; i++) decs.append("0"); // NumberFormat decimalsFormat = new DecimalFormat(decs.toString()); // // StringBuilder sb = new StringBuilder(); // for (int i=0; i<a.length; i++) { // for (int j=0; j<a[i].length; j++) { // sb.append(decimalsFormat.format(a[i][j])).append(" "); // } // sb.append("\n"); // } // return sb.toString(); // } // // public static void addNoise(double[][] s) { // for (int i=0; i<s.length; i++) { // for (int j=0; j<s[i].length; j++) { // s[i][j] = s[i][j] + (EPSILON * s[i][j] + REALMIN100) * Math.random(); // } // } // } // // public static void addNoise(DoubleMatrix2D s) { // IntArrayList is = new IntArrayList(); // IntArrayList ks = new IntArrayList(); // DoubleArrayList vs = new DoubleArrayList(); // s.getNonZeros(is, ks, vs); // // for (int j=0; j<is.size(); j++) { // int i = is.get(j); // int k = ks.get(j); // double v = vs.get(j); // v = v + (EPSILON * v + REALMIN100) * Math.random(); // s.setQuick(i, k, v); // } // } // // } // Path: src/fr/lri/tao/apro/data/points/PointsProvider.java import cern.colt.matrix.DoubleMatrix2D; import cern.colt.matrix.impl.DenseDoubleMatrix2D; import fr.lri.tao.apro.data.DataProvider; import fr.lri.tao.apro.util.Utils; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; points.add(point); } reader.close(); return points; } public Points getPoints() { return points; } public SimilarityMeasure getSimilarityMeasure() { return measure; } @Override public DoubleMatrix2D getMatrix() { return new DenseDoubleMatrix2D(s); } public double[][] getS() { return s; } @Override public int size() { return points.size(); } @Override public void addNoise() {
Utils.addNoise(s);
lovro-i/apro
src/fr/lri/tao/apro/ap/GroupWorker.java
// Path: src/fr/lri/tao/numa/NUMA.java // public class NUMA { // // // public static boolean isAvailable() { // try { return NUMALibrary.INSTANCE.numa_available() != -1; } // catch (Throwable e) { return false; } // } // // public static int getMaxNode() { // return NUMALibrary.INSTANCE.numa_max_node(); // } // // public static int getNumNodes() { // return NUMALibrary.INSTANCE.numa_num_task_nodes(); // } // // public static int getNumCores() { // return NUMALibrary.INSTANCE.numa_num_task_cpus(); // } // // public static int getCoresPerNode() { // return getNumCores() / getNumNodes(); // } // // /** Get NUMA node of the specified cpu */ // public static int getNode(int cpu) { // return NUMALibrary.INSTANCE.numa_node_of_cpu(cpu); // } // // // public static int getNode(Object obj) { // // Pointer[] ptrs = new Pointer[1]; // // IntByReference c = new IntByReference(); // // PointerByReference pref = new PointerByReference(); // // //ptrs[0] = obj.; // // int[] status = new int[1]; // // NativeLong nl = new NativeLong(1l); // // NUMALibrary.INSTANCE.numa_move_pages(0, nl, ptrs, null, status, 0); // // return status[0]; // // } // // public static void allocOnNode(Integer node) { // if (node != null) NUMALibrary.INSTANCE.numa_set_preferred(node); // else localAlloc(); // } // // public static void localAlloc() { // if (!isAvailable()) return; // NUMALibrary.INSTANCE.numa_set_localalloc(); // } // // public static int runOnNode(int node) { // int res = NUMALibrary.INSTANCE.numa_run_on_node(node); // NUMALibrary.INSTANCE.numa_set_localalloc(); // return res; // } // // /** @return Current CPU */ // public static int getCore() { // return CLibrary.INSTANCE.sched_getcpu(); // } // // /** @return Current node */ // public static int getNode() { // return getNode(getCore()); // } // // public static List<Integer> getCores(int node) { // List<Integer> cores = new ArrayList<Integer>(); // // for (int cpu=0; cpu<getNumCores(); cpu++) { // // if (getNode(cpu) == node) cores.add(cpu); // // } // // return cores; // // NUMALibrary.Bitmask mask = NUMALibrary.INSTANCE.numa_allocate_cpumask(); // // or... NUMALibrary.Bitmask mask2 = NUMALibrary.INSTANCE.numa_bitmask_alloc(16); // // NUMALibrary.INSTANCE.numa_node_to_cpus(node, mask); // int cc = getNumCores(); // for (int cpu = 0; cpu < cc; cpu++) { // if (NUMALibrary.INSTANCE.numa_bitmask_isbitset(mask, cpu) > 0) cores.add(cpu); // } // // return cores; // } // // public static void main(String[] args) throws InterruptedException { // System.out.println("NUMA Available: " + NUMA.isAvailable()); // System.out.println("NUMA Nodes: " + NUMA.getNumNodes()); // System.out.println("NUMA Cores: " + NUMA.getNumCores()); // System.out.println("NUMA Node of core " + 44 +": "+NUMA.getNode(44)); // System.out.println("Running on node "+getNode()+", core "+getCore()); // // // Random random = new Random(); // List<Thread> threads = new ArrayList<Thread>(); // for (int i = 0; i < 100; i++) { // LittleThread t = new LittleThread(random.nextInt(NUMA.getNumNodes())); // t.start(); // threads.add(t); // } // // for (int i = 0; i < 100; i++) { // threads.get(i).join(); // } // // // List<Integer> cores = NUMA.getCores(5); // System.out.println(cores.size()); // System.out.println(Arrays.toString(cores.toArray())); // // System.out.println("Done."); // } // }
import fr.lri.tao.numa.NUMA;
package fr.lri.tao.apro.ap; public class GroupWorker extends Thread { public static enum Mode { RESPONSIBILITIES, AVAILABILITIES } private final Group group; private final boolean useNuma; private Mode mode; private Mode todo; private boolean go = false; private boolean done = false; private boolean busy = false; GroupWorker(Group group, boolean useNuma) { this.group = group; this.mode = null; this.useNuma = useNuma; } @Override public void run() { if (useNuma) { int node = group.getNumaNode();
// Path: src/fr/lri/tao/numa/NUMA.java // public class NUMA { // // // public static boolean isAvailable() { // try { return NUMALibrary.INSTANCE.numa_available() != -1; } // catch (Throwable e) { return false; } // } // // public static int getMaxNode() { // return NUMALibrary.INSTANCE.numa_max_node(); // } // // public static int getNumNodes() { // return NUMALibrary.INSTANCE.numa_num_task_nodes(); // } // // public static int getNumCores() { // return NUMALibrary.INSTANCE.numa_num_task_cpus(); // } // // public static int getCoresPerNode() { // return getNumCores() / getNumNodes(); // } // // /** Get NUMA node of the specified cpu */ // public static int getNode(int cpu) { // return NUMALibrary.INSTANCE.numa_node_of_cpu(cpu); // } // // // public static int getNode(Object obj) { // // Pointer[] ptrs = new Pointer[1]; // // IntByReference c = new IntByReference(); // // PointerByReference pref = new PointerByReference(); // // //ptrs[0] = obj.; // // int[] status = new int[1]; // // NativeLong nl = new NativeLong(1l); // // NUMALibrary.INSTANCE.numa_move_pages(0, nl, ptrs, null, status, 0); // // return status[0]; // // } // // public static void allocOnNode(Integer node) { // if (node != null) NUMALibrary.INSTANCE.numa_set_preferred(node); // else localAlloc(); // } // // public static void localAlloc() { // if (!isAvailable()) return; // NUMALibrary.INSTANCE.numa_set_localalloc(); // } // // public static int runOnNode(int node) { // int res = NUMALibrary.INSTANCE.numa_run_on_node(node); // NUMALibrary.INSTANCE.numa_set_localalloc(); // return res; // } // // /** @return Current CPU */ // public static int getCore() { // return CLibrary.INSTANCE.sched_getcpu(); // } // // /** @return Current node */ // public static int getNode() { // return getNode(getCore()); // } // // public static List<Integer> getCores(int node) { // List<Integer> cores = new ArrayList<Integer>(); // // for (int cpu=0; cpu<getNumCores(); cpu++) { // // if (getNode(cpu) == node) cores.add(cpu); // // } // // return cores; // // NUMALibrary.Bitmask mask = NUMALibrary.INSTANCE.numa_allocate_cpumask(); // // or... NUMALibrary.Bitmask mask2 = NUMALibrary.INSTANCE.numa_bitmask_alloc(16); // // NUMALibrary.INSTANCE.numa_node_to_cpus(node, mask); // int cc = getNumCores(); // for (int cpu = 0; cpu < cc; cpu++) { // if (NUMALibrary.INSTANCE.numa_bitmask_isbitset(mask, cpu) > 0) cores.add(cpu); // } // // return cores; // } // // public static void main(String[] args) throws InterruptedException { // System.out.println("NUMA Available: " + NUMA.isAvailable()); // System.out.println("NUMA Nodes: " + NUMA.getNumNodes()); // System.out.println("NUMA Cores: " + NUMA.getNumCores()); // System.out.println("NUMA Node of core " + 44 +": "+NUMA.getNode(44)); // System.out.println("Running on node "+getNode()+", core "+getCore()); // // // Random random = new Random(); // List<Thread> threads = new ArrayList<Thread>(); // for (int i = 0; i < 100; i++) { // LittleThread t = new LittleThread(random.nextInt(NUMA.getNumNodes())); // t.start(); // threads.add(t); // } // // for (int i = 0; i < 100; i++) { // threads.get(i).join(); // } // // // List<Integer> cores = NUMA.getCores(5); // System.out.println(cores.size()); // System.out.println(Arrays.toString(cores.toArray())); // // System.out.println("Done."); // } // } // Path: src/fr/lri/tao/apro/ap/GroupWorker.java import fr.lri.tao.numa.NUMA; package fr.lri.tao.apro.ap; public class GroupWorker extends Thread { public static enum Mode { RESPONSIBILITIES, AVAILABILITIES } private final Group group; private final boolean useNuma; private Mode mode; private Mode todo; private boolean go = false; private boolean done = false; private boolean busy = false; GroupWorker(Group group, boolean useNuma) { this.group = group; this.mode = null; this.useNuma = useNuma; } @Override public void run() { if (useNuma) { int node = group.getNumaNode();
NUMA.runOnNode(node);
lovro-i/apro
src/fr/lri/tao/apro/data/DSVProvider.java
// Path: src/fr/lri/tao/apro/util/Logger.java // public class Logger { // // private static final java.util.logging.Logger logger = java.util.logging.Logger.getLogger("fr.lri.tao.apro"); // // public static void info(String msg, Object... params) { // logger.info(String.format(msg, params)); // } // // public static void warn(String msg, Object... params) { // logger.warning(String.format(msg, params)); // } // // public static void warn(Throwable t) { // logger.warning(t.getMessage()); // } // // public static void warn(Throwable t, String msg, Object... params) { // logger.warning(t.getMessage() + "\n" + String.format(msg, params)); // } // // public static void error(String msg, Object... params) { // logger.severe(String.format(msg, params)); // } // // public static void error(Throwable t) { // logger.severe(t.getMessage()); // } // // public static void error(Throwable t, String msg, Object... params) { // logger.severe(t.getMessage() + "\n" + String.format(msg, params)); // } // // public static void log(Level level, String msg) { // logger.log(level, msg); // } // // public static void main(String[] args) { // Logger.info("Test %d", 5); // } // } // // Path: src/fr/lri/tao/apro/util/Utils.java // public class Utils { // // private static final double EPSILON = 1E-14; // private static final double REALMIN100 = 100 * Double.MIN_NORMAL; // // // public static String toString(double[][] a) { // int maxLength = 12; // StringBuilder sb = new StringBuilder(); // for (int i=0; i<a.length; i++) { // for (int j=0; j<a[i].length; j++) { // String val = String.valueOf(a[i][j]); // maxLength = Math.max(maxLength, val.length()); // while (val.length() < maxLength) val = " " + val; // sb.append(val); // } // sb.append("\n"); // } // return sb.toString(); // } // // public static String toString(double[][] a, int decimals) { // if (decimals < 0) throw new IllegalArgumentException("Number of decimals must be positive"); // StringBuilder decs = new StringBuilder("0."); // for (int i = 0; i < decimals; i++) decs.append("0"); // NumberFormat decimalsFormat = new DecimalFormat(decs.toString()); // // StringBuilder sb = new StringBuilder(); // for (int i=0; i<a.length; i++) { // for (int j=0; j<a[i].length; j++) { // sb.append(decimalsFormat.format(a[i][j])).append(" "); // } // sb.append("\n"); // } // return sb.toString(); // } // // public static void addNoise(double[][] s) { // for (int i=0; i<s.length; i++) { // for (int j=0; j<s[i].length; j++) { // s[i][j] = s[i][j] + (EPSILON * s[i][j] + REALMIN100) * Math.random(); // } // } // } // // public static void addNoise(DoubleMatrix2D s) { // IntArrayList is = new IntArrayList(); // IntArrayList ks = new IntArrayList(); // DoubleArrayList vs = new DoubleArrayList(); // s.getNonZeros(is, ks, vs); // // for (int j=0; j<is.size(); j++) { // int i = is.get(j); // int k = ks.get(j); // double v = vs.get(j); // v = v + (EPSILON * v + REALMIN100) * Math.random(); // s.setQuick(i, k, v); // } // } // // }
import cern.colt.matrix.DoubleMatrix2D; import cern.colt.matrix.impl.SparseDoubleMatrix2D; import fr.lri.tao.apro.util.Logger; import fr.lri.tao.apro.util.Utils; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer;
// Load preferences List<Double> prefs = loadPreferences(preferences); this.n = prefs.size(); // Similarity matrix s = new SparseDoubleMatrix2D(n, n); int c = 0; for (Double p: prefs) { s.set(c, c, p); c++; } // Load similarities int simCount = 0; String line; BufferedReader reader = new BufferedReader(new FileReader(similarities)); while ((line = reader.readLine()) != null) { List<String> tokens = getTokens(line, delimiters); int i = Integer.parseInt(tokens.get(0)) - base; int j = Integer.parseInt(tokens.get(1)) - base; Double v = Double.parseDouble(tokens.get(2)); s.set(i, j, v); simCount++; } reader.close(); double full = 100d * (simCount + n) / (n * n);
// Path: src/fr/lri/tao/apro/util/Logger.java // public class Logger { // // private static final java.util.logging.Logger logger = java.util.logging.Logger.getLogger("fr.lri.tao.apro"); // // public static void info(String msg, Object... params) { // logger.info(String.format(msg, params)); // } // // public static void warn(String msg, Object... params) { // logger.warning(String.format(msg, params)); // } // // public static void warn(Throwable t) { // logger.warning(t.getMessage()); // } // // public static void warn(Throwable t, String msg, Object... params) { // logger.warning(t.getMessage() + "\n" + String.format(msg, params)); // } // // public static void error(String msg, Object... params) { // logger.severe(String.format(msg, params)); // } // // public static void error(Throwable t) { // logger.severe(t.getMessage()); // } // // public static void error(Throwable t, String msg, Object... params) { // logger.severe(t.getMessage() + "\n" + String.format(msg, params)); // } // // public static void log(Level level, String msg) { // logger.log(level, msg); // } // // public static void main(String[] args) { // Logger.info("Test %d", 5); // } // } // // Path: src/fr/lri/tao/apro/util/Utils.java // public class Utils { // // private static final double EPSILON = 1E-14; // private static final double REALMIN100 = 100 * Double.MIN_NORMAL; // // // public static String toString(double[][] a) { // int maxLength = 12; // StringBuilder sb = new StringBuilder(); // for (int i=0; i<a.length; i++) { // for (int j=0; j<a[i].length; j++) { // String val = String.valueOf(a[i][j]); // maxLength = Math.max(maxLength, val.length()); // while (val.length() < maxLength) val = " " + val; // sb.append(val); // } // sb.append("\n"); // } // return sb.toString(); // } // // public static String toString(double[][] a, int decimals) { // if (decimals < 0) throw new IllegalArgumentException("Number of decimals must be positive"); // StringBuilder decs = new StringBuilder("0."); // for (int i = 0; i < decimals; i++) decs.append("0"); // NumberFormat decimalsFormat = new DecimalFormat(decs.toString()); // // StringBuilder sb = new StringBuilder(); // for (int i=0; i<a.length; i++) { // for (int j=0; j<a[i].length; j++) { // sb.append(decimalsFormat.format(a[i][j])).append(" "); // } // sb.append("\n"); // } // return sb.toString(); // } // // public static void addNoise(double[][] s) { // for (int i=0; i<s.length; i++) { // for (int j=0; j<s[i].length; j++) { // s[i][j] = s[i][j] + (EPSILON * s[i][j] + REALMIN100) * Math.random(); // } // } // } // // public static void addNoise(DoubleMatrix2D s) { // IntArrayList is = new IntArrayList(); // IntArrayList ks = new IntArrayList(); // DoubleArrayList vs = new DoubleArrayList(); // s.getNonZeros(is, ks, vs); // // for (int j=0; j<is.size(); j++) { // int i = is.get(j); // int k = ks.get(j); // double v = vs.get(j); // v = v + (EPSILON * v + REALMIN100) * Math.random(); // s.setQuick(i, k, v); // } // } // // } // Path: src/fr/lri/tao/apro/data/DSVProvider.java import cern.colt.matrix.DoubleMatrix2D; import cern.colt.matrix.impl.SparseDoubleMatrix2D; import fr.lri.tao.apro.util.Logger; import fr.lri.tao.apro.util.Utils; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; // Load preferences List<Double> prefs = loadPreferences(preferences); this.n = prefs.size(); // Similarity matrix s = new SparseDoubleMatrix2D(n, n); int c = 0; for (Double p: prefs) { s.set(c, c, p); c++; } // Load similarities int simCount = 0; String line; BufferedReader reader = new BufferedReader(new FileReader(similarities)); while ((line = reader.readLine()) != null) { List<String> tokens = getTokens(line, delimiters); int i = Integer.parseInt(tokens.get(0)) - base; int j = Integer.parseInt(tokens.get(1)) - base; Double v = Double.parseDouble(tokens.get(2)); s.set(i, j, v); simCount++; } reader.close(); double full = 100d * (simCount + n) / (n * n);
Logger.info("[Loader] Loaded %d similarities, matrix is %f%% populated", simCount, full);
lovro-i/apro
src/fr/lri/tao/apro/data/DSVProvider.java
// Path: src/fr/lri/tao/apro/util/Logger.java // public class Logger { // // private static final java.util.logging.Logger logger = java.util.logging.Logger.getLogger("fr.lri.tao.apro"); // // public static void info(String msg, Object... params) { // logger.info(String.format(msg, params)); // } // // public static void warn(String msg, Object... params) { // logger.warning(String.format(msg, params)); // } // // public static void warn(Throwable t) { // logger.warning(t.getMessage()); // } // // public static void warn(Throwable t, String msg, Object... params) { // logger.warning(t.getMessage() + "\n" + String.format(msg, params)); // } // // public static void error(String msg, Object... params) { // logger.severe(String.format(msg, params)); // } // // public static void error(Throwable t) { // logger.severe(t.getMessage()); // } // // public static void error(Throwable t, String msg, Object... params) { // logger.severe(t.getMessage() + "\n" + String.format(msg, params)); // } // // public static void log(Level level, String msg) { // logger.log(level, msg); // } // // public static void main(String[] args) { // Logger.info("Test %d", 5); // } // } // // Path: src/fr/lri/tao/apro/util/Utils.java // public class Utils { // // private static final double EPSILON = 1E-14; // private static final double REALMIN100 = 100 * Double.MIN_NORMAL; // // // public static String toString(double[][] a) { // int maxLength = 12; // StringBuilder sb = new StringBuilder(); // for (int i=0; i<a.length; i++) { // for (int j=0; j<a[i].length; j++) { // String val = String.valueOf(a[i][j]); // maxLength = Math.max(maxLength, val.length()); // while (val.length() < maxLength) val = " " + val; // sb.append(val); // } // sb.append("\n"); // } // return sb.toString(); // } // // public static String toString(double[][] a, int decimals) { // if (decimals < 0) throw new IllegalArgumentException("Number of decimals must be positive"); // StringBuilder decs = new StringBuilder("0."); // for (int i = 0; i < decimals; i++) decs.append("0"); // NumberFormat decimalsFormat = new DecimalFormat(decs.toString()); // // StringBuilder sb = new StringBuilder(); // for (int i=0; i<a.length; i++) { // for (int j=0; j<a[i].length; j++) { // sb.append(decimalsFormat.format(a[i][j])).append(" "); // } // sb.append("\n"); // } // return sb.toString(); // } // // public static void addNoise(double[][] s) { // for (int i=0; i<s.length; i++) { // for (int j=0; j<s[i].length; j++) { // s[i][j] = s[i][j] + (EPSILON * s[i][j] + REALMIN100) * Math.random(); // } // } // } // // public static void addNoise(DoubleMatrix2D s) { // IntArrayList is = new IntArrayList(); // IntArrayList ks = new IntArrayList(); // DoubleArrayList vs = new DoubleArrayList(); // s.getNonZeros(is, ks, vs); // // for (int j=0; j<is.size(); j++) { // int i = is.get(j); // int k = ks.get(j); // double v = vs.get(j); // v = v + (EPSILON * v + REALMIN100) * Math.random(); // s.setQuick(i, k, v); // } // } // // }
import cern.colt.matrix.DoubleMatrix2D; import cern.colt.matrix.impl.SparseDoubleMatrix2D; import fr.lri.tao.apro.util.Logger; import fr.lri.tao.apro.util.Utils; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer;
int simCount = 0; String line; BufferedReader reader = new BufferedReader(new FileReader(similarities)); while ((line = reader.readLine()) != null) { List<String> tokens = getTokens(line, delimiters); int i = Integer.parseInt(tokens.get(0)) - base; int j = Integer.parseInt(tokens.get(1)) - base; Double v = Double.parseDouble(tokens.get(2)); s.set(i, j, v); simCount++; } reader.close(); double full = 100d * (simCount + n) / (n * n); Logger.info("[Loader] Loaded %d similarities, matrix is %f%% populated", simCount, full); } @Override public DoubleMatrix2D getMatrix() { return s; } @Override public int size() { return n; } @Override public void addNoise() {
// Path: src/fr/lri/tao/apro/util/Logger.java // public class Logger { // // private static final java.util.logging.Logger logger = java.util.logging.Logger.getLogger("fr.lri.tao.apro"); // // public static void info(String msg, Object... params) { // logger.info(String.format(msg, params)); // } // // public static void warn(String msg, Object... params) { // logger.warning(String.format(msg, params)); // } // // public static void warn(Throwable t) { // logger.warning(t.getMessage()); // } // // public static void warn(Throwable t, String msg, Object... params) { // logger.warning(t.getMessage() + "\n" + String.format(msg, params)); // } // // public static void error(String msg, Object... params) { // logger.severe(String.format(msg, params)); // } // // public static void error(Throwable t) { // logger.severe(t.getMessage()); // } // // public static void error(Throwable t, String msg, Object... params) { // logger.severe(t.getMessage() + "\n" + String.format(msg, params)); // } // // public static void log(Level level, String msg) { // logger.log(level, msg); // } // // public static void main(String[] args) { // Logger.info("Test %d", 5); // } // } // // Path: src/fr/lri/tao/apro/util/Utils.java // public class Utils { // // private static final double EPSILON = 1E-14; // private static final double REALMIN100 = 100 * Double.MIN_NORMAL; // // // public static String toString(double[][] a) { // int maxLength = 12; // StringBuilder sb = new StringBuilder(); // for (int i=0; i<a.length; i++) { // for (int j=0; j<a[i].length; j++) { // String val = String.valueOf(a[i][j]); // maxLength = Math.max(maxLength, val.length()); // while (val.length() < maxLength) val = " " + val; // sb.append(val); // } // sb.append("\n"); // } // return sb.toString(); // } // // public static String toString(double[][] a, int decimals) { // if (decimals < 0) throw new IllegalArgumentException("Number of decimals must be positive"); // StringBuilder decs = new StringBuilder("0."); // for (int i = 0; i < decimals; i++) decs.append("0"); // NumberFormat decimalsFormat = new DecimalFormat(decs.toString()); // // StringBuilder sb = new StringBuilder(); // for (int i=0; i<a.length; i++) { // for (int j=0; j<a[i].length; j++) { // sb.append(decimalsFormat.format(a[i][j])).append(" "); // } // sb.append("\n"); // } // return sb.toString(); // } // // public static void addNoise(double[][] s) { // for (int i=0; i<s.length; i++) { // for (int j=0; j<s[i].length; j++) { // s[i][j] = s[i][j] + (EPSILON * s[i][j] + REALMIN100) * Math.random(); // } // } // } // // public static void addNoise(DoubleMatrix2D s) { // IntArrayList is = new IntArrayList(); // IntArrayList ks = new IntArrayList(); // DoubleArrayList vs = new DoubleArrayList(); // s.getNonZeros(is, ks, vs); // // for (int j=0; j<is.size(); j++) { // int i = is.get(j); // int k = ks.get(j); // double v = vs.get(j); // v = v + (EPSILON * v + REALMIN100) * Math.random(); // s.setQuick(i, k, v); // } // } // // } // Path: src/fr/lri/tao/apro/data/DSVProvider.java import cern.colt.matrix.DoubleMatrix2D; import cern.colt.matrix.impl.SparseDoubleMatrix2D; import fr.lri.tao.apro.util.Logger; import fr.lri.tao.apro.util.Utils; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; int simCount = 0; String line; BufferedReader reader = new BufferedReader(new FileReader(similarities)); while ((line = reader.readLine()) != null) { List<String> tokens = getTokens(line, delimiters); int i = Integer.parseInt(tokens.get(0)) - base; int j = Integer.parseInt(tokens.get(1)) - base; Double v = Double.parseDouble(tokens.get(2)); s.set(i, j, v); simCount++; } reader.close(); double full = 100d * (simCount + n) / (n * n); Logger.info("[Loader] Loaded %d similarities, matrix is %f%% populated", simCount, full); } @Override public DoubleMatrix2D getMatrix() { return s; } @Override public int size() { return n; } @Override public void addNoise() {
Utils.addNoise(s);
lovro-i/apro
src/fr/lri/tao/apro/hiap/DataParts.java
// Path: src/fr/lri/tao/apro/data/points/Points.java // public class Points extends ArrayList<Point> { // // private final Map<Long, Point> pointMap = new HashMap<Long, Point>(); // // @Override // public boolean add(Point point) { // this.pointMap.put(point.getId(), point); // return super.add(point); // } // // public Point getByIndex(int index) { // return this.get(index); // } // // public Point getById(long id) { // return pointMap.get(id); // } // // public int indexOf(Point point) { // long id = point.getId(); // for (int i = 0; i < this.size(); i++) { // if (this.get(i).getId() == id) return i; // } // return -1; // } // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append(size()).append(" points: "); // for (Point point: this) sb.append(" ").append(point); // return sb.toString(); // } // // public void shuffle() { // Random random = new Random(); // for (int i = 0; i < size(); i++) { // int j = random.nextInt(size()); // Point point1 = this.get(i); // Point point2 = this.get(j); // this.set(i, point2); // this.set(j, point1); // } // } // // // } // // Path: src/fr/lri/tao/apro/data/points/Point.java // public class Point { // // public final long id; // public final double[] features; // // /** Create a point with an ID and a list of numerical features */ // public Point(long id, double[] features) { // this.id = id; // this.features = features; // } // // public long getId() { // return id; // } // // /** Create a point with an ID and a collection of numerical features */ // public Point(long id, Collection<Double> features) { // this.id = id; // this.features = new double[features.size()]; // int i = 0; // for (Double d: features) { // this.features[i++] = d; // } // } // // /** Array of point features */ // public double[] getFeatures() { // return features; // } // // /** Euclidean distance between two points */ // public double distance(Point p) { // double s = 0; // for (int i=0; i<Math.min(features.length, p.features.length); i++) { // double d = features[i] - p.features[i]; // s += d * d; // } // return Math.sqrt(s); // } // // /** Default similarity between two points defined as negative squared distance */ // public double similarity(Point p) { // double s = 0; // int len = Math.min(features.length, p.features.length); // for (int i=0; i<len; i++) { // double d = features[i] - p.features[i]; // s += d * d; // } // return -s; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("Point ").append(id).append(" ("); // for (int i=0; i<features.length; i++) { // if (i > 0) sb.append(", "); // sb.append(features[i]); // } // sb.append(")"); // return sb.toString(); // } // // @Override // public boolean equals(Object o) { // Point p = (Point) o; // return p.id == this.id; // } // // @Override // public int hashCode() { // return (int) id; // } // // }
import fr.lri.tao.apro.data.points.Points; import fr.lri.tao.apro.data.points.Point; import java.util.ArrayList;
package fr.lri.tao.apro.hiap; /** Helper class for splitting the set of points into n subsets */ public class DataParts extends ArrayList<Points> { /** * @param points The integral set of points to be split * @param n Number of sets to split the set into */ public DataParts(Points points, int n) { final Points[] parts = new Points[n]; for (int i = 0; i < n; i++) { parts[i] = new Points(); this.add(parts[i]); } for (int i = 0; i < points.size(); i++) {
// Path: src/fr/lri/tao/apro/data/points/Points.java // public class Points extends ArrayList<Point> { // // private final Map<Long, Point> pointMap = new HashMap<Long, Point>(); // // @Override // public boolean add(Point point) { // this.pointMap.put(point.getId(), point); // return super.add(point); // } // // public Point getByIndex(int index) { // return this.get(index); // } // // public Point getById(long id) { // return pointMap.get(id); // } // // public int indexOf(Point point) { // long id = point.getId(); // for (int i = 0; i < this.size(); i++) { // if (this.get(i).getId() == id) return i; // } // return -1; // } // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append(size()).append(" points: "); // for (Point point: this) sb.append(" ").append(point); // return sb.toString(); // } // // public void shuffle() { // Random random = new Random(); // for (int i = 0; i < size(); i++) { // int j = random.nextInt(size()); // Point point1 = this.get(i); // Point point2 = this.get(j); // this.set(i, point2); // this.set(j, point1); // } // } // // // } // // Path: src/fr/lri/tao/apro/data/points/Point.java // public class Point { // // public final long id; // public final double[] features; // // /** Create a point with an ID and a list of numerical features */ // public Point(long id, double[] features) { // this.id = id; // this.features = features; // } // // public long getId() { // return id; // } // // /** Create a point with an ID and a collection of numerical features */ // public Point(long id, Collection<Double> features) { // this.id = id; // this.features = new double[features.size()]; // int i = 0; // for (Double d: features) { // this.features[i++] = d; // } // } // // /** Array of point features */ // public double[] getFeatures() { // return features; // } // // /** Euclidean distance between two points */ // public double distance(Point p) { // double s = 0; // for (int i=0; i<Math.min(features.length, p.features.length); i++) { // double d = features[i] - p.features[i]; // s += d * d; // } // return Math.sqrt(s); // } // // /** Default similarity between two points defined as negative squared distance */ // public double similarity(Point p) { // double s = 0; // int len = Math.min(features.length, p.features.length); // for (int i=0; i<len; i++) { // double d = features[i] - p.features[i]; // s += d * d; // } // return -s; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("Point ").append(id).append(" ("); // for (int i=0; i<features.length; i++) { // if (i > 0) sb.append(", "); // sb.append(features[i]); // } // sb.append(")"); // return sb.toString(); // } // // @Override // public boolean equals(Object o) { // Point p = (Point) o; // return p.id == this.id; // } // // @Override // public int hashCode() { // return (int) id; // } // // } // Path: src/fr/lri/tao/apro/hiap/DataParts.java import fr.lri.tao.apro.data.points.Points; import fr.lri.tao.apro.data.points.Point; import java.util.ArrayList; package fr.lri.tao.apro.hiap; /** Helper class for splitting the set of points into n subsets */ public class DataParts extends ArrayList<Points> { /** * @param points The integral set of points to be split * @param n Number of sets to split the set into */ public DataParts(Points points, int n) { final Points[] parts = new Points[n]; for (int i = 0; i < n; i++) { parts[i] = new Points(); this.add(parts[i]); } for (int i = 0; i < points.size(); i++) {
Point point = points.getByIndex(i);
TinyModularThings/TinyModularThings
src/speiger/src/api/common/recipes/squezingCompressor/parts/SqueezerRecipe.java
// Path: src/speiger/src/api/common/recipes/squezingCompressor/EnumRecipeType.java // public enum EnumRecipeType // { // Compressor, // Sqeezing, // Mixing; // } // // Path: src/speiger/src/api/common/recipes/util/RecipeHardness.java // public enum RecipeHardness // { // Extrem_Easy(0), // Very_Easy(1), // Easy(2), // Medium(3), // Hard(4), // Very_Hard(5), // Extrem_Hard(6), // Insane(7), // Nearly_Impossible(8); // // int id; // // private RecipeHardness(int par1) // { // id = par1; // } // // public int getComplexity() // { // return this.id; // } // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // }
import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType; import speiger.src.api.common.recipes.util.RecipeHardness; import speiger.src.api.common.recipes.util.Result;
package speiger.src.api.common.recipes.squezingCompressor.parts; public class SqueezerRecipe implements INormalRecipe { ItemStack recipeInput;
// Path: src/speiger/src/api/common/recipes/squezingCompressor/EnumRecipeType.java // public enum EnumRecipeType // { // Compressor, // Sqeezing, // Mixing; // } // // Path: src/speiger/src/api/common/recipes/util/RecipeHardness.java // public enum RecipeHardness // { // Extrem_Easy(0), // Very_Easy(1), // Easy(2), // Medium(3), // Hard(4), // Very_Hard(5), // Extrem_Hard(6), // Insane(7), // Nearly_Impossible(8); // // int id; // // private RecipeHardness(int par1) // { // id = par1; // } // // public int getComplexity() // { // return this.id; // } // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // } // Path: src/speiger/src/api/common/recipes/squezingCompressor/parts/SqueezerRecipe.java import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType; import speiger.src.api.common.recipes.util.RecipeHardness; import speiger.src.api.common.recipes.util.Result; package speiger.src.api.common.recipes.squezingCompressor.parts; public class SqueezerRecipe implements INormalRecipe { ItemStack recipeInput;
Result[] result;
TinyModularThings/TinyModularThings
src/speiger/src/api/common/recipes/squezingCompressor/parts/SqueezerRecipe.java
// Path: src/speiger/src/api/common/recipes/squezingCompressor/EnumRecipeType.java // public enum EnumRecipeType // { // Compressor, // Sqeezing, // Mixing; // } // // Path: src/speiger/src/api/common/recipes/util/RecipeHardness.java // public enum RecipeHardness // { // Extrem_Easy(0), // Very_Easy(1), // Easy(2), // Medium(3), // Hard(4), // Very_Hard(5), // Extrem_Hard(6), // Insane(7), // Nearly_Impossible(8); // // int id; // // private RecipeHardness(int par1) // { // id = par1; // } // // public int getComplexity() // { // return this.id; // } // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // }
import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType; import speiger.src.api.common.recipes.util.RecipeHardness; import speiger.src.api.common.recipes.util.Result;
@Override public ItemStack getItemInput() { return recipeInput; } @Override public FluidStack[] getFluidInput() { return null; } @Override public Result[] getResults() { return result; } @Override public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world) { if(recipeInput.isItemEqual(input) && input.stackSize >= recipeInput.stackSize) { return true; } return false; } @Override
// Path: src/speiger/src/api/common/recipes/squezingCompressor/EnumRecipeType.java // public enum EnumRecipeType // { // Compressor, // Sqeezing, // Mixing; // } // // Path: src/speiger/src/api/common/recipes/util/RecipeHardness.java // public enum RecipeHardness // { // Extrem_Easy(0), // Very_Easy(1), // Easy(2), // Medium(3), // Hard(4), // Very_Hard(5), // Extrem_Hard(6), // Insane(7), // Nearly_Impossible(8); // // int id; // // private RecipeHardness(int par1) // { // id = par1; // } // // public int getComplexity() // { // return this.id; // } // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // } // Path: src/speiger/src/api/common/recipes/squezingCompressor/parts/SqueezerRecipe.java import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType; import speiger.src.api.common.recipes.util.RecipeHardness; import speiger.src.api.common.recipes.util.Result; @Override public ItemStack getItemInput() { return recipeInput; } @Override public FluidStack[] getFluidInput() { return null; } @Override public Result[] getResults() { return result; } @Override public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world) { if(recipeInput.isItemEqual(input) && input.stackSize >= recipeInput.stackSize) { return true; } return false; } @Override
public EnumRecipeType getRecipeType()
TinyModularThings/TinyModularThings
src/speiger/src/api/common/recipes/squezingCompressor/parts/SqueezerRecipe.java
// Path: src/speiger/src/api/common/recipes/squezingCompressor/EnumRecipeType.java // public enum EnumRecipeType // { // Compressor, // Sqeezing, // Mixing; // } // // Path: src/speiger/src/api/common/recipes/util/RecipeHardness.java // public enum RecipeHardness // { // Extrem_Easy(0), // Very_Easy(1), // Easy(2), // Medium(3), // Hard(4), // Very_Hard(5), // Extrem_Hard(6), // Insane(7), // Nearly_Impossible(8); // // int id; // // private RecipeHardness(int par1) // { // id = par1; // } // // public int getComplexity() // { // return this.id; // } // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // }
import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType; import speiger.src.api.common.recipes.util.RecipeHardness; import speiger.src.api.common.recipes.util.Result;
@Override public Result[] getResults() { return result; } @Override public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world) { if(recipeInput.isItemEqual(input) && input.stackSize >= recipeInput.stackSize) { return true; } return false; } @Override public EnumRecipeType getRecipeType() { return EnumRecipeType.Sqeezing; } @Override public void runResult(ItemStack input, FluidTank first, FluidTank second, World world) { input.stackSize -= recipeInput.stackSize; } @Override
// Path: src/speiger/src/api/common/recipes/squezingCompressor/EnumRecipeType.java // public enum EnumRecipeType // { // Compressor, // Sqeezing, // Mixing; // } // // Path: src/speiger/src/api/common/recipes/util/RecipeHardness.java // public enum RecipeHardness // { // Extrem_Easy(0), // Very_Easy(1), // Easy(2), // Medium(3), // Hard(4), // Very_Hard(5), // Extrem_Hard(6), // Insane(7), // Nearly_Impossible(8); // // int id; // // private RecipeHardness(int par1) // { // id = par1; // } // // public int getComplexity() // { // return this.id; // } // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // } // Path: src/speiger/src/api/common/recipes/squezingCompressor/parts/SqueezerRecipe.java import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType; import speiger.src.api.common.recipes.util.RecipeHardness; import speiger.src.api.common.recipes.util.Result; @Override public Result[] getResults() { return result; } @Override public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world) { if(recipeInput.isItemEqual(input) && input.stackSize >= recipeInput.stackSize) { return true; } return false; } @Override public EnumRecipeType getRecipeType() { return EnumRecipeType.Sqeezing; } @Override public void runResult(ItemStack input, FluidTank first, FluidTank second, World world) { input.stackSize -= recipeInput.stackSize; } @Override
public RecipeHardness getComplexity()
TinyModularThings/TinyModularThings
src/speiger/src/api/common/recipes/squezingCompressor/parts/CompressorRecipe.java
// Path: src/speiger/src/api/common/recipes/squezingCompressor/EnumRecipeType.java // public enum EnumRecipeType // { // Compressor, // Sqeezing, // Mixing; // } // // Path: src/speiger/src/api/common/recipes/util/RecipeHardness.java // public enum RecipeHardness // { // Extrem_Easy(0), // Very_Easy(1), // Easy(2), // Medium(3), // Hard(4), // Very_Hard(5), // Extrem_Hard(6), // Insane(7), // Nearly_Impossible(8); // // int id; // // private RecipeHardness(int par1) // { // id = par1; // } // // public int getComplexity() // { // return this.id; // } // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // }
import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType; import speiger.src.api.common.recipes.util.RecipeHardness; import speiger.src.api.common.recipes.util.Result;
package speiger.src.api.common.recipes.squezingCompressor.parts; public class CompressorRecipe implements INormalRecipe {
// Path: src/speiger/src/api/common/recipes/squezingCompressor/EnumRecipeType.java // public enum EnumRecipeType // { // Compressor, // Sqeezing, // Mixing; // } // // Path: src/speiger/src/api/common/recipes/util/RecipeHardness.java // public enum RecipeHardness // { // Extrem_Easy(0), // Very_Easy(1), // Easy(2), // Medium(3), // Hard(4), // Very_Hard(5), // Extrem_Hard(6), // Insane(7), // Nearly_Impossible(8); // // int id; // // private RecipeHardness(int par1) // { // id = par1; // } // // public int getComplexity() // { // return this.id; // } // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // } // Path: src/speiger/src/api/common/recipes/squezingCompressor/parts/CompressorRecipe.java import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType; import speiger.src.api.common.recipes.util.RecipeHardness; import speiger.src.api.common.recipes.util.Result; package speiger.src.api.common.recipes.squezingCompressor.parts; public class CompressorRecipe implements INormalRecipe {
Result[] results;
TinyModularThings/TinyModularThings
src/speiger/src/api/common/recipes/squezingCompressor/parts/CompressorRecipe.java
// Path: src/speiger/src/api/common/recipes/squezingCompressor/EnumRecipeType.java // public enum EnumRecipeType // { // Compressor, // Sqeezing, // Mixing; // } // // Path: src/speiger/src/api/common/recipes/util/RecipeHardness.java // public enum RecipeHardness // { // Extrem_Easy(0), // Very_Easy(1), // Easy(2), // Medium(3), // Hard(4), // Very_Hard(5), // Extrem_Hard(6), // Insane(7), // Nearly_Impossible(8); // // int id; // // private RecipeHardness(int par1) // { // id = par1; // } // // public int getComplexity() // { // return this.id; // } // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // }
import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType; import speiger.src.api.common.recipes.util.RecipeHardness; import speiger.src.api.common.recipes.util.Result;
@Override public ItemStack getItemInput() { return recipeItem; } @Override public FluidStack[] getFluidInput() { return null; } @Override public Result[] getResults() { return results; } @Override public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world) { if(recipeItem.isItemEqual(input) && input.stackSize >= recipeItem.stackSize) { return true; } return false; } @Override
// Path: src/speiger/src/api/common/recipes/squezingCompressor/EnumRecipeType.java // public enum EnumRecipeType // { // Compressor, // Sqeezing, // Mixing; // } // // Path: src/speiger/src/api/common/recipes/util/RecipeHardness.java // public enum RecipeHardness // { // Extrem_Easy(0), // Very_Easy(1), // Easy(2), // Medium(3), // Hard(4), // Very_Hard(5), // Extrem_Hard(6), // Insane(7), // Nearly_Impossible(8); // // int id; // // private RecipeHardness(int par1) // { // id = par1; // } // // public int getComplexity() // { // return this.id; // } // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // } // Path: src/speiger/src/api/common/recipes/squezingCompressor/parts/CompressorRecipe.java import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType; import speiger.src.api.common.recipes.util.RecipeHardness; import speiger.src.api.common.recipes.util.Result; @Override public ItemStack getItemInput() { return recipeItem; } @Override public FluidStack[] getFluidInput() { return null; } @Override public Result[] getResults() { return results; } @Override public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world) { if(recipeItem.isItemEqual(input) && input.stackSize >= recipeItem.stackSize) { return true; } return false; } @Override
public EnumRecipeType getRecipeType()
TinyModularThings/TinyModularThings
src/speiger/src/api/common/recipes/squezingCompressor/parts/CompressorRecipe.java
// Path: src/speiger/src/api/common/recipes/squezingCompressor/EnumRecipeType.java // public enum EnumRecipeType // { // Compressor, // Sqeezing, // Mixing; // } // // Path: src/speiger/src/api/common/recipes/util/RecipeHardness.java // public enum RecipeHardness // { // Extrem_Easy(0), // Very_Easy(1), // Easy(2), // Medium(3), // Hard(4), // Very_Hard(5), // Extrem_Hard(6), // Insane(7), // Nearly_Impossible(8); // // int id; // // private RecipeHardness(int par1) // { // id = par1; // } // // public int getComplexity() // { // return this.id; // } // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // }
import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType; import speiger.src.api.common.recipes.util.RecipeHardness; import speiger.src.api.common.recipes.util.Result;
@Override public Result[] getResults() { return results; } @Override public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world) { if(recipeItem.isItemEqual(input) && input.stackSize >= recipeItem.stackSize) { return true; } return false; } @Override public EnumRecipeType getRecipeType() { return EnumRecipeType.Compressor; } @Override public void runResult(ItemStack input, FluidTank first, FluidTank second, World world) { input.stackSize -= recipeItem.stackSize; } @Override
// Path: src/speiger/src/api/common/recipes/squezingCompressor/EnumRecipeType.java // public enum EnumRecipeType // { // Compressor, // Sqeezing, // Mixing; // } // // Path: src/speiger/src/api/common/recipes/util/RecipeHardness.java // public enum RecipeHardness // { // Extrem_Easy(0), // Very_Easy(1), // Easy(2), // Medium(3), // Hard(4), // Very_Hard(5), // Extrem_Hard(6), // Insane(7), // Nearly_Impossible(8); // // int id; // // private RecipeHardness(int par1) // { // id = par1; // } // // public int getComplexity() // { // return this.id; // } // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // } // Path: src/speiger/src/api/common/recipes/squezingCompressor/parts/CompressorRecipe.java import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType; import speiger.src.api.common.recipes.util.RecipeHardness; import speiger.src.api.common.recipes.util.Result; @Override public Result[] getResults() { return results; } @Override public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world) { if(recipeItem.isItemEqual(input) && input.stackSize >= recipeItem.stackSize) { return true; } return false; } @Override public EnumRecipeType getRecipeType() { return EnumRecipeType.Compressor; } @Override public void runResult(ItemStack input, FluidTank first, FluidTank second, World world) { input.stackSize -= recipeItem.stackSize; } @Override
public RecipeHardness getComplexity()
TinyModularThings/TinyModularThings
src/speiger/src/api/common/data/nbt/INBTListener.java
// Path: src/speiger/src/api/common/core/SpmodMod.java // public interface SpmodMod // { // // /** // * @return Logging name // */ // public String getModName(); // // /** // * @return custom Logger // * @Default can be found in the registry // */ // public LogProxy getLogger(); // // }
import net.minecraft.nbt.NBTTagCompound; import speiger.src.api.common.core.SpmodMod;
package speiger.src.api.common.data.nbt; public interface INBTListener { public void readFromNBT(NBTTagCompound nbt); public void writeToNBT(NBTTagCompound nbt);
// Path: src/speiger/src/api/common/core/SpmodMod.java // public interface SpmodMod // { // // /** // * @return Logging name // */ // public String getModName(); // // /** // * @return custom Logger // * @Default can be found in the registry // */ // public LogProxy getLogger(); // // } // Path: src/speiger/src/api/common/data/nbt/INBTListener.java import net.minecraft.nbt.NBTTagCompound; import speiger.src.api.common.core.SpmodMod; package speiger.src.api.common.data.nbt; public interface INBTListener { public void readFromNBT(NBTTagCompound nbt); public void writeToNBT(NBTTagCompound nbt);
public SpmodMod getOwner();
TinyModularThings/TinyModularThings
src/speiger/src/api/client/gui/SpmodSlotLabel.java
// Path: src/speiger/src/api/common/inventory/IInfoSlot.java // public interface IInfoSlot // { // public List<String> getSlotInfo(); // // }
import java.util.List; import speiger.src.api.common.inventory.IInfoSlot;
package speiger.src.api.client.gui; public class SpmodSlotLabel extends SpmodLabel {
// Path: src/speiger/src/api/common/inventory/IInfoSlot.java // public interface IInfoSlot // { // public List<String> getSlotInfo(); // // } // Path: src/speiger/src/api/client/gui/SpmodSlotLabel.java import java.util.List; import speiger.src.api.common.inventory.IInfoSlot; package speiger.src.api.client.gui; public class SpmodSlotLabel extends SpmodLabel {
public IInfoSlot slot;
TinyModularThings/TinyModularThings
src/speiger/src/api/common/data/packets/ISpmodPacketHandler.java
// Path: src/speiger/src/api/common/data/packets/server/ISyncTile.java // public interface ISyncTile // { // // }
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import speiger.src.api.common.data.packets.server.ISyncTile;
package speiger.src.api.common.data.packets; public interface ISpmodPacketHandler { public void updateNetworkField(TileEntity tile, String field);
// Path: src/speiger/src/api/common/data/packets/server/ISyncTile.java // public interface ISyncTile // { // // } // Path: src/speiger/src/api/common/data/packets/ISpmodPacketHandler.java import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import speiger.src.api.common.data.packets.server.ISyncTile; package speiger.src.api.common.data.packets; public interface ISpmodPacketHandler { public void updateNetworkField(TileEntity tile, String field);
public void updateNetworkTile(ISyncTile par1);
TinyModularThings/TinyModularThings
src/speiger/src/api/common/data/nbt/NBTStorage.java
// Path: src/speiger/src/api/common/core/SpmodMod.java // public interface SpmodMod // { // // /** // * @return Logging name // */ // public String getModName(); // // /** // * @return custom Logger // * @Default can be found in the registry // */ // public LogProxy getLogger(); // // } // // Path: src/speiger/src/api/common/core/SpmodModRegistry.java // public class SpmodModRegistry // { // private static HashMap<String, SpmodMod> addons = new HashMap<String, SpmodMod>(); // private static LogProxy defaultProxy; // // static // { // SpmodMod baseMod = new SpmodMod(){ // @Override // public LogProxy getLogger() // { // return defaultProxy; // } // @Override // public String getModName() // { // return "Spmod Mod"; // } // }; // addons.put("Spmod Mod", baseMod); // defaultProxy = new LogProxy(baseMod); // } // // public static void registerMod(SpmodMod par1) // { // if (par1.getClass().isAnnotationPresent(Mod.class) && !Strings.isNullOrEmpty(par1.getModName())) // { // addons.put(par1.getModName(), par1); // } // else // { // FMLLog.getLogger().info(par1.getModName() + " Is not a valid SpmodMod, He will not registered"); // } // } // // public static boolean isAddonRegistered(SpmodMod par1) // { // if(par1 == null) // { // return false; // } // return isAddonRegistered(par1.getModName()); // } // // public static boolean isAddonRegistered(String par1) // { // return addons.containsKey(par1); // } // // public static boolean areAddonsEqual(SpmodMod par1, SpmodMod par2) // { // if(!isAddonRegistered(par1) || !isAddonRegistered(par2)) // { // return false; // } // return par1.getModName().equals(par2.getModName()); // } // // public static SpmodMod getModFromName(String par1) // { // return addons.get(par1); // } // // public static Collection<SpmodMod> getRegisteredMods() // { // return addons.values(); // } // // public static LogProxy getDefaultLogger(SpmodMod par1) // { // if(!isAddonRegistered(par1)) // { // return null; // } // return defaultProxy; // } // // public static void log(SpmodMod mod, String par2) // { // mod.getLogger().print(par2); // } // // public static void log(SpmodMod mod, Object par2) // { // mod.getLogger().print(par2); // } // } // // Path: src/speiger/src/api/common/data/nbt/INBTListener.java // public static enum LoadingState // { // Loading, // Loaded, // FailedLoading, // Saving, // RequestedSaving, // Saved, // FailedSaving, // Done; // }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.server.MinecraftServer; import speiger.src.api.common.core.SpmodMod; import speiger.src.api.common.core.SpmodModRegistry; import speiger.src.api.common.data.nbt.INBTListener.LoadingState; import cpw.mods.fml.common.FMLLog;
package speiger.src.api.common.data.nbt; public class NBTStorage {
// Path: src/speiger/src/api/common/core/SpmodMod.java // public interface SpmodMod // { // // /** // * @return Logging name // */ // public String getModName(); // // /** // * @return custom Logger // * @Default can be found in the registry // */ // public LogProxy getLogger(); // // } // // Path: src/speiger/src/api/common/core/SpmodModRegistry.java // public class SpmodModRegistry // { // private static HashMap<String, SpmodMod> addons = new HashMap<String, SpmodMod>(); // private static LogProxy defaultProxy; // // static // { // SpmodMod baseMod = new SpmodMod(){ // @Override // public LogProxy getLogger() // { // return defaultProxy; // } // @Override // public String getModName() // { // return "Spmod Mod"; // } // }; // addons.put("Spmod Mod", baseMod); // defaultProxy = new LogProxy(baseMod); // } // // public static void registerMod(SpmodMod par1) // { // if (par1.getClass().isAnnotationPresent(Mod.class) && !Strings.isNullOrEmpty(par1.getModName())) // { // addons.put(par1.getModName(), par1); // } // else // { // FMLLog.getLogger().info(par1.getModName() + " Is not a valid SpmodMod, He will not registered"); // } // } // // public static boolean isAddonRegistered(SpmodMod par1) // { // if(par1 == null) // { // return false; // } // return isAddonRegistered(par1.getModName()); // } // // public static boolean isAddonRegistered(String par1) // { // return addons.containsKey(par1); // } // // public static boolean areAddonsEqual(SpmodMod par1, SpmodMod par2) // { // if(!isAddonRegistered(par1) || !isAddonRegistered(par2)) // { // return false; // } // return par1.getModName().equals(par2.getModName()); // } // // public static SpmodMod getModFromName(String par1) // { // return addons.get(par1); // } // // public static Collection<SpmodMod> getRegisteredMods() // { // return addons.values(); // } // // public static LogProxy getDefaultLogger(SpmodMod par1) // { // if(!isAddonRegistered(par1)) // { // return null; // } // return defaultProxy; // } // // public static void log(SpmodMod mod, String par2) // { // mod.getLogger().print(par2); // } // // public static void log(SpmodMod mod, Object par2) // { // mod.getLogger().print(par2); // } // } // // Path: src/speiger/src/api/common/data/nbt/INBTListener.java // public static enum LoadingState // { // Loading, // Loaded, // FailedLoading, // Saving, // RequestedSaving, // Saved, // FailedSaving, // Done; // } // Path: src/speiger/src/api/common/data/nbt/NBTStorage.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.server.MinecraftServer; import speiger.src.api.common.core.SpmodMod; import speiger.src.api.common.core.SpmodModRegistry; import speiger.src.api.common.data.nbt.INBTListener.LoadingState; import cpw.mods.fml.common.FMLLog; package speiger.src.api.common.data.nbt; public class NBTStorage {
private static Map<SpmodMod, List<INBTListener>> listeners = new HashMap<SpmodMod, List<INBTListener>>();
TinyModularThings/TinyModularThings
src/speiger/src/api/common/data/nbt/NBTStorage.java
// Path: src/speiger/src/api/common/core/SpmodMod.java // public interface SpmodMod // { // // /** // * @return Logging name // */ // public String getModName(); // // /** // * @return custom Logger // * @Default can be found in the registry // */ // public LogProxy getLogger(); // // } // // Path: src/speiger/src/api/common/core/SpmodModRegistry.java // public class SpmodModRegistry // { // private static HashMap<String, SpmodMod> addons = new HashMap<String, SpmodMod>(); // private static LogProxy defaultProxy; // // static // { // SpmodMod baseMod = new SpmodMod(){ // @Override // public LogProxy getLogger() // { // return defaultProxy; // } // @Override // public String getModName() // { // return "Spmod Mod"; // } // }; // addons.put("Spmod Mod", baseMod); // defaultProxy = new LogProxy(baseMod); // } // // public static void registerMod(SpmodMod par1) // { // if (par1.getClass().isAnnotationPresent(Mod.class) && !Strings.isNullOrEmpty(par1.getModName())) // { // addons.put(par1.getModName(), par1); // } // else // { // FMLLog.getLogger().info(par1.getModName() + " Is not a valid SpmodMod, He will not registered"); // } // } // // public static boolean isAddonRegistered(SpmodMod par1) // { // if(par1 == null) // { // return false; // } // return isAddonRegistered(par1.getModName()); // } // // public static boolean isAddonRegistered(String par1) // { // return addons.containsKey(par1); // } // // public static boolean areAddonsEqual(SpmodMod par1, SpmodMod par2) // { // if(!isAddonRegistered(par1) || !isAddonRegistered(par2)) // { // return false; // } // return par1.getModName().equals(par2.getModName()); // } // // public static SpmodMod getModFromName(String par1) // { // return addons.get(par1); // } // // public static Collection<SpmodMod> getRegisteredMods() // { // return addons.values(); // } // // public static LogProxy getDefaultLogger(SpmodMod par1) // { // if(!isAddonRegistered(par1)) // { // return null; // } // return defaultProxy; // } // // public static void log(SpmodMod mod, String par2) // { // mod.getLogger().print(par2); // } // // public static void log(SpmodMod mod, Object par2) // { // mod.getLogger().print(par2); // } // } // // Path: src/speiger/src/api/common/data/nbt/INBTListener.java // public static enum LoadingState // { // Loading, // Loaded, // FailedLoading, // Saving, // RequestedSaving, // Saved, // FailedSaving, // Done; // }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.server.MinecraftServer; import speiger.src.api.common.core.SpmodMod; import speiger.src.api.common.core.SpmodModRegistry; import speiger.src.api.common.data.nbt.INBTListener.LoadingState; import cpw.mods.fml.common.FMLLog;
package speiger.src.api.common.data.nbt; public class NBTStorage { private static Map<SpmodMod, List<INBTListener>> listeners = new HashMap<SpmodMod, List<INBTListener>>(); private static List<SpmodMod> requestedUpdates = new LinkedList<SpmodMod>(); public static void registerNBTListener(INBTListener par1) {
// Path: src/speiger/src/api/common/core/SpmodMod.java // public interface SpmodMod // { // // /** // * @return Logging name // */ // public String getModName(); // // /** // * @return custom Logger // * @Default can be found in the registry // */ // public LogProxy getLogger(); // // } // // Path: src/speiger/src/api/common/core/SpmodModRegistry.java // public class SpmodModRegistry // { // private static HashMap<String, SpmodMod> addons = new HashMap<String, SpmodMod>(); // private static LogProxy defaultProxy; // // static // { // SpmodMod baseMod = new SpmodMod(){ // @Override // public LogProxy getLogger() // { // return defaultProxy; // } // @Override // public String getModName() // { // return "Spmod Mod"; // } // }; // addons.put("Spmod Mod", baseMod); // defaultProxy = new LogProxy(baseMod); // } // // public static void registerMod(SpmodMod par1) // { // if (par1.getClass().isAnnotationPresent(Mod.class) && !Strings.isNullOrEmpty(par1.getModName())) // { // addons.put(par1.getModName(), par1); // } // else // { // FMLLog.getLogger().info(par1.getModName() + " Is not a valid SpmodMod, He will not registered"); // } // } // // public static boolean isAddonRegistered(SpmodMod par1) // { // if(par1 == null) // { // return false; // } // return isAddonRegistered(par1.getModName()); // } // // public static boolean isAddonRegistered(String par1) // { // return addons.containsKey(par1); // } // // public static boolean areAddonsEqual(SpmodMod par1, SpmodMod par2) // { // if(!isAddonRegistered(par1) || !isAddonRegistered(par2)) // { // return false; // } // return par1.getModName().equals(par2.getModName()); // } // // public static SpmodMod getModFromName(String par1) // { // return addons.get(par1); // } // // public static Collection<SpmodMod> getRegisteredMods() // { // return addons.values(); // } // // public static LogProxy getDefaultLogger(SpmodMod par1) // { // if(!isAddonRegistered(par1)) // { // return null; // } // return defaultProxy; // } // // public static void log(SpmodMod mod, String par2) // { // mod.getLogger().print(par2); // } // // public static void log(SpmodMod mod, Object par2) // { // mod.getLogger().print(par2); // } // } // // Path: src/speiger/src/api/common/data/nbt/INBTListener.java // public static enum LoadingState // { // Loading, // Loaded, // FailedLoading, // Saving, // RequestedSaving, // Saved, // FailedSaving, // Done; // } // Path: src/speiger/src/api/common/data/nbt/NBTStorage.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.server.MinecraftServer; import speiger.src.api.common.core.SpmodMod; import speiger.src.api.common.core.SpmodModRegistry; import speiger.src.api.common.data.nbt.INBTListener.LoadingState; import cpw.mods.fml.common.FMLLog; package speiger.src.api.common.data.nbt; public class NBTStorage { private static Map<SpmodMod, List<INBTListener>> listeners = new HashMap<SpmodMod, List<INBTListener>>(); private static List<SpmodMod> requestedUpdates = new LinkedList<SpmodMod>(); public static void registerNBTListener(INBTListener par1) {
if(SpmodModRegistry.isAddonRegistered(par1.getOwner()))
TinyModularThings/TinyModularThings
src/speiger/src/api/common/utils/misc/SaveableList.java
// Path: src/speiger/src/api/common/utils/misc/saveHandlers/IDataSaver.java // public interface IDataSaver<T> // { // public void writeToNBT(List<T> par1, NBTTagCompound nbt); // // public List<T> readFromNBT(NBTTagCompound par1); // }
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import speiger.src.api.common.utils.misc.saveHandlers.IDataSaver;
package speiger.src.api.common.utils.misc; public class SaveableList<T> implements Iterable { List<T> dataList = new ArrayList<T>();
// Path: src/speiger/src/api/common/utils/misc/saveHandlers/IDataSaver.java // public interface IDataSaver<T> // { // public void writeToNBT(List<T> par1, NBTTagCompound nbt); // // public List<T> readFromNBT(NBTTagCompound par1); // } // Path: src/speiger/src/api/common/utils/misc/SaveableList.java import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import speiger.src.api.common.utils.misc.saveHandlers.IDataSaver; package speiger.src.api.common.utils.misc; public class SaveableList<T> implements Iterable { List<T> dataList = new ArrayList<T>();
IDataSaver dataSaver;
TinyModularThings/TinyModularThings
src/speiger/src/api/common/recipes/gas/GasRegistry.java
// Path: src/speiger/src/api/common/recipes/gas/IGasEntity.java // public static class GasInfo // { // int min; // int max; // // int result; // // public GasInfo(int par1, int par2) // { // min = par1; // max = par2; // if(max > 9) // { // max = 9; // } // if(min > 9) // { // min = 9; // } // } // // public int getMax() // { // return max; // } // // public int getMin() // { // return min; // } // // public int getResult() // { // return result; // } // // public GasInfo setResult(Random rand) // { // result = min + rand.nextInt(max + 1); // if(result > 10) // { // result = 10; // } // return this; // } // }
import java.util.ArrayList; import java.util.List; import net.minecraft.entity.EntityAgeable; import speiger.src.api.common.recipes.gas.IGasEntity.GasInfo;
package speiger.src.api.common.recipes.gas; public class GasRegistry { private static List<IGasEntity> list = new ArrayList<IGasEntity>(); public static void registerGasHandler(IGasEntity par1) { list.add(par1); }
// Path: src/speiger/src/api/common/recipes/gas/IGasEntity.java // public static class GasInfo // { // int min; // int max; // // int result; // // public GasInfo(int par1, int par2) // { // min = par1; // max = par2; // if(max > 9) // { // max = 9; // } // if(min > 9) // { // min = 9; // } // } // // public int getMax() // { // return max; // } // // public int getMin() // { // return min; // } // // public int getResult() // { // return result; // } // // public GasInfo setResult(Random rand) // { // result = min + rand.nextInt(max + 1); // if(result > 10) // { // result = 10; // } // return this; // } // } // Path: src/speiger/src/api/common/recipes/gas/GasRegistry.java import java.util.ArrayList; import java.util.List; import net.minecraft.entity.EntityAgeable; import speiger.src.api.common.recipes.gas.IGasEntity.GasInfo; package speiger.src.api.common.recipes.gas; public class GasRegistry { private static List<IGasEntity> list = new ArrayList<IGasEntity>(); public static void registerGasHandler(IGasEntity par1) { list.add(par1); }
public static GasInfo getGasInfo(EntityAgeable par1)
TinyModularThings/TinyModularThings
src/speiger/src/api/common/utils/misc/SaveableMap.java
// Path: src/speiger/src/api/common/utils/misc/saveHandlers/IDataSaver.java // public interface IDataSaver<T> // { // public void writeToNBT(List<T> par1, NBTTagCompound nbt); // // public List<T> readFromNBT(NBTTagCompound par1); // }
import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import net.minecraft.nbt.NBTTagCompound; import speiger.src.api.common.utils.misc.saveHandlers.IDataSaver;
package speiger.src.api.common.utils.misc; public class SaveableMap<K, V> implements Iterable { Map<K, V> data = new HashMap<K, V>();
// Path: src/speiger/src/api/common/utils/misc/saveHandlers/IDataSaver.java // public interface IDataSaver<T> // { // public void writeToNBT(List<T> par1, NBTTagCompound nbt); // // public List<T> readFromNBT(NBTTagCompound par1); // } // Path: src/speiger/src/api/common/utils/misc/SaveableMap.java import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import net.minecraft.nbt.NBTTagCompound; import speiger.src.api.common.utils.misc.saveHandlers.IDataSaver; package speiger.src.api.common.utils.misc; public class SaveableMap<K, V> implements Iterable { Map<K, V> data = new HashMap<K, V>();
IDataSaver keySave;
TinyModularThings/TinyModularThings
src/speiger/src/api/common/data/packets/SpmodPacketHandlerDummy.java
// Path: src/speiger/src/api/common/data/packets/server/INetworkTile.java // public interface INetworkTile extends ISyncTile // { // public List<String> getNetworkFields(); // } // // Path: src/speiger/src/api/common/data/packets/server/ISyncTile.java // public interface ISyncTile // { // // }
import speiger.src.api.common.data.packets.server.INetworkTile; import speiger.src.api.common.data.packets.server.ISyncTile; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity;
package speiger.src.api.common.data.packets; public class SpmodPacketHandlerDummy implements ISpmodPacketHandler { @Override public void updateNetworkField(TileEntity tile, String field) { } @Override
// Path: src/speiger/src/api/common/data/packets/server/INetworkTile.java // public interface INetworkTile extends ISyncTile // { // public List<String> getNetworkFields(); // } // // Path: src/speiger/src/api/common/data/packets/server/ISyncTile.java // public interface ISyncTile // { // // } // Path: src/speiger/src/api/common/data/packets/SpmodPacketHandlerDummy.java import speiger.src.api.common.data.packets.server.INetworkTile; import speiger.src.api.common.data.packets.server.ISyncTile; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; package speiger.src.api.common.data.packets; public class SpmodPacketHandlerDummy implements ISpmodPacketHandler { @Override public void updateNetworkField(TileEntity tile, String field) { } @Override
public void updateNetworkTile(ISyncTile par1)
TinyModularThings/TinyModularThings
src/speiger/src/api/common/recipes/mobmachine/MobRegistry.java
// Path: src/speiger/src/api/common/recipes/mobmachine/MobEntry.java // public static class FoodInfo // { // ItemStack item; // int foodAmount; // // public FoodInfo(Block par1, int par2) // { // this(new ItemStack(par1), par2); // } // // public FoodInfo(Item par1, int par2) // { // this(new ItemStack(par1), par2); // } // // public FoodInfo(ItemStack par1, int par2) // { // item = par1; // foodAmount = par2; // } // // public ItemStack getItem() // { // return item; // } // // public int getFoodAmount() // { // return foodAmount; // } // }
import java.util.List; import java.util.Map; import net.minecraft.item.ItemStack; import speiger.src.api.common.recipes.mobmachine.MobEntry.FoodInfo;
package speiger.src.api.common.recipes.mobmachine; public class MobRegistry { public static IMobRegistry registry; public static interface IMobRegistry { //256 IDs is the Limit for now public boolean registerMobEntry(MobEntry entry); public MobEntry getEntryForID(int id); public Map<Integer, MobEntry> getEntries(); public boolean registerActivationItem(int id, ItemStack item); public List<ItemStack> getActivationItem(int id); public Map<Integer, List<ItemStack>> getActivationItems(); public void registerMobFoodModifier(IMobFoodModifier mob); } public static interface IMobFoodModifier { /** * This is for NotEnoughItems so please return here all values you support for that mob is requested. */
// Path: src/speiger/src/api/common/recipes/mobmachine/MobEntry.java // public static class FoodInfo // { // ItemStack item; // int foodAmount; // // public FoodInfo(Block par1, int par2) // { // this(new ItemStack(par1), par2); // } // // public FoodInfo(Item par1, int par2) // { // this(new ItemStack(par1), par2); // } // // public FoodInfo(ItemStack par1, int par2) // { // item = par1; // foodAmount = par2; // } // // public ItemStack getItem() // { // return item; // } // // public int getFoodAmount() // { // return foodAmount; // } // } // Path: src/speiger/src/api/common/recipes/mobmachine/MobRegistry.java import java.util.List; import java.util.Map; import net.minecraft.item.ItemStack; import speiger.src.api.common.recipes.mobmachine.MobEntry.FoodInfo; package speiger.src.api.common.recipes.mobmachine; public class MobRegistry { public static IMobRegistry registry; public static interface IMobRegistry { //256 IDs is the Limit for now public boolean registerMobEntry(MobEntry entry); public MobEntry getEntryForID(int id); public Map<Integer, MobEntry> getEntries(); public boolean registerActivationItem(int id, ItemStack item); public List<ItemStack> getActivationItem(int id); public Map<Integer, List<ItemStack>> getActivationItems(); public void registerMobFoodModifier(IMobFoodModifier mob); } public static interface IMobFoodModifier { /** * This is for NotEnoughItems so please return here all values you support for that mob is requested. */
public List<FoodInfo> getFoodInfoForMob(MobEntry entry);
TinyModularThings/TinyModularThings
src/speiger/src/api/common/recipes/squezingCompressor/MachineRecipeMaker.java
// Path: src/speiger/src/api/common/recipes/squezingCompressor/parts/INormalRecipe.java // public interface INormalRecipe // { // public ItemStack getItemInput(); // // public FluidStack[] getFluidInput(); // // public Result[] getResults(); // // public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world); // // public EnumRecipeType getRecipeType(); // // public void runResult(ItemStack input, FluidTank first, FluidTank second, World world); // // public RecipeHardness getComplexity(); // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // }
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.parts.INormalRecipe; import speiger.src.api.common.recipes.util.Result;
package speiger.src.api.common.recipes.squezingCompressor; public class MachineRecipeMaker { public static MachineRecipeMaker INSTANCE = new MachineRecipeMaker();
// Path: src/speiger/src/api/common/recipes/squezingCompressor/parts/INormalRecipe.java // public interface INormalRecipe // { // public ItemStack getItemInput(); // // public FluidStack[] getFluidInput(); // // public Result[] getResults(); // // public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world); // // public EnumRecipeType getRecipeType(); // // public void runResult(ItemStack input, FluidTank first, FluidTank second, World world); // // public RecipeHardness getComplexity(); // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // } // Path: src/speiger/src/api/common/recipes/squezingCompressor/MachineRecipeMaker.java import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.parts.INormalRecipe; import speiger.src.api.common.recipes.util.Result; package speiger.src.api.common.recipes.squezingCompressor; public class MachineRecipeMaker { public static MachineRecipeMaker INSTANCE = new MachineRecipeMaker();
public List<INormalRecipe> compressorRecipe = new ArrayList<INormalRecipe>();
TinyModularThings/TinyModularThings
src/speiger/src/api/common/recipes/squezingCompressor/MachineRecipeMaker.java
// Path: src/speiger/src/api/common/recipes/squezingCompressor/parts/INormalRecipe.java // public interface INormalRecipe // { // public ItemStack getItemInput(); // // public FluidStack[] getFluidInput(); // // public Result[] getResults(); // // public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world); // // public EnumRecipeType getRecipeType(); // // public void runResult(ItemStack input, FluidTank first, FluidTank second, World world); // // public RecipeHardness getComplexity(); // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // }
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.parts.INormalRecipe; import speiger.src.api.common.recipes.util.Result;
{ if(item == null) { return new ArrayList<INormalRecipe>(); } List<INormalRecipe> list = new ArrayList<INormalRecipe>(); for(EnumRecipeType type : EnumRecipeType.values()) { list.addAll(getRecipeFromItem(type, item, false)); } return list; } public List<INormalRecipe> getRecipeFromItem(EnumRecipeType type, ItemStack item, boolean input) { if(item == null) { return new ArrayList<INormalRecipe>(); } List<INormalRecipe> list = new ArrayList<INormalRecipe>(); if(getRecipeListFromType(type) != null) { for(INormalRecipe recipe : getRecipeListFromType(type)) { ItemStack stack = recipe.getItemInput(); if(input && stack != null && stack.isItemEqual(item)) { list.add(recipe); continue; }
// Path: src/speiger/src/api/common/recipes/squezingCompressor/parts/INormalRecipe.java // public interface INormalRecipe // { // public ItemStack getItemInput(); // // public FluidStack[] getFluidInput(); // // public Result[] getResults(); // // public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world); // // public EnumRecipeType getRecipeType(); // // public void runResult(ItemStack input, FluidTank first, FluidTank second, World world); // // public RecipeHardness getComplexity(); // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // } // Path: src/speiger/src/api/common/recipes/squezingCompressor/MachineRecipeMaker.java import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.parts.INormalRecipe; import speiger.src.api.common.recipes.util.Result; { if(item == null) { return new ArrayList<INormalRecipe>(); } List<INormalRecipe> list = new ArrayList<INormalRecipe>(); for(EnumRecipeType type : EnumRecipeType.values()) { list.addAll(getRecipeFromItem(type, item, false)); } return list; } public List<INormalRecipe> getRecipeFromItem(EnumRecipeType type, ItemStack item, boolean input) { if(item == null) { return new ArrayList<INormalRecipe>(); } List<INormalRecipe> list = new ArrayList<INormalRecipe>(); if(getRecipeListFromType(type) != null) { for(INormalRecipe recipe : getRecipeListFromType(type)) { ItemStack stack = recipe.getItemInput(); if(input && stack != null && stack.isItemEqual(item)) { list.add(recipe); continue; }
Result[] results = recipe.getResults();
TinyModularThings/TinyModularThings
src/speiger/src/api/common/plugins/PluginManager.java
// Path: src/speiger/src/api/common/core/SpmodMod.java // public interface SpmodMod // { // // /** // * @return Logging name // */ // public String getModName(); // // /** // * @return custom Logger // * @Default can be found in the registry // */ // public LogProxy getLogger(); // // } // // Path: src/speiger/src/api/common/utils/misc/DataMap.java // public class DataMap<T> // { // Map<String, T> data = new HashMap<String, T>(); // // public void addData(String par1, T par2) // { // data.put(par1, par2); // } // // public T getData(String par1) // { // return data.get(par1); // } // // public boolean containsData(String par1) // { // return data.containsKey(par1); // } // // public Set<Entry<String, T>> entrySet() // { // return data.entrySet(); // } // // public void remove(String par1) // { // data.remove(par1); // } // // public void clear() // { // data.clear(); // } // }
import cpw.mods.fml.common.FMLLog; import speiger.src.api.common.core.SpmodMod; import speiger.src.api.common.utils.misc.DataMap;
package speiger.src.api.common.plugins; public class PluginManager {
// Path: src/speiger/src/api/common/core/SpmodMod.java // public interface SpmodMod // { // // /** // * @return Logging name // */ // public String getModName(); // // /** // * @return custom Logger // * @Default can be found in the registry // */ // public LogProxy getLogger(); // // } // // Path: src/speiger/src/api/common/utils/misc/DataMap.java // public class DataMap<T> // { // Map<String, T> data = new HashMap<String, T>(); // // public void addData(String par1, T par2) // { // data.put(par1, par2); // } // // public T getData(String par1) // { // return data.get(par1); // } // // public boolean containsData(String par1) // { // return data.containsKey(par1); // } // // public Set<Entry<String, T>> entrySet() // { // return data.entrySet(); // } // // public void remove(String par1) // { // data.remove(par1); // } // // public void clear() // { // data.clear(); // } // } // Path: src/speiger/src/api/common/plugins/PluginManager.java import cpw.mods.fml.common.FMLLog; import speiger.src.api.common.core.SpmodMod; import speiger.src.api.common.utils.misc.DataMap; package speiger.src.api.common.plugins; public class PluginManager {
private static DataMap<IPluginLoader> pluginLoaders = new DataMap<IPluginLoader>();
TinyModularThings/TinyModularThings
src/speiger/src/api/common/plugins/PluginManager.java
// Path: src/speiger/src/api/common/core/SpmodMod.java // public interface SpmodMod // { // // /** // * @return Logging name // */ // public String getModName(); // // /** // * @return custom Logger // * @Default can be found in the registry // */ // public LogProxy getLogger(); // // } // // Path: src/speiger/src/api/common/utils/misc/DataMap.java // public class DataMap<T> // { // Map<String, T> data = new HashMap<String, T>(); // // public void addData(String par1, T par2) // { // data.put(par1, par2); // } // // public T getData(String par1) // { // return data.get(par1); // } // // public boolean containsData(String par1) // { // return data.containsKey(par1); // } // // public Set<Entry<String, T>> entrySet() // { // return data.entrySet(); // } // // public void remove(String par1) // { // data.remove(par1); // } // // public void clear() // { // data.clear(); // } // }
import cpw.mods.fml.common.FMLLog; import speiger.src.api.common.core.SpmodMod; import speiger.src.api.common.utils.misc.DataMap;
package speiger.src.api.common.plugins; public class PluginManager { private static DataMap<IPluginLoader> pluginLoaders = new DataMap<IPluginLoader>(); /** * @param path is the Path where he should search for * @param name is the ID * @param mod is the Modowner. (Simply for logging) * @return the Created Plugin */
// Path: src/speiger/src/api/common/core/SpmodMod.java // public interface SpmodMod // { // // /** // * @return Logging name // */ // public String getModName(); // // /** // * @return custom Logger // * @Default can be found in the registry // */ // public LogProxy getLogger(); // // } // // Path: src/speiger/src/api/common/utils/misc/DataMap.java // public class DataMap<T> // { // Map<String, T> data = new HashMap<String, T>(); // // public void addData(String par1, T par2) // { // data.put(par1, par2); // } // // public T getData(String par1) // { // return data.get(par1); // } // // public boolean containsData(String par1) // { // return data.containsKey(par1); // } // // public Set<Entry<String, T>> entrySet() // { // return data.entrySet(); // } // // public void remove(String par1) // { // data.remove(par1); // } // // public void clear() // { // data.clear(); // } // } // Path: src/speiger/src/api/common/plugins/PluginManager.java import cpw.mods.fml.common.FMLLog; import speiger.src.api.common.core.SpmodMod; import speiger.src.api.common.utils.misc.DataMap; package speiger.src.api.common.plugins; public class PluginManager { private static DataMap<IPluginLoader> pluginLoaders = new DataMap<IPluginLoader>(); /** * @param path is the Path where he should search for * @param name is the ID * @param mod is the Modowner. (Simply for logging) * @return the Created Plugin */
public static IPluginLoader createPluginLoader(String path, String name, SpmodMod mod)
TinyModularThings/TinyModularThings
src/speiger/src/api/common/recipes/squezingCompressor/parts/INormalRecipe.java
// Path: src/speiger/src/api/common/recipes/squezingCompressor/EnumRecipeType.java // public enum EnumRecipeType // { // Compressor, // Sqeezing, // Mixing; // } // // Path: src/speiger/src/api/common/recipes/util/RecipeHardness.java // public enum RecipeHardness // { // Extrem_Easy(0), // Very_Easy(1), // Easy(2), // Medium(3), // Hard(4), // Very_Hard(5), // Extrem_Hard(6), // Insane(7), // Nearly_Impossible(8); // // int id; // // private RecipeHardness(int par1) // { // id = par1; // } // // public int getComplexity() // { // return this.id; // } // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // }
import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType; import speiger.src.api.common.recipes.util.RecipeHardness; import speiger.src.api.common.recipes.util.Result;
package speiger.src.api.common.recipes.squezingCompressor.parts; public interface INormalRecipe { public ItemStack getItemInput(); public FluidStack[] getFluidInput();
// Path: src/speiger/src/api/common/recipes/squezingCompressor/EnumRecipeType.java // public enum EnumRecipeType // { // Compressor, // Sqeezing, // Mixing; // } // // Path: src/speiger/src/api/common/recipes/util/RecipeHardness.java // public enum RecipeHardness // { // Extrem_Easy(0), // Very_Easy(1), // Easy(2), // Medium(3), // Hard(4), // Very_Hard(5), // Extrem_Hard(6), // Insane(7), // Nearly_Impossible(8); // // int id; // // private RecipeHardness(int par1) // { // id = par1; // } // // public int getComplexity() // { // return this.id; // } // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // } // Path: src/speiger/src/api/common/recipes/squezingCompressor/parts/INormalRecipe.java import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType; import speiger.src.api.common.recipes.util.RecipeHardness; import speiger.src.api.common.recipes.util.Result; package speiger.src.api.common.recipes.squezingCompressor.parts; public interface INormalRecipe { public ItemStack getItemInput(); public FluidStack[] getFluidInput();
public Result[] getResults();
TinyModularThings/TinyModularThings
src/speiger/src/api/common/recipes/squezingCompressor/parts/INormalRecipe.java
// Path: src/speiger/src/api/common/recipes/squezingCompressor/EnumRecipeType.java // public enum EnumRecipeType // { // Compressor, // Sqeezing, // Mixing; // } // // Path: src/speiger/src/api/common/recipes/util/RecipeHardness.java // public enum RecipeHardness // { // Extrem_Easy(0), // Very_Easy(1), // Easy(2), // Medium(3), // Hard(4), // Very_Hard(5), // Extrem_Hard(6), // Insane(7), // Nearly_Impossible(8); // // int id; // // private RecipeHardness(int par1) // { // id = par1; // } // // public int getComplexity() // { // return this.id; // } // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // }
import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType; import speiger.src.api.common.recipes.util.RecipeHardness; import speiger.src.api.common.recipes.util.Result;
package speiger.src.api.common.recipes.squezingCompressor.parts; public interface INormalRecipe { public ItemStack getItemInput(); public FluidStack[] getFluidInput(); public Result[] getResults(); public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world);
// Path: src/speiger/src/api/common/recipes/squezingCompressor/EnumRecipeType.java // public enum EnumRecipeType // { // Compressor, // Sqeezing, // Mixing; // } // // Path: src/speiger/src/api/common/recipes/util/RecipeHardness.java // public enum RecipeHardness // { // Extrem_Easy(0), // Very_Easy(1), // Easy(2), // Medium(3), // Hard(4), // Very_Hard(5), // Extrem_Hard(6), // Insane(7), // Nearly_Impossible(8); // // int id; // // private RecipeHardness(int par1) // { // id = par1; // } // // public int getComplexity() // { // return this.id; // } // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // } // Path: src/speiger/src/api/common/recipes/squezingCompressor/parts/INormalRecipe.java import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType; import speiger.src.api.common.recipes.util.RecipeHardness; import speiger.src.api.common.recipes.util.Result; package speiger.src.api.common.recipes.squezingCompressor.parts; public interface INormalRecipe { public ItemStack getItemInput(); public FluidStack[] getFluidInput(); public Result[] getResults(); public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world);
public EnumRecipeType getRecipeType();
TinyModularThings/TinyModularThings
src/speiger/src/api/common/recipes/squezingCompressor/parts/INormalRecipe.java
// Path: src/speiger/src/api/common/recipes/squezingCompressor/EnumRecipeType.java // public enum EnumRecipeType // { // Compressor, // Sqeezing, // Mixing; // } // // Path: src/speiger/src/api/common/recipes/util/RecipeHardness.java // public enum RecipeHardness // { // Extrem_Easy(0), // Very_Easy(1), // Easy(2), // Medium(3), // Hard(4), // Very_Hard(5), // Extrem_Hard(6), // Insane(7), // Nearly_Impossible(8); // // int id; // // private RecipeHardness(int par1) // { // id = par1; // } // // public int getComplexity() // { // return this.id; // } // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // }
import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType; import speiger.src.api.common.recipes.util.RecipeHardness; import speiger.src.api.common.recipes.util.Result;
package speiger.src.api.common.recipes.squezingCompressor.parts; public interface INormalRecipe { public ItemStack getItemInput(); public FluidStack[] getFluidInput(); public Result[] getResults(); public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world); public EnumRecipeType getRecipeType(); public void runResult(ItemStack input, FluidTank first, FluidTank second, World world);
// Path: src/speiger/src/api/common/recipes/squezingCompressor/EnumRecipeType.java // public enum EnumRecipeType // { // Compressor, // Sqeezing, // Mixing; // } // // Path: src/speiger/src/api/common/recipes/util/RecipeHardness.java // public enum RecipeHardness // { // Extrem_Easy(0), // Very_Easy(1), // Easy(2), // Medium(3), // Hard(4), // Very_Hard(5), // Extrem_Hard(6), // Insane(7), // Nearly_Impossible(8); // // int id; // // private RecipeHardness(int par1) // { // id = par1; // } // // public int getComplexity() // { // return this.id; // } // } // // Path: src/speiger/src/api/common/recipes/util/Result.java // public interface Result // { // public boolean hasItemResult(); // // public ItemStack getItemResult(); // // public int getItemResultChance(); // // public boolean hasFluidResult(); // // public FluidStack getFluidResult(); // // public int getFluidResultChance(); // // } // Path: src/speiger/src/api/common/recipes/squezingCompressor/parts/INormalRecipe.java import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType; import speiger.src.api.common.recipes.util.RecipeHardness; import speiger.src.api.common.recipes.util.Result; package speiger.src.api.common.recipes.squezingCompressor.parts; public interface INormalRecipe { public ItemStack getItemInput(); public FluidStack[] getFluidInput(); public Result[] getResults(); public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world); public EnumRecipeType getRecipeType(); public void runResult(ItemStack input, FluidTank first, FluidTank second, World world);
public RecipeHardness getComplexity();
TinyModularThings/TinyModularThings
src/speiger/src/api/client/gui/BaseGui.java
// Path: src/speiger/src/api/common/inventory/IInfoSlot.java // public interface IInfoSlot // { // public List<String> getSlotInfo(); // // } // // Path: src/speiger/src/api/common/inventory/IUpdateInfoSlot.java // public interface IUpdateInfoSlot extends IInfoSlot // { // // }
import java.util.ArrayList; import java.util.List; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import speiger.src.api.common.inventory.IInfoSlot; import speiger.src.api.common.inventory.IUpdateInfoSlot;
package speiger.src.api.client.gui; public abstract class BaseGui extends GuiContainer { public static final ResourceLocation BLOCK_TEXTURE = TextureMap.locationBlocksTexture; public List<IGuiLabel> label = new ArrayList<IGuiLabel>(); public BaseGui(Container par1) { super(par1); } public void drawHoverText(List text, int x, int y) { this.drawHoveringText(text, x, y, fontRendererObj); } @Override public void initGui() { super.initGui(); int k = (this.width - this.xSize) / 2; int l = (this.height - this.ySize) / 2; this.label.clear(); List slots = this.inventorySlots.inventorySlots; for(int i = 0;i < slots.size();i++) { Slot slot = (Slot)slots.get(i);
// Path: src/speiger/src/api/common/inventory/IInfoSlot.java // public interface IInfoSlot // { // public List<String> getSlotInfo(); // // } // // Path: src/speiger/src/api/common/inventory/IUpdateInfoSlot.java // public interface IUpdateInfoSlot extends IInfoSlot // { // // } // Path: src/speiger/src/api/client/gui/BaseGui.java import java.util.ArrayList; import java.util.List; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import speiger.src.api.common.inventory.IInfoSlot; import speiger.src.api.common.inventory.IUpdateInfoSlot; package speiger.src.api.client.gui; public abstract class BaseGui extends GuiContainer { public static final ResourceLocation BLOCK_TEXTURE = TextureMap.locationBlocksTexture; public List<IGuiLabel> label = new ArrayList<IGuiLabel>(); public BaseGui(Container par1) { super(par1); } public void drawHoverText(List text, int x, int y) { this.drawHoveringText(text, x, y, fontRendererObj); } @Override public void initGui() { super.initGui(); int k = (this.width - this.xSize) / 2; int l = (this.height - this.ySize) / 2; this.label.clear(); List slots = this.inventorySlots.inventorySlots; for(int i = 0;i < slots.size();i++) { Slot slot = (Slot)slots.get(i);
if(slot instanceof IInfoSlot)
TinyModularThings/TinyModularThings
src/speiger/src/api/client/gui/BaseGui.java
// Path: src/speiger/src/api/common/inventory/IInfoSlot.java // public interface IInfoSlot // { // public List<String> getSlotInfo(); // // } // // Path: src/speiger/src/api/common/inventory/IUpdateInfoSlot.java // public interface IUpdateInfoSlot extends IInfoSlot // { // // }
import java.util.ArrayList; import java.util.List; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import speiger.src.api.common.inventory.IInfoSlot; import speiger.src.api.common.inventory.IUpdateInfoSlot;
package speiger.src.api.client.gui; public abstract class BaseGui extends GuiContainer { public static final ResourceLocation BLOCK_TEXTURE = TextureMap.locationBlocksTexture; public List<IGuiLabel> label = new ArrayList<IGuiLabel>(); public BaseGui(Container par1) { super(par1); } public void drawHoverText(List text, int x, int y) { this.drawHoveringText(text, x, y, fontRendererObj); } @Override public void initGui() { super.initGui(); int k = (this.width - this.xSize) / 2; int l = (this.height - this.ySize) / 2; this.label.clear(); List slots = this.inventorySlots.inventorySlots; for(int i = 0;i < slots.size();i++) { Slot slot = (Slot)slots.get(i); if(slot instanceof IInfoSlot) {
// Path: src/speiger/src/api/common/inventory/IInfoSlot.java // public interface IInfoSlot // { // public List<String> getSlotInfo(); // // } // // Path: src/speiger/src/api/common/inventory/IUpdateInfoSlot.java // public interface IUpdateInfoSlot extends IInfoSlot // { // // } // Path: src/speiger/src/api/client/gui/BaseGui.java import java.util.ArrayList; import java.util.List; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import speiger.src.api.common.inventory.IInfoSlot; import speiger.src.api.common.inventory.IUpdateInfoSlot; package speiger.src.api.client.gui; public abstract class BaseGui extends GuiContainer { public static final ResourceLocation BLOCK_TEXTURE = TextureMap.locationBlocksTexture; public List<IGuiLabel> label = new ArrayList<IGuiLabel>(); public BaseGui(Container par1) { super(par1); } public void drawHoverText(List text, int x, int y) { this.drawHoveringText(text, x, y, fontRendererObj); } @Override public void initGui() { super.initGui(); int k = (this.width - this.xSize) / 2; int l = (this.height - this.ySize) / 2; this.label.clear(); List slots = this.inventorySlots.inventorySlots; for(int i = 0;i < slots.size();i++) { Slot slot = (Slot)slots.get(i); if(slot instanceof IInfoSlot) {
if(slot instanceof IUpdateInfoSlot)
Adobe-Marketing-Cloud-Apps/aem-mobile-hybrid-reference
aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/impl/AccountManagerImpl.java
// Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AccountManager.java // @Component // @Service // public interface AccountManager { // /** // * Creates a new user profile in the repository. // * @param userName user's login name // * @param password user's passward // * @param givenName user's first name // * @param lastName user's last name // * @param email user's email // * @param avatarParam user's avatar upload parameter. This parameter may be null. // * @return the newly created profile resource, null if failed to create one. // */ // Resource createUser(String userName, String password, String givenName, String lastName, String email, RequestParameter avatarParam); // void changePassword(String newPassword, ResourceResolver resourceResolver); // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/ProfileConstants.java // public class ProfileConstants { // // public static final String PARAM_AVATAR = "avatar"; // public static final String PARAM_EMAIL = "email"; // public static final String PARAM_FAMILY_NAME = "familyName"; // public static final String PARAM_GIVEN_NAME = "givenName"; // public static final String PARAM_PASSWORD = "password"; // public static final String PARAM_USER_PROFILE_PATH = "profilePath"; // // public static final String PROP_EMAIL = "email"; // public static final String PROP_FAMILY_NAME = "familyName"; // public static final String PROP_GIVEN_NAME = "givenName"; // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AvatarManager.java // @Component // @Service // public interface AvatarManager { // // /** // * Updates an existing avatar or creates a new one. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void saveAvatar(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // // /** // * Creates the folder structure and stores avatar for a profile without a avatar. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void createAvatarWithDirectories(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // }
import com.adobe.ionicapp.profile.services.AccountManager; import com.adobe.ionicapp.profile.ProfileConstants; import com.adobe.ionicapp.profile.services.AvatarManager; import com.day.cq.commons.jcr.JcrConstants; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.jackrabbit.api.security.user.User; import org.apache.jackrabbit.api.security.user.UserManager; import org.apache.sling.api.request.RequestParameter; import org.apache.sling.api.resource.LoginException; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceResolverFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jcr.RepositoryException; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.HashMap; import java.util.Map;
package com.adobe.ionicapp.profile.services.impl; @Component(metatype = false, immediate = true) @Service(AccountManager.class) public class AccountManagerImpl implements AccountManager { private static final Logger LOG = LoggerFactory.getLogger(AccountManagerImpl.class); private static final String IONIC_APP_PROFILE_SERVICE_USER = "ionic-app-profile-service"; private static final String PROFILE_RESOURCE_NAME = "profile"; private static final String PROFILE_RESOURCE_TYPE = "cq/security/components/profile"; private static final String SLING_RESOURCE_TYPE = "sling:resourceType"; @Reference
// Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AccountManager.java // @Component // @Service // public interface AccountManager { // /** // * Creates a new user profile in the repository. // * @param userName user's login name // * @param password user's passward // * @param givenName user's first name // * @param lastName user's last name // * @param email user's email // * @param avatarParam user's avatar upload parameter. This parameter may be null. // * @return the newly created profile resource, null if failed to create one. // */ // Resource createUser(String userName, String password, String givenName, String lastName, String email, RequestParameter avatarParam); // void changePassword(String newPassword, ResourceResolver resourceResolver); // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/ProfileConstants.java // public class ProfileConstants { // // public static final String PARAM_AVATAR = "avatar"; // public static final String PARAM_EMAIL = "email"; // public static final String PARAM_FAMILY_NAME = "familyName"; // public static final String PARAM_GIVEN_NAME = "givenName"; // public static final String PARAM_PASSWORD = "password"; // public static final String PARAM_USER_PROFILE_PATH = "profilePath"; // // public static final String PROP_EMAIL = "email"; // public static final String PROP_FAMILY_NAME = "familyName"; // public static final String PROP_GIVEN_NAME = "givenName"; // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AvatarManager.java // @Component // @Service // public interface AvatarManager { // // /** // * Updates an existing avatar or creates a new one. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void saveAvatar(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // // /** // * Creates the folder structure and stores avatar for a profile without a avatar. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void createAvatarWithDirectories(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // } // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/impl/AccountManagerImpl.java import com.adobe.ionicapp.profile.services.AccountManager; import com.adobe.ionicapp.profile.ProfileConstants; import com.adobe.ionicapp.profile.services.AvatarManager; import com.day.cq.commons.jcr.JcrConstants; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.jackrabbit.api.security.user.User; import org.apache.jackrabbit.api.security.user.UserManager; import org.apache.sling.api.request.RequestParameter; import org.apache.sling.api.resource.LoginException; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceResolverFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jcr.RepositoryException; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.HashMap; import java.util.Map; package com.adobe.ionicapp.profile.services.impl; @Component(metatype = false, immediate = true) @Service(AccountManager.class) public class AccountManagerImpl implements AccountManager { private static final Logger LOG = LoggerFactory.getLogger(AccountManagerImpl.class); private static final String IONIC_APP_PROFILE_SERVICE_USER = "ionic-app-profile-service"; private static final String PROFILE_RESOURCE_NAME = "profile"; private static final String PROFILE_RESOURCE_TYPE = "cq/security/components/profile"; private static final String SLING_RESOURCE_TYPE = "sling:resourceType"; @Reference
AvatarManager avatarManager;
Adobe-Marketing-Cloud-Apps/aem-mobile-hybrid-reference
aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/impl/AccountManagerImpl.java
// Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AccountManager.java // @Component // @Service // public interface AccountManager { // /** // * Creates a new user profile in the repository. // * @param userName user's login name // * @param password user's passward // * @param givenName user's first name // * @param lastName user's last name // * @param email user's email // * @param avatarParam user's avatar upload parameter. This parameter may be null. // * @return the newly created profile resource, null if failed to create one. // */ // Resource createUser(String userName, String password, String givenName, String lastName, String email, RequestParameter avatarParam); // void changePassword(String newPassword, ResourceResolver resourceResolver); // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/ProfileConstants.java // public class ProfileConstants { // // public static final String PARAM_AVATAR = "avatar"; // public static final String PARAM_EMAIL = "email"; // public static final String PARAM_FAMILY_NAME = "familyName"; // public static final String PARAM_GIVEN_NAME = "givenName"; // public static final String PARAM_PASSWORD = "password"; // public static final String PARAM_USER_PROFILE_PATH = "profilePath"; // // public static final String PROP_EMAIL = "email"; // public static final String PROP_FAMILY_NAME = "familyName"; // public static final String PROP_GIVEN_NAME = "givenName"; // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AvatarManager.java // @Component // @Service // public interface AvatarManager { // // /** // * Updates an existing avatar or creates a new one. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void saveAvatar(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // // /** // * Creates the folder structure and stores avatar for a profile without a avatar. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void createAvatarWithDirectories(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // }
import com.adobe.ionicapp.profile.services.AccountManager; import com.adobe.ionicapp.profile.ProfileConstants; import com.adobe.ionicapp.profile.services.AvatarManager; import com.day.cq.commons.jcr.JcrConstants; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.jackrabbit.api.security.user.User; import org.apache.jackrabbit.api.security.user.UserManager; import org.apache.sling.api.request.RequestParameter; import org.apache.sling.api.resource.LoginException; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceResolverFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jcr.RepositoryException; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.HashMap; import java.util.Map;
package com.adobe.ionicapp.profile.services.impl; @Component(metatype = false, immediate = true) @Service(AccountManager.class) public class AccountManagerImpl implements AccountManager { private static final Logger LOG = LoggerFactory.getLogger(AccountManagerImpl.class); private static final String IONIC_APP_PROFILE_SERVICE_USER = "ionic-app-profile-service"; private static final String PROFILE_RESOURCE_NAME = "profile"; private static final String PROFILE_RESOURCE_TYPE = "cq/security/components/profile"; private static final String SLING_RESOURCE_TYPE = "sling:resourceType"; @Reference AvatarManager avatarManager; @Reference private ResourceResolverFactory resourceResolverFactory; public Resource createUser(final String userName, final String password, final String givenName, final String lastName, final String email, final RequestParameter avatarParam) { LOG.debug("Creating new account for user {}", userName); final Map<String, Object> authInfo = new HashMap<String, Object>(); authInfo.put(ResourceResolverFactory.SUBSERVICE, IONIC_APP_PROFILE_SERVICE_USER); ResourceResolver resourceResolver = null; try { // create a new resource for the user resourceResolver = resourceResolverFactory.getServiceResourceResolver(authInfo); final UserManager userManager = resourceResolver.adaptTo(UserManager.class); final User user = userManager.createUser(userName, password); String path = user.getPath(); // Apply user data to the resource Map<String, Object> map = new HashMap<String, Object>();
// Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AccountManager.java // @Component // @Service // public interface AccountManager { // /** // * Creates a new user profile in the repository. // * @param userName user's login name // * @param password user's passward // * @param givenName user's first name // * @param lastName user's last name // * @param email user's email // * @param avatarParam user's avatar upload parameter. This parameter may be null. // * @return the newly created profile resource, null if failed to create one. // */ // Resource createUser(String userName, String password, String givenName, String lastName, String email, RequestParameter avatarParam); // void changePassword(String newPassword, ResourceResolver resourceResolver); // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/ProfileConstants.java // public class ProfileConstants { // // public static final String PARAM_AVATAR = "avatar"; // public static final String PARAM_EMAIL = "email"; // public static final String PARAM_FAMILY_NAME = "familyName"; // public static final String PARAM_GIVEN_NAME = "givenName"; // public static final String PARAM_PASSWORD = "password"; // public static final String PARAM_USER_PROFILE_PATH = "profilePath"; // // public static final String PROP_EMAIL = "email"; // public static final String PROP_FAMILY_NAME = "familyName"; // public static final String PROP_GIVEN_NAME = "givenName"; // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AvatarManager.java // @Component // @Service // public interface AvatarManager { // // /** // * Updates an existing avatar or creates a new one. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void saveAvatar(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // // /** // * Creates the folder structure and stores avatar for a profile without a avatar. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void createAvatarWithDirectories(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // } // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/impl/AccountManagerImpl.java import com.adobe.ionicapp.profile.services.AccountManager; import com.adobe.ionicapp.profile.ProfileConstants; import com.adobe.ionicapp.profile.services.AvatarManager; import com.day.cq.commons.jcr.JcrConstants; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.jackrabbit.api.security.user.User; import org.apache.jackrabbit.api.security.user.UserManager; import org.apache.sling.api.request.RequestParameter; import org.apache.sling.api.resource.LoginException; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceResolverFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jcr.RepositoryException; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.HashMap; import java.util.Map; package com.adobe.ionicapp.profile.services.impl; @Component(metatype = false, immediate = true) @Service(AccountManager.class) public class AccountManagerImpl implements AccountManager { private static final Logger LOG = LoggerFactory.getLogger(AccountManagerImpl.class); private static final String IONIC_APP_PROFILE_SERVICE_USER = "ionic-app-profile-service"; private static final String PROFILE_RESOURCE_NAME = "profile"; private static final String PROFILE_RESOURCE_TYPE = "cq/security/components/profile"; private static final String SLING_RESOURCE_TYPE = "sling:resourceType"; @Reference AvatarManager avatarManager; @Reference private ResourceResolverFactory resourceResolverFactory; public Resource createUser(final String userName, final String password, final String givenName, final String lastName, final String email, final RequestParameter avatarParam) { LOG.debug("Creating new account for user {}", userName); final Map<String, Object> authInfo = new HashMap<String, Object>(); authInfo.put(ResourceResolverFactory.SUBSERVICE, IONIC_APP_PROFILE_SERVICE_USER); ResourceResolver resourceResolver = null; try { // create a new resource for the user resourceResolver = resourceResolverFactory.getServiceResourceResolver(authInfo); final UserManager userManager = resourceResolver.adaptTo(UserManager.class); final User user = userManager.createUser(userName, password); String path = user.getPath(); // Apply user data to the resource Map<String, Object> map = new HashMap<String, Object>();
map.put(ProfileConstants.PROP_GIVEN_NAME, givenName);
Adobe-Marketing-Cloud-Apps/aem-mobile-hybrid-reference
aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/servlets/UpdateProfileServlet.java
// Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/ProfileConstants.java // public class ProfileConstants { // // public static final String PARAM_AVATAR = "avatar"; // public static final String PARAM_EMAIL = "email"; // public static final String PARAM_FAMILY_NAME = "familyName"; // public static final String PARAM_GIVEN_NAME = "givenName"; // public static final String PARAM_PASSWORD = "password"; // public static final String PARAM_USER_PROFILE_PATH = "profilePath"; // // public static final String PROP_EMAIL = "email"; // public static final String PROP_FAMILY_NAME = "familyName"; // public static final String PROP_GIVEN_NAME = "givenName"; // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AccountManager.java // @Component // @Service // public interface AccountManager { // /** // * Creates a new user profile in the repository. // * @param userName user's login name // * @param password user's passward // * @param givenName user's first name // * @param lastName user's last name // * @param email user's email // * @param avatarParam user's avatar upload parameter. This parameter may be null. // * @return the newly created profile resource, null if failed to create one. // */ // Resource createUser(String userName, String password, String givenName, String lastName, String email, RequestParameter avatarParam); // void changePassword(String newPassword, ResourceResolver resourceResolver); // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AvatarManager.java // @Component // @Service // public interface AvatarManager { // // /** // * Updates an existing avatar or creates a new one. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void saveAvatar(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // // /** // * Creates the folder structure and stores avatar for a profile without a avatar. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void createAvatarWithDirectories(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // }
import com.adobe.ionicapp.profile.ProfileConstants; import com.adobe.ionicapp.profile.services.AccountManager; import com.adobe.ionicapp.profile.services.AvatarManager; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.request.RequestParameter; import org.apache.sling.api.resource.ModifiableValueMap; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Servlet; import java.io.*;
package com.adobe.ionicapp.profile.servlets; @Component(immediate = true, metatype = true) @Service(Servlet.class) @Properties({ @Property(name = "sling.servlet.resourceTypes", value = "sling/servlet/default"), @Property(name = "sling.servlet.methods", value = "POST"), @Property(name = "sling.servlet.selectors", value = "ionicapp.profile"), @Property(name = "sling.servlet.extensions", value = "html") }) public class UpdateProfileServlet extends SlingAllMethodsServlet { private static final Logger LOG = LoggerFactory.getLogger(UpdateProfileServlet.class); @Reference
// Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/ProfileConstants.java // public class ProfileConstants { // // public static final String PARAM_AVATAR = "avatar"; // public static final String PARAM_EMAIL = "email"; // public static final String PARAM_FAMILY_NAME = "familyName"; // public static final String PARAM_GIVEN_NAME = "givenName"; // public static final String PARAM_PASSWORD = "password"; // public static final String PARAM_USER_PROFILE_PATH = "profilePath"; // // public static final String PROP_EMAIL = "email"; // public static final String PROP_FAMILY_NAME = "familyName"; // public static final String PROP_GIVEN_NAME = "givenName"; // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AccountManager.java // @Component // @Service // public interface AccountManager { // /** // * Creates a new user profile in the repository. // * @param userName user's login name // * @param password user's passward // * @param givenName user's first name // * @param lastName user's last name // * @param email user's email // * @param avatarParam user's avatar upload parameter. This parameter may be null. // * @return the newly created profile resource, null if failed to create one. // */ // Resource createUser(String userName, String password, String givenName, String lastName, String email, RequestParameter avatarParam); // void changePassword(String newPassword, ResourceResolver resourceResolver); // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AvatarManager.java // @Component // @Service // public interface AvatarManager { // // /** // * Updates an existing avatar or creates a new one. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void saveAvatar(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // // /** // * Creates the folder structure and stores avatar for a profile without a avatar. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void createAvatarWithDirectories(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // } // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/servlets/UpdateProfileServlet.java import com.adobe.ionicapp.profile.ProfileConstants; import com.adobe.ionicapp.profile.services.AccountManager; import com.adobe.ionicapp.profile.services.AvatarManager; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.request.RequestParameter; import org.apache.sling.api.resource.ModifiableValueMap; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Servlet; import java.io.*; package com.adobe.ionicapp.profile.servlets; @Component(immediate = true, metatype = true) @Service(Servlet.class) @Properties({ @Property(name = "sling.servlet.resourceTypes", value = "sling/servlet/default"), @Property(name = "sling.servlet.methods", value = "POST"), @Property(name = "sling.servlet.selectors", value = "ionicapp.profile"), @Property(name = "sling.servlet.extensions", value = "html") }) public class UpdateProfileServlet extends SlingAllMethodsServlet { private static final Logger LOG = LoggerFactory.getLogger(UpdateProfileServlet.class); @Reference
AccountManager accountManager;
Adobe-Marketing-Cloud-Apps/aem-mobile-hybrid-reference
aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/servlets/UpdateProfileServlet.java
// Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/ProfileConstants.java // public class ProfileConstants { // // public static final String PARAM_AVATAR = "avatar"; // public static final String PARAM_EMAIL = "email"; // public static final String PARAM_FAMILY_NAME = "familyName"; // public static final String PARAM_GIVEN_NAME = "givenName"; // public static final String PARAM_PASSWORD = "password"; // public static final String PARAM_USER_PROFILE_PATH = "profilePath"; // // public static final String PROP_EMAIL = "email"; // public static final String PROP_FAMILY_NAME = "familyName"; // public static final String PROP_GIVEN_NAME = "givenName"; // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AccountManager.java // @Component // @Service // public interface AccountManager { // /** // * Creates a new user profile in the repository. // * @param userName user's login name // * @param password user's passward // * @param givenName user's first name // * @param lastName user's last name // * @param email user's email // * @param avatarParam user's avatar upload parameter. This parameter may be null. // * @return the newly created profile resource, null if failed to create one. // */ // Resource createUser(String userName, String password, String givenName, String lastName, String email, RequestParameter avatarParam); // void changePassword(String newPassword, ResourceResolver resourceResolver); // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AvatarManager.java // @Component // @Service // public interface AvatarManager { // // /** // * Updates an existing avatar or creates a new one. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void saveAvatar(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // // /** // * Creates the folder structure and stores avatar for a profile without a avatar. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void createAvatarWithDirectories(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // }
import com.adobe.ionicapp.profile.ProfileConstants; import com.adobe.ionicapp.profile.services.AccountManager; import com.adobe.ionicapp.profile.services.AvatarManager; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.request.RequestParameter; import org.apache.sling.api.resource.ModifiableValueMap; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Servlet; import java.io.*;
package com.adobe.ionicapp.profile.servlets; @Component(immediate = true, metatype = true) @Service(Servlet.class) @Properties({ @Property(name = "sling.servlet.resourceTypes", value = "sling/servlet/default"), @Property(name = "sling.servlet.methods", value = "POST"), @Property(name = "sling.servlet.selectors", value = "ionicapp.profile"), @Property(name = "sling.servlet.extensions", value = "html") }) public class UpdateProfileServlet extends SlingAllMethodsServlet { private static final Logger LOG = LoggerFactory.getLogger(UpdateProfileServlet.class); @Reference AccountManager accountManager; @Reference
// Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/ProfileConstants.java // public class ProfileConstants { // // public static final String PARAM_AVATAR = "avatar"; // public static final String PARAM_EMAIL = "email"; // public static final String PARAM_FAMILY_NAME = "familyName"; // public static final String PARAM_GIVEN_NAME = "givenName"; // public static final String PARAM_PASSWORD = "password"; // public static final String PARAM_USER_PROFILE_PATH = "profilePath"; // // public static final String PROP_EMAIL = "email"; // public static final String PROP_FAMILY_NAME = "familyName"; // public static final String PROP_GIVEN_NAME = "givenName"; // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AccountManager.java // @Component // @Service // public interface AccountManager { // /** // * Creates a new user profile in the repository. // * @param userName user's login name // * @param password user's passward // * @param givenName user's first name // * @param lastName user's last name // * @param email user's email // * @param avatarParam user's avatar upload parameter. This parameter may be null. // * @return the newly created profile resource, null if failed to create one. // */ // Resource createUser(String userName, String password, String givenName, String lastName, String email, RequestParameter avatarParam); // void changePassword(String newPassword, ResourceResolver resourceResolver); // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AvatarManager.java // @Component // @Service // public interface AvatarManager { // // /** // * Updates an existing avatar or creates a new one. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void saveAvatar(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // // /** // * Creates the folder structure and stores avatar for a profile without a avatar. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void createAvatarWithDirectories(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // } // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/servlets/UpdateProfileServlet.java import com.adobe.ionicapp.profile.ProfileConstants; import com.adobe.ionicapp.profile.services.AccountManager; import com.adobe.ionicapp.profile.services.AvatarManager; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.request.RequestParameter; import org.apache.sling.api.resource.ModifiableValueMap; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Servlet; import java.io.*; package com.adobe.ionicapp.profile.servlets; @Component(immediate = true, metatype = true) @Service(Servlet.class) @Properties({ @Property(name = "sling.servlet.resourceTypes", value = "sling/servlet/default"), @Property(name = "sling.servlet.methods", value = "POST"), @Property(name = "sling.servlet.selectors", value = "ionicapp.profile"), @Property(name = "sling.servlet.extensions", value = "html") }) public class UpdateProfileServlet extends SlingAllMethodsServlet { private static final Logger LOG = LoggerFactory.getLogger(UpdateProfileServlet.class); @Reference AccountManager accountManager; @Reference
AvatarManager avatarManager;
Adobe-Marketing-Cloud-Apps/aem-mobile-hybrid-reference
aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/servlets/UpdateProfileServlet.java
// Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/ProfileConstants.java // public class ProfileConstants { // // public static final String PARAM_AVATAR = "avatar"; // public static final String PARAM_EMAIL = "email"; // public static final String PARAM_FAMILY_NAME = "familyName"; // public static final String PARAM_GIVEN_NAME = "givenName"; // public static final String PARAM_PASSWORD = "password"; // public static final String PARAM_USER_PROFILE_PATH = "profilePath"; // // public static final String PROP_EMAIL = "email"; // public static final String PROP_FAMILY_NAME = "familyName"; // public static final String PROP_GIVEN_NAME = "givenName"; // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AccountManager.java // @Component // @Service // public interface AccountManager { // /** // * Creates a new user profile in the repository. // * @param userName user's login name // * @param password user's passward // * @param givenName user's first name // * @param lastName user's last name // * @param email user's email // * @param avatarParam user's avatar upload parameter. This parameter may be null. // * @return the newly created profile resource, null if failed to create one. // */ // Resource createUser(String userName, String password, String givenName, String lastName, String email, RequestParameter avatarParam); // void changePassword(String newPassword, ResourceResolver resourceResolver); // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AvatarManager.java // @Component // @Service // public interface AvatarManager { // // /** // * Updates an existing avatar or creates a new one. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void saveAvatar(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // // /** // * Creates the folder structure and stores avatar for a profile without a avatar. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void createAvatarWithDirectories(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // }
import com.adobe.ionicapp.profile.ProfileConstants; import com.adobe.ionicapp.profile.services.AccountManager; import com.adobe.ionicapp.profile.services.AvatarManager; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.request.RequestParameter; import org.apache.sling.api.resource.ModifiableValueMap; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Servlet; import java.io.*;
package com.adobe.ionicapp.profile.servlets; @Component(immediate = true, metatype = true) @Service(Servlet.class) @Properties({ @Property(name = "sling.servlet.resourceTypes", value = "sling/servlet/default"), @Property(name = "sling.servlet.methods", value = "POST"), @Property(name = "sling.servlet.selectors", value = "ionicapp.profile"), @Property(name = "sling.servlet.extensions", value = "html") }) public class UpdateProfileServlet extends SlingAllMethodsServlet { private static final Logger LOG = LoggerFactory.getLogger(UpdateProfileServlet.class); @Reference AccountManager accountManager; @Reference AvatarManager avatarManager; @Override public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) { final ResourceResolver resourceResolver = request.getResource().getResourceResolver();
// Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/ProfileConstants.java // public class ProfileConstants { // // public static final String PARAM_AVATAR = "avatar"; // public static final String PARAM_EMAIL = "email"; // public static final String PARAM_FAMILY_NAME = "familyName"; // public static final String PARAM_GIVEN_NAME = "givenName"; // public static final String PARAM_PASSWORD = "password"; // public static final String PARAM_USER_PROFILE_PATH = "profilePath"; // // public static final String PROP_EMAIL = "email"; // public static final String PROP_FAMILY_NAME = "familyName"; // public static final String PROP_GIVEN_NAME = "givenName"; // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AccountManager.java // @Component // @Service // public interface AccountManager { // /** // * Creates a new user profile in the repository. // * @param userName user's login name // * @param password user's passward // * @param givenName user's first name // * @param lastName user's last name // * @param email user's email // * @param avatarParam user's avatar upload parameter. This parameter may be null. // * @return the newly created profile resource, null if failed to create one. // */ // Resource createUser(String userName, String password, String givenName, String lastName, String email, RequestParameter avatarParam); // void changePassword(String newPassword, ResourceResolver resourceResolver); // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AvatarManager.java // @Component // @Service // public interface AvatarManager { // // /** // * Updates an existing avatar or creates a new one. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void saveAvatar(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // // /** // * Creates the folder structure and stores avatar for a profile without a avatar. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void createAvatarWithDirectories(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // } // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/servlets/UpdateProfileServlet.java import com.adobe.ionicapp.profile.ProfileConstants; import com.adobe.ionicapp.profile.services.AccountManager; import com.adobe.ionicapp.profile.services.AvatarManager; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.request.RequestParameter; import org.apache.sling.api.resource.ModifiableValueMap; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Servlet; import java.io.*; package com.adobe.ionicapp.profile.servlets; @Component(immediate = true, metatype = true) @Service(Servlet.class) @Properties({ @Property(name = "sling.servlet.resourceTypes", value = "sling/servlet/default"), @Property(name = "sling.servlet.methods", value = "POST"), @Property(name = "sling.servlet.selectors", value = "ionicapp.profile"), @Property(name = "sling.servlet.extensions", value = "html") }) public class UpdateProfileServlet extends SlingAllMethodsServlet { private static final Logger LOG = LoggerFactory.getLogger(UpdateProfileServlet.class); @Reference AccountManager accountManager; @Reference AvatarManager avatarManager; @Override public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) { final ResourceResolver resourceResolver = request.getResource().getResourceResolver();
final String profilePath = request.getParameter(ProfileConstants.PARAM_USER_PROFILE_PATH);
Adobe-Marketing-Cloud-Apps/aem-mobile-hybrid-reference
aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/servlets/CreateProfileServlet.java
// Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/ProfileConstants.java // public class ProfileConstants { // // public static final String PARAM_AVATAR = "avatar"; // public static final String PARAM_EMAIL = "email"; // public static final String PARAM_FAMILY_NAME = "familyName"; // public static final String PARAM_GIVEN_NAME = "givenName"; // public static final String PARAM_PASSWORD = "password"; // public static final String PARAM_USER_PROFILE_PATH = "profilePath"; // // public static final String PROP_EMAIL = "email"; // public static final String PROP_FAMILY_NAME = "familyName"; // public static final String PROP_GIVEN_NAME = "givenName"; // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AccountManager.java // @Component // @Service // public interface AccountManager { // /** // * Creates a new user profile in the repository. // * @param userName user's login name // * @param password user's passward // * @param givenName user's first name // * @param lastName user's last name // * @param email user's email // * @param avatarParam user's avatar upload parameter. This parameter may be null. // * @return the newly created profile resource, null if failed to create one. // */ // Resource createUser(String userName, String password, String givenName, String lastName, String email, RequestParameter avatarParam); // void changePassword(String newPassword, ResourceResolver resourceResolver); // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AvatarManager.java // @Component // @Service // public interface AvatarManager { // // /** // * Updates an existing avatar or creates a new one. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void saveAvatar(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // // /** // * Creates the folder structure and stores avatar for a profile without a avatar. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void createAvatarWithDirectories(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // }
import com.adobe.ionicapp.profile.ProfileConstants; import com.adobe.ionicapp.profile.services.AccountManager; import com.adobe.ionicapp.profile.services.AvatarManager; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.request.RequestParameter; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Servlet;
package com.adobe.ionicapp.profile.servlets; @Component(immediate = true, metatype = true) @Service(Servlet.class) @Properties({ @Property(name = "sling.servlet.resourceTypes", value = "sling/servlet/default"), @Property(name = "sling.servlet.methods", value = "POST"), @Property(name = "sling.servlet.selectors", value = "ionicapp.create"), @Property(name = "sling.servlet.extensions", value = "html") }) public class CreateProfileServlet extends SlingAllMethodsServlet { private static final Logger LOG = LoggerFactory.getLogger(CreateProfileServlet.class); @Reference
// Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/ProfileConstants.java // public class ProfileConstants { // // public static final String PARAM_AVATAR = "avatar"; // public static final String PARAM_EMAIL = "email"; // public static final String PARAM_FAMILY_NAME = "familyName"; // public static final String PARAM_GIVEN_NAME = "givenName"; // public static final String PARAM_PASSWORD = "password"; // public static final String PARAM_USER_PROFILE_PATH = "profilePath"; // // public static final String PROP_EMAIL = "email"; // public static final String PROP_FAMILY_NAME = "familyName"; // public static final String PROP_GIVEN_NAME = "givenName"; // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AccountManager.java // @Component // @Service // public interface AccountManager { // /** // * Creates a new user profile in the repository. // * @param userName user's login name // * @param password user's passward // * @param givenName user's first name // * @param lastName user's last name // * @param email user's email // * @param avatarParam user's avatar upload parameter. This parameter may be null. // * @return the newly created profile resource, null if failed to create one. // */ // Resource createUser(String userName, String password, String givenName, String lastName, String email, RequestParameter avatarParam); // void changePassword(String newPassword, ResourceResolver resourceResolver); // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AvatarManager.java // @Component // @Service // public interface AvatarManager { // // /** // * Updates an existing avatar or creates a new one. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void saveAvatar(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // // /** // * Creates the folder structure and stores avatar for a profile without a avatar. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void createAvatarWithDirectories(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // } // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/servlets/CreateProfileServlet.java import com.adobe.ionicapp.profile.ProfileConstants; import com.adobe.ionicapp.profile.services.AccountManager; import com.adobe.ionicapp.profile.services.AvatarManager; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.request.RequestParameter; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Servlet; package com.adobe.ionicapp.profile.servlets; @Component(immediate = true, metatype = true) @Service(Servlet.class) @Properties({ @Property(name = "sling.servlet.resourceTypes", value = "sling/servlet/default"), @Property(name = "sling.servlet.methods", value = "POST"), @Property(name = "sling.servlet.selectors", value = "ionicapp.create"), @Property(name = "sling.servlet.extensions", value = "html") }) public class CreateProfileServlet extends SlingAllMethodsServlet { private static final Logger LOG = LoggerFactory.getLogger(CreateProfileServlet.class); @Reference
AccountManager accountManager;
Adobe-Marketing-Cloud-Apps/aem-mobile-hybrid-reference
aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/servlets/CreateProfileServlet.java
// Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/ProfileConstants.java // public class ProfileConstants { // // public static final String PARAM_AVATAR = "avatar"; // public static final String PARAM_EMAIL = "email"; // public static final String PARAM_FAMILY_NAME = "familyName"; // public static final String PARAM_GIVEN_NAME = "givenName"; // public static final String PARAM_PASSWORD = "password"; // public static final String PARAM_USER_PROFILE_PATH = "profilePath"; // // public static final String PROP_EMAIL = "email"; // public static final String PROP_FAMILY_NAME = "familyName"; // public static final String PROP_GIVEN_NAME = "givenName"; // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AccountManager.java // @Component // @Service // public interface AccountManager { // /** // * Creates a new user profile in the repository. // * @param userName user's login name // * @param password user's passward // * @param givenName user's first name // * @param lastName user's last name // * @param email user's email // * @param avatarParam user's avatar upload parameter. This parameter may be null. // * @return the newly created profile resource, null if failed to create one. // */ // Resource createUser(String userName, String password, String givenName, String lastName, String email, RequestParameter avatarParam); // void changePassword(String newPassword, ResourceResolver resourceResolver); // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AvatarManager.java // @Component // @Service // public interface AvatarManager { // // /** // * Updates an existing avatar or creates a new one. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void saveAvatar(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // // /** // * Creates the folder structure and stores avatar for a profile without a avatar. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void createAvatarWithDirectories(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // }
import com.adobe.ionicapp.profile.ProfileConstants; import com.adobe.ionicapp.profile.services.AccountManager; import com.adobe.ionicapp.profile.services.AvatarManager; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.request.RequestParameter; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Servlet;
package com.adobe.ionicapp.profile.servlets; @Component(immediate = true, metatype = true) @Service(Servlet.class) @Properties({ @Property(name = "sling.servlet.resourceTypes", value = "sling/servlet/default"), @Property(name = "sling.servlet.methods", value = "POST"), @Property(name = "sling.servlet.selectors", value = "ionicapp.create"), @Property(name = "sling.servlet.extensions", value = "html") }) public class CreateProfileServlet extends SlingAllMethodsServlet { private static final Logger LOG = LoggerFactory.getLogger(CreateProfileServlet.class); @Reference AccountManager accountManager; @Override public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) {
// Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/ProfileConstants.java // public class ProfileConstants { // // public static final String PARAM_AVATAR = "avatar"; // public static final String PARAM_EMAIL = "email"; // public static final String PARAM_FAMILY_NAME = "familyName"; // public static final String PARAM_GIVEN_NAME = "givenName"; // public static final String PARAM_PASSWORD = "password"; // public static final String PARAM_USER_PROFILE_PATH = "profilePath"; // // public static final String PROP_EMAIL = "email"; // public static final String PROP_FAMILY_NAME = "familyName"; // public static final String PROP_GIVEN_NAME = "givenName"; // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AccountManager.java // @Component // @Service // public interface AccountManager { // /** // * Creates a new user profile in the repository. // * @param userName user's login name // * @param password user's passward // * @param givenName user's first name // * @param lastName user's last name // * @param email user's email // * @param avatarParam user's avatar upload parameter. This parameter may be null. // * @return the newly created profile resource, null if failed to create one. // */ // Resource createUser(String userName, String password, String givenName, String lastName, String email, RequestParameter avatarParam); // void changePassword(String newPassword, ResourceResolver resourceResolver); // } // // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/services/AvatarManager.java // @Component // @Service // public interface AvatarManager { // // /** // * Updates an existing avatar or creates a new one. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void saveAvatar(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // // /** // * Creates the folder structure and stores avatar for a profile without a avatar. // * @param inputStream avatar's upload stream // * @param mimeType file mime type // * @param resourceResolver resource resolver created from the user's session // * @param userProfilePath path to the user's profile, <code>/home/user/bob@email.com</code> for example // */ // void createAvatarWithDirectories(final InputStream inputStream, final String mimeType, // final ResourceResolver resourceResolver, final String userProfilePath); // } // Path: aem-package/bundles/ionic-app-profile-manager/src/main/java/com/adobe/ionicapp/profile/servlets/CreateProfileServlet.java import com.adobe.ionicapp.profile.ProfileConstants; import com.adobe.ionicapp.profile.services.AccountManager; import com.adobe.ionicapp.profile.services.AvatarManager; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.request.RequestParameter; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Servlet; package com.adobe.ionicapp.profile.servlets; @Component(immediate = true, metatype = true) @Service(Servlet.class) @Properties({ @Property(name = "sling.servlet.resourceTypes", value = "sling/servlet/default"), @Property(name = "sling.servlet.methods", value = "POST"), @Property(name = "sling.servlet.selectors", value = "ionicapp.create"), @Property(name = "sling.servlet.extensions", value = "html") }) public class CreateProfileServlet extends SlingAllMethodsServlet { private static final Logger LOG = LoggerFactory.getLogger(CreateProfileServlet.class); @Reference AccountManager accountManager; @Override public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) {
final String givenName = request.getParameter(ProfileConstants.PARAM_GIVEN_NAME);
shekhargulati/rx-docker-client
rx-docker-client/src/test/java/com/shekhargulati/reactivex/docker/client/ImageListQueryParametersTest.java
// Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/ImageListQueryParameters.java // public class ImageListQueryParameters { // private Optional<String> imageName = Optional.empty(); // private Map<String, List<String>> filters = new HashMap<>(); // private boolean all = false; // // public static ImageListQueryParameters queryParameterWithImageName(String imageName) { // return new ImageListQueryParameters(imageName); // } // // public static ImageListQueryParameters allImagesQueryParameters() { // return new ImageListQueryParameters(true); // } // // public static ImageListQueryParameters defaultQueryParameters() { // return new ImageListQueryParameters(); // } // // private ImageListQueryParameters() { // } // // public ImageListQueryParameters(String imageName, boolean all) { // this.imageName = Optional.ofNullable(imageName); // this.all = all; // } // // private ImageListQueryParameters(String imageName) { // this.imageName = Optional.ofNullable(imageName); // } // // private ImageListQueryParameters(boolean all) { // this.all = all; // } // // public ImageListQueryParameters addFilter(String key, String value) { // filters.put(key, filters.compute(key, (k, v) -> { // if (v == null) { // v = new ArrayList<>(); // // } // v.add(value); // return v; // })); // return this; // } // // public String toQuery() { // StringBuilder queryBuilder = new StringBuilder("?"); // queryBuilder.append("all=" + all); // queryBuilder.append("&"); // if (imageName.isPresent()) { // queryBuilder.append("filter=" + imageName.get()); // queryBuilder.append("&"); // } // if (!filters.isEmpty()) { // String json = new Gson().toJson(filters); // try { // final String encoded = URLEncoder.encode(json, UTF_8.name()); // queryBuilder.append("filters=" + encoded); // } catch (UnsupportedEncodingException e) { // throw new IllegalArgumentException(String.format("unable to encode filter %s", filters)); // } // } // String queryStr = queryBuilder.toString(); // if (queryStr.endsWith("&")) { // queryStr = queryStr.substring(0, queryStr.lastIndexOf("&")); // } // return queryStr; // } // // // }
import org.junit.Test; import static com.shekhargulati.reactivex.docker.client.ImageListQueryParameters.*; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat;
package com.shekhargulati.reactivex.docker.client; public class ImageListQueryParametersTest { @Test public void defaultQueryForListImages() throws Exception {
// Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/ImageListQueryParameters.java // public class ImageListQueryParameters { // private Optional<String> imageName = Optional.empty(); // private Map<String, List<String>> filters = new HashMap<>(); // private boolean all = false; // // public static ImageListQueryParameters queryParameterWithImageName(String imageName) { // return new ImageListQueryParameters(imageName); // } // // public static ImageListQueryParameters allImagesQueryParameters() { // return new ImageListQueryParameters(true); // } // // public static ImageListQueryParameters defaultQueryParameters() { // return new ImageListQueryParameters(); // } // // private ImageListQueryParameters() { // } // // public ImageListQueryParameters(String imageName, boolean all) { // this.imageName = Optional.ofNullable(imageName); // this.all = all; // } // // private ImageListQueryParameters(String imageName) { // this.imageName = Optional.ofNullable(imageName); // } // // private ImageListQueryParameters(boolean all) { // this.all = all; // } // // public ImageListQueryParameters addFilter(String key, String value) { // filters.put(key, filters.compute(key, (k, v) -> { // if (v == null) { // v = new ArrayList<>(); // // } // v.add(value); // return v; // })); // return this; // } // // public String toQuery() { // StringBuilder queryBuilder = new StringBuilder("?"); // queryBuilder.append("all=" + all); // queryBuilder.append("&"); // if (imageName.isPresent()) { // queryBuilder.append("filter=" + imageName.get()); // queryBuilder.append("&"); // } // if (!filters.isEmpty()) { // String json = new Gson().toJson(filters); // try { // final String encoded = URLEncoder.encode(json, UTF_8.name()); // queryBuilder.append("filters=" + encoded); // } catch (UnsupportedEncodingException e) { // throw new IllegalArgumentException(String.format("unable to encode filter %s", filters)); // } // } // String queryStr = queryBuilder.toString(); // if (queryStr.endsWith("&")) { // queryStr = queryStr.substring(0, queryStr.lastIndexOf("&")); // } // return queryStr; // } // // // } // Path: rx-docker-client/src/test/java/com/shekhargulati/reactivex/docker/client/ImageListQueryParametersTest.java import org.junit.Test; import static com.shekhargulati.reactivex.docker.client.ImageListQueryParameters.*; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; package com.shekhargulati.reactivex.docker.client; public class ImageListQueryParametersTest { @Test public void defaultQueryForListImages() throws Exception {
ImageListQueryParameters queryParameters = defaultQueryParameters();
shekhargulati/rx-docker-client
rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/DefaultRxDockerClient.java
// Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Dates.java // public abstract class Dates { // public static final String DOCKER_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public abstract class StreamUtils { // // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Strings.java // public abstract class Strings { // // public static boolean isEmptyOrNull(String str) { // Optional<String> optional = Optional.ofNullable(str); // return optional.flatMap(s -> s.trim().length() == 0 ? Optional.of(true) : Optional.of(false)).orElse(true); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Validations.java // public static <T> void validate(T t, Predicate<T> predicate, String message) throws IllegalArgumentException { // if (predicate.test(t)) { // throw new IllegalArgumentException(message); // } // }
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.shekhargulati.reactivex.docker.client.representations.*; import com.shekhargulati.reactivex.docker.client.utils.Dates; import com.shekhargulati.reactivex.docker.client.utils.StreamUtils; import com.shekhargulati.reactivex.docker.client.utils.Strings; import com.shekhargulati.reactivex.rxokhttp.*; import com.shekhargulati.reactivex.rxokhttp.functions.*; import okhttp3.Response; import okhttp3.ResponseBody; import okio.Buffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscriber; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.AbstractMap.SimpleEntry; import java.util.*; import java.util.function.Predicate; import java.util.stream.Stream; import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE; import static com.shekhargulati.reactivex.docker.client.utils.StreamUtils.iteratorToStream; import static com.shekhargulati.reactivex.docker.client.utils.Validations.validate; import static com.shekhargulati.reactivex.rxokhttp.ClientConfig.defaultConfig; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap;
/* * The MIT License * * Copyright 2015 Shekhar Gulati <shekhargulati84@gmail.com>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.shekhargulati.reactivex.docker.client; class DefaultRxDockerClient implements RxDockerClient { private static final String EMPTY_BODY = ""; private final Logger logger = LoggerFactory.getLogger(DefaultRxDockerClient.class); private final String apiUri; private final RxHttpClient httpClient; private final Gson gson = new GsonBuilder() .setFieldNamingPolicy(UPPER_CAMEL_CASE)
// Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Dates.java // public abstract class Dates { // public static final String DOCKER_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public abstract class StreamUtils { // // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Strings.java // public abstract class Strings { // // public static boolean isEmptyOrNull(String str) { // Optional<String> optional = Optional.ofNullable(str); // return optional.flatMap(s -> s.trim().length() == 0 ? Optional.of(true) : Optional.of(false)).orElse(true); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Validations.java // public static <T> void validate(T t, Predicate<T> predicate, String message) throws IllegalArgumentException { // if (predicate.test(t)) { // throw new IllegalArgumentException(message); // } // } // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/DefaultRxDockerClient.java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.shekhargulati.reactivex.docker.client.representations.*; import com.shekhargulati.reactivex.docker.client.utils.Dates; import com.shekhargulati.reactivex.docker.client.utils.StreamUtils; import com.shekhargulati.reactivex.docker.client.utils.Strings; import com.shekhargulati.reactivex.rxokhttp.*; import com.shekhargulati.reactivex.rxokhttp.functions.*; import okhttp3.Response; import okhttp3.ResponseBody; import okio.Buffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscriber; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.AbstractMap.SimpleEntry; import java.util.*; import java.util.function.Predicate; import java.util.stream.Stream; import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE; import static com.shekhargulati.reactivex.docker.client.utils.StreamUtils.iteratorToStream; import static com.shekhargulati.reactivex.docker.client.utils.Validations.validate; import static com.shekhargulati.reactivex.rxokhttp.ClientConfig.defaultConfig; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; /* * The MIT License * * Copyright 2015 Shekhar Gulati <shekhargulati84@gmail.com>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.shekhargulati.reactivex.docker.client; class DefaultRxDockerClient implements RxDockerClient { private static final String EMPTY_BODY = ""; private final Logger logger = LoggerFactory.getLogger(DefaultRxDockerClient.class); private final String apiUri; private final RxHttpClient httpClient; private final Gson gson = new GsonBuilder() .setFieldNamingPolicy(UPPER_CAMEL_CASE)
.setDateFormat(Dates.DOCKER_DATE_TIME_FORMAT)
shekhargulati/rx-docker-client
rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/DefaultRxDockerClient.java
// Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Dates.java // public abstract class Dates { // public static final String DOCKER_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public abstract class StreamUtils { // // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Strings.java // public abstract class Strings { // // public static boolean isEmptyOrNull(String str) { // Optional<String> optional = Optional.ofNullable(str); // return optional.flatMap(s -> s.trim().length() == 0 ? Optional.of(true) : Optional.of(false)).orElse(true); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Validations.java // public static <T> void validate(T t, Predicate<T> predicate, String message) throws IllegalArgumentException { // if (predicate.test(t)) { // throw new IllegalArgumentException(message); // } // }
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.shekhargulati.reactivex.docker.client.representations.*; import com.shekhargulati.reactivex.docker.client.utils.Dates; import com.shekhargulati.reactivex.docker.client.utils.StreamUtils; import com.shekhargulati.reactivex.docker.client.utils.Strings; import com.shekhargulati.reactivex.rxokhttp.*; import com.shekhargulati.reactivex.rxokhttp.functions.*; import okhttp3.Response; import okhttp3.ResponseBody; import okio.Buffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscriber; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.AbstractMap.SimpleEntry; import java.util.*; import java.util.function.Predicate; import java.util.stream.Stream; import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE; import static com.shekhargulati.reactivex.docker.client.utils.StreamUtils.iteratorToStream; import static com.shekhargulati.reactivex.docker.client.utils.Validations.validate; import static com.shekhargulati.reactivex.rxokhttp.ClientConfig.defaultConfig; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap;
} @Override public Observable<DockerInfo> infoObs() { return httpClient .get(INFO_ENDPOINT, (StringResponseTransformer<DockerInfo>) json -> gson.fromJson(json, DockerInfo.class)); } @Override public DockerInfo info() { return infoObs(). toBlocking(). single(); } @Override public HttpStatus checkAuth(final AuthConfig authConfig) { return checkAuthObs(authConfig).onErrorReturn(e -> { if (e instanceof ServiceException) { logger.info("checkAuth threw RestServiceCommunicationException"); ServiceException restException = (ServiceException) e; return HttpStatus.of(restException.getCode(), restException.getHttpMessage()); } return HttpStatus.of(500, e.getMessage()); }).toBlocking().last(); } @Override public Observable<HttpStatus> checkAuthObs(final AuthConfig authConfig) {
// Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Dates.java // public abstract class Dates { // public static final String DOCKER_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public abstract class StreamUtils { // // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Strings.java // public abstract class Strings { // // public static boolean isEmptyOrNull(String str) { // Optional<String> optional = Optional.ofNullable(str); // return optional.flatMap(s -> s.trim().length() == 0 ? Optional.of(true) : Optional.of(false)).orElse(true); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Validations.java // public static <T> void validate(T t, Predicate<T> predicate, String message) throws IllegalArgumentException { // if (predicate.test(t)) { // throw new IllegalArgumentException(message); // } // } // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/DefaultRxDockerClient.java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.shekhargulati.reactivex.docker.client.representations.*; import com.shekhargulati.reactivex.docker.client.utils.Dates; import com.shekhargulati.reactivex.docker.client.utils.StreamUtils; import com.shekhargulati.reactivex.docker.client.utils.Strings; import com.shekhargulati.reactivex.rxokhttp.*; import com.shekhargulati.reactivex.rxokhttp.functions.*; import okhttp3.Response; import okhttp3.ResponseBody; import okio.Buffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscriber; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.AbstractMap.SimpleEntry; import java.util.*; import java.util.function.Predicate; import java.util.stream.Stream; import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE; import static com.shekhargulati.reactivex.docker.client.utils.StreamUtils.iteratorToStream; import static com.shekhargulati.reactivex.docker.client.utils.Validations.validate; import static com.shekhargulati.reactivex.rxokhttp.ClientConfig.defaultConfig; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; } @Override public Observable<DockerInfo> infoObs() { return httpClient .get(INFO_ENDPOINT, (StringResponseTransformer<DockerInfo>) json -> gson.fromJson(json, DockerInfo.class)); } @Override public DockerInfo info() { return infoObs(). toBlocking(). single(); } @Override public HttpStatus checkAuth(final AuthConfig authConfig) { return checkAuthObs(authConfig).onErrorReturn(e -> { if (e instanceof ServiceException) { logger.info("checkAuth threw RestServiceCommunicationException"); ServiceException restException = (ServiceException) e; return HttpStatus.of(restException.getCode(), restException.getHttpMessage()); } return HttpStatus.of(500, e.getMessage()); }).toBlocking().last(); } @Override public Observable<HttpStatus> checkAuthObs(final AuthConfig authConfig) {
validate(authConfig, cfg -> cfg == null, () -> "authConfig can't be null.");
shekhargulati/rx-docker-client
rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/DefaultRxDockerClient.java
// Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Dates.java // public abstract class Dates { // public static final String DOCKER_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public abstract class StreamUtils { // // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Strings.java // public abstract class Strings { // // public static boolean isEmptyOrNull(String str) { // Optional<String> optional = Optional.ofNullable(str); // return optional.flatMap(s -> s.trim().length() == 0 ? Optional.of(true) : Optional.of(false)).orElse(true); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Validations.java // public static <T> void validate(T t, Predicate<T> predicate, String message) throws IllegalArgumentException { // if (predicate.test(t)) { // throw new IllegalArgumentException(message); // } // }
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.shekhargulati.reactivex.docker.client.representations.*; import com.shekhargulati.reactivex.docker.client.utils.Dates; import com.shekhargulati.reactivex.docker.client.utils.StreamUtils; import com.shekhargulati.reactivex.docker.client.utils.Strings; import com.shekhargulati.reactivex.rxokhttp.*; import com.shekhargulati.reactivex.rxokhttp.functions.*; import okhttp3.Response; import okhttp3.ResponseBody; import okio.Buffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscriber; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.AbstractMap.SimpleEntry; import java.util.*; import java.util.function.Predicate; import java.util.stream.Stream; import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE; import static com.shekhargulati.reactivex.docker.client.utils.StreamUtils.iteratorToStream; import static com.shekhargulati.reactivex.docker.client.utils.Validations.validate; import static com.shekhargulati.reactivex.rxokhttp.ClientConfig.defaultConfig; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap;
public Observable<DockerContainerResponse> createContainerObs(String jsonRequest, String name) { return createContainerObs(jsonRequest, Optional.ofNullable(name)); } private Observable<DockerContainerResponse> createContainerObs(String jsonRequest, Optional<String> name) { if (jsonRequest == null || jsonRequest.length() == 0) { throw new IllegalArgumentException("jsonRequest can't be null or empty"); } logger.info("Creating container for json request >>\n'{}'", jsonRequest); final String uri = name.isPresent() ? CREATE_CONTAINER_ENDPOINT + "?name=" + name.get() : CREATE_CONTAINER_ENDPOINT; return httpClient.post(uri, jsonRequest, (ResponseBody body) -> gson.fromJson(body.string(), DockerContainerResponse.class)); } @Override public DockerContainerResponse createContainer(String jsonRequest) { return createContainerObs(jsonRequest).toBlocking().last(); } @Override public DockerContainerResponse createContainer(String jsonRequest, String name) { return createContainerObs(jsonRequest, name).toBlocking().last(); } @Override public ContainerInspectResponse inspectContainer(final String containerId) { return inspectContainerObs(containerId).toBlocking().single(); } @Override public Observable<ContainerInspectResponse> inspectContainerObs(final String containerId) {
// Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Dates.java // public abstract class Dates { // public static final String DOCKER_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public abstract class StreamUtils { // // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Strings.java // public abstract class Strings { // // public static boolean isEmptyOrNull(String str) { // Optional<String> optional = Optional.ofNullable(str); // return optional.flatMap(s -> s.trim().length() == 0 ? Optional.of(true) : Optional.of(false)).orElse(true); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Validations.java // public static <T> void validate(T t, Predicate<T> predicate, String message) throws IllegalArgumentException { // if (predicate.test(t)) { // throw new IllegalArgumentException(message); // } // } // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/DefaultRxDockerClient.java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.shekhargulati.reactivex.docker.client.representations.*; import com.shekhargulati.reactivex.docker.client.utils.Dates; import com.shekhargulati.reactivex.docker.client.utils.StreamUtils; import com.shekhargulati.reactivex.docker.client.utils.Strings; import com.shekhargulati.reactivex.rxokhttp.*; import com.shekhargulati.reactivex.rxokhttp.functions.*; import okhttp3.Response; import okhttp3.ResponseBody; import okio.Buffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscriber; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.AbstractMap.SimpleEntry; import java.util.*; import java.util.function.Predicate; import java.util.stream.Stream; import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE; import static com.shekhargulati.reactivex.docker.client.utils.StreamUtils.iteratorToStream; import static com.shekhargulati.reactivex.docker.client.utils.Validations.validate; import static com.shekhargulati.reactivex.rxokhttp.ClientConfig.defaultConfig; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; public Observable<DockerContainerResponse> createContainerObs(String jsonRequest, String name) { return createContainerObs(jsonRequest, Optional.ofNullable(name)); } private Observable<DockerContainerResponse> createContainerObs(String jsonRequest, Optional<String> name) { if (jsonRequest == null || jsonRequest.length() == 0) { throw new IllegalArgumentException("jsonRequest can't be null or empty"); } logger.info("Creating container for json request >>\n'{}'", jsonRequest); final String uri = name.isPresent() ? CREATE_CONTAINER_ENDPOINT + "?name=" + name.get() : CREATE_CONTAINER_ENDPOINT; return httpClient.post(uri, jsonRequest, (ResponseBody body) -> gson.fromJson(body.string(), DockerContainerResponse.class)); } @Override public DockerContainerResponse createContainer(String jsonRequest) { return createContainerObs(jsonRequest).toBlocking().last(); } @Override public DockerContainerResponse createContainer(String jsonRequest, String name) { return createContainerObs(jsonRequest, name).toBlocking().last(); } @Override public ContainerInspectResponse inspectContainer(final String containerId) { return inspectContainerObs(containerId).toBlocking().single(); } @Override public Observable<ContainerInspectResponse> inspectContainerObs(final String containerId) {
validate(containerId, Strings::isEmptyOrNull, () -> "containerId can't be null or empty.");
shekhargulati/rx-docker-client
rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/DefaultRxDockerClient.java
// Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Dates.java // public abstract class Dates { // public static final String DOCKER_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public abstract class StreamUtils { // // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Strings.java // public abstract class Strings { // // public static boolean isEmptyOrNull(String str) { // Optional<String> optional = Optional.ofNullable(str); // return optional.flatMap(s -> s.trim().length() == 0 ? Optional.of(true) : Optional.of(false)).orElse(true); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Validations.java // public static <T> void validate(T t, Predicate<T> predicate, String message) throws IllegalArgumentException { // if (predicate.test(t)) { // throw new IllegalArgumentException(message); // } // }
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.shekhargulati.reactivex.docker.client.representations.*; import com.shekhargulati.reactivex.docker.client.utils.Dates; import com.shekhargulati.reactivex.docker.client.utils.StreamUtils; import com.shekhargulati.reactivex.docker.client.utils.Strings; import com.shekhargulati.reactivex.rxokhttp.*; import com.shekhargulati.reactivex.rxokhttp.functions.*; import okhttp3.Response; import okhttp3.ResponseBody; import okio.Buffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscriber; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.AbstractMap.SimpleEntry; import java.util.*; import java.util.function.Predicate; import java.util.stream.Stream; import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE; import static com.shekhargulati.reactivex.docker.client.utils.StreamUtils.iteratorToStream; import static com.shekhargulati.reactivex.docker.client.utils.Validations.validate; import static com.shekhargulati.reactivex.rxokhttp.ClientConfig.defaultConfig; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap;
final String endpointUri = String.format(CONTAINER_EXPORT_ENDPOINT, containerId); Observable<Buffer> bufferStream = httpClient.getResponseBufferStream(endpointUri); String exportFilePath = pathToExportTo.toString() + "/" + containerId + ".tar"; writeToOutputDir(bufferStream, exportFilePath); } @Override public Observable<ContainerStats> containerStatsObs(final String containerId) { validate(containerId, Strings::isEmptyOrNull, () -> "containerId can't be null or empty."); final String endpointUri = String.format(CONTAINER_STATS_ENDPOINT, containerId); return httpClient.getResponseStream(endpointUri).map(json -> gson.fromJson(json, ContainerStats.class)); } @Override public Observable<String> containerLogsObs(final String containerId) { return containerLogsObs(containerId, ContainerLogQueryParameters.withDefaultValues()); } @Override public Observable<String> containerLogsObs(final String containerId, ContainerLogQueryParameters queryParameters) { validate(containerId, Strings::isEmptyOrNull, () -> "containerId can't be null or empty."); final String endpointUri = String.format(CONTAINER_LOGS_ENDPOINT, containerId) + queryParameters.toQueryParametersString(); Map<String, String> headers = Stream.of(new SimpleEntry<>("Accept", "application/vnd.docker.raw-stream")) .collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue)); return httpClient .getResponseStream(endpointUri, headers); } @Override public List<ContainerChange> inspectChangesOnContainerFilesystem(final String containerId) {
// Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Dates.java // public abstract class Dates { // public static final String DOCKER_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public abstract class StreamUtils { // // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Strings.java // public abstract class Strings { // // public static boolean isEmptyOrNull(String str) { // Optional<String> optional = Optional.ofNullable(str); // return optional.flatMap(s -> s.trim().length() == 0 ? Optional.of(true) : Optional.of(false)).orElse(true); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Validations.java // public static <T> void validate(T t, Predicate<T> predicate, String message) throws IllegalArgumentException { // if (predicate.test(t)) { // throw new IllegalArgumentException(message); // } // } // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/DefaultRxDockerClient.java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.shekhargulati.reactivex.docker.client.representations.*; import com.shekhargulati.reactivex.docker.client.utils.Dates; import com.shekhargulati.reactivex.docker.client.utils.StreamUtils; import com.shekhargulati.reactivex.docker.client.utils.Strings; import com.shekhargulati.reactivex.rxokhttp.*; import com.shekhargulati.reactivex.rxokhttp.functions.*; import okhttp3.Response; import okhttp3.ResponseBody; import okio.Buffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscriber; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.AbstractMap.SimpleEntry; import java.util.*; import java.util.function.Predicate; import java.util.stream.Stream; import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE; import static com.shekhargulati.reactivex.docker.client.utils.StreamUtils.iteratorToStream; import static com.shekhargulati.reactivex.docker.client.utils.Validations.validate; import static com.shekhargulati.reactivex.rxokhttp.ClientConfig.defaultConfig; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; final String endpointUri = String.format(CONTAINER_EXPORT_ENDPOINT, containerId); Observable<Buffer> bufferStream = httpClient.getResponseBufferStream(endpointUri); String exportFilePath = pathToExportTo.toString() + "/" + containerId + ".tar"; writeToOutputDir(bufferStream, exportFilePath); } @Override public Observable<ContainerStats> containerStatsObs(final String containerId) { validate(containerId, Strings::isEmptyOrNull, () -> "containerId can't be null or empty."); final String endpointUri = String.format(CONTAINER_STATS_ENDPOINT, containerId); return httpClient.getResponseStream(endpointUri).map(json -> gson.fromJson(json, ContainerStats.class)); } @Override public Observable<String> containerLogsObs(final String containerId) { return containerLogsObs(containerId, ContainerLogQueryParameters.withDefaultValues()); } @Override public Observable<String> containerLogsObs(final String containerId, ContainerLogQueryParameters queryParameters) { validate(containerId, Strings::isEmptyOrNull, () -> "containerId can't be null or empty."); final String endpointUri = String.format(CONTAINER_LOGS_ENDPOINT, containerId) + queryParameters.toQueryParametersString(); Map<String, String> headers = Stream.of(new SimpleEntry<>("Accept", "application/vnd.docker.raw-stream")) .collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue)); return httpClient .getResponseStream(endpointUri, headers); } @Override public List<ContainerChange> inspectChangesOnContainerFilesystem(final String containerId) {
return StreamUtils.iteratorToStream(inspectChangesOnContainerFilesystemObs(containerId).toBlocking().getIterator()).collect(toList());
shekhargulati/rx-docker-client
rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/DefaultRxDockerClient.java
// Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Dates.java // public abstract class Dates { // public static final String DOCKER_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public abstract class StreamUtils { // // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Strings.java // public abstract class Strings { // // public static boolean isEmptyOrNull(String str) { // Optional<String> optional = Optional.ofNullable(str); // return optional.flatMap(s -> s.trim().length() == 0 ? Optional.of(true) : Optional.of(false)).orElse(true); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Validations.java // public static <T> void validate(T t, Predicate<T> predicate, String message) throws IllegalArgumentException { // if (predicate.test(t)) { // throw new IllegalArgumentException(message); // } // }
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.shekhargulati.reactivex.docker.client.representations.*; import com.shekhargulati.reactivex.docker.client.utils.Dates; import com.shekhargulati.reactivex.docker.client.utils.StreamUtils; import com.shekhargulati.reactivex.docker.client.utils.Strings; import com.shekhargulati.reactivex.rxokhttp.*; import com.shekhargulati.reactivex.rxokhttp.functions.*; import okhttp3.Response; import okhttp3.ResponseBody; import okio.Buffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscriber; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.AbstractMap.SimpleEntry; import java.util.*; import java.util.function.Predicate; import java.util.stream.Stream; import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE; import static com.shekhargulati.reactivex.docker.client.utils.StreamUtils.iteratorToStream; import static com.shekhargulati.reactivex.docker.client.utils.Validations.validate; import static com.shekhargulati.reactivex.rxokhttp.ClientConfig.defaultConfig; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap;
final String endpointUri = String.format(CONTAINER_EXPORT_ENDPOINT, containerId); Observable<Buffer> bufferStream = httpClient.getResponseBufferStream(endpointUri); String exportFilePath = pathToExportTo.toString() + "/" + containerId + ".tar"; writeToOutputDir(bufferStream, exportFilePath); } @Override public Observable<ContainerStats> containerStatsObs(final String containerId) { validate(containerId, Strings::isEmptyOrNull, () -> "containerId can't be null or empty."); final String endpointUri = String.format(CONTAINER_STATS_ENDPOINT, containerId); return httpClient.getResponseStream(endpointUri).map(json -> gson.fromJson(json, ContainerStats.class)); } @Override public Observable<String> containerLogsObs(final String containerId) { return containerLogsObs(containerId, ContainerLogQueryParameters.withDefaultValues()); } @Override public Observable<String> containerLogsObs(final String containerId, ContainerLogQueryParameters queryParameters) { validate(containerId, Strings::isEmptyOrNull, () -> "containerId can't be null or empty."); final String endpointUri = String.format(CONTAINER_LOGS_ENDPOINT, containerId) + queryParameters.toQueryParametersString(); Map<String, String> headers = Stream.of(new SimpleEntry<>("Accept", "application/vnd.docker.raw-stream")) .collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue)); return httpClient .getResponseStream(endpointUri, headers); } @Override public List<ContainerChange> inspectChangesOnContainerFilesystem(final String containerId) {
// Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Dates.java // public abstract class Dates { // public static final String DOCKER_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public abstract class StreamUtils { // // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Strings.java // public abstract class Strings { // // public static boolean isEmptyOrNull(String str) { // Optional<String> optional = Optional.ofNullable(str); // return optional.flatMap(s -> s.trim().length() == 0 ? Optional.of(true) : Optional.of(false)).orElse(true); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/StreamUtils.java // public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) { // return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Validations.java // public static <T> void validate(T t, Predicate<T> predicate, String message) throws IllegalArgumentException { // if (predicate.test(t)) { // throw new IllegalArgumentException(message); // } // } // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/DefaultRxDockerClient.java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.shekhargulati.reactivex.docker.client.representations.*; import com.shekhargulati.reactivex.docker.client.utils.Dates; import com.shekhargulati.reactivex.docker.client.utils.StreamUtils; import com.shekhargulati.reactivex.docker.client.utils.Strings; import com.shekhargulati.reactivex.rxokhttp.*; import com.shekhargulati.reactivex.rxokhttp.functions.*; import okhttp3.Response; import okhttp3.ResponseBody; import okio.Buffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Subscriber; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.AbstractMap.SimpleEntry; import java.util.*; import java.util.function.Predicate; import java.util.stream.Stream; import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE; import static com.shekhargulati.reactivex.docker.client.utils.StreamUtils.iteratorToStream; import static com.shekhargulati.reactivex.docker.client.utils.Validations.validate; import static com.shekhargulati.reactivex.rxokhttp.ClientConfig.defaultConfig; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; final String endpointUri = String.format(CONTAINER_EXPORT_ENDPOINT, containerId); Observable<Buffer> bufferStream = httpClient.getResponseBufferStream(endpointUri); String exportFilePath = pathToExportTo.toString() + "/" + containerId + ".tar"; writeToOutputDir(bufferStream, exportFilePath); } @Override public Observable<ContainerStats> containerStatsObs(final String containerId) { validate(containerId, Strings::isEmptyOrNull, () -> "containerId can't be null or empty."); final String endpointUri = String.format(CONTAINER_STATS_ENDPOINT, containerId); return httpClient.getResponseStream(endpointUri).map(json -> gson.fromJson(json, ContainerStats.class)); } @Override public Observable<String> containerLogsObs(final String containerId) { return containerLogsObs(containerId, ContainerLogQueryParameters.withDefaultValues()); } @Override public Observable<String> containerLogsObs(final String containerId, ContainerLogQueryParameters queryParameters) { validate(containerId, Strings::isEmptyOrNull, () -> "containerId can't be null or empty."); final String endpointUri = String.format(CONTAINER_LOGS_ENDPOINT, containerId) + queryParameters.toQueryParametersString(); Map<String, String> headers = Stream.of(new SimpleEntry<>("Accept", "application/vnd.docker.raw-stream")) .collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue)); return httpClient .getResponseStream(endpointUri, headers); } @Override public List<ContainerChange> inspectChangesOnContainerFilesystem(final String containerId) {
return StreamUtils.iteratorToStream(inspectChangesOnContainerFilesystemObs(containerId).toBlocking().getIterator()).collect(toList());
shekhargulati/rx-docker-client
samples/src/main/java/com/shekhargulati/reactivex/rx_docker_client/samples/CreateExposePortsAndStartContainer.java
// Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/RxDockerClient.java // public interface RxDockerClient extends MiscOperations, ContainerOperations, ImageOperations { // // String DEFAULT_DOCKER_HOST = "127.0.0.1"; // int DEFAULT_DOCKER_PORT = 2375; // // /** // * Builds the client using DOCKER_HOST and DOCKER_CERT_PATH environment variables // * // * @return a new instance of DefaultRxDockerClient // */ // static RxDockerClient fromDefaultEnv() { // return newDockerClient(System.getenv("DOCKER_HOST"), System.getenv("DOCKER_CERT_PATH")); // } // // static DefaultRxDockerClient newDockerClient(final String dockerHost, final String dockerCertPath) { // return new DefaultRxDockerClient(dockerHost, dockerCertPath); // } // // String getApiUri(); // // }
import com.shekhargulati.reactivex.docker.client.RxDockerClient; import com.shekhargulati.reactivex.docker.client.representations.*; import java.util.*;
/* * The MIT License * * Copyright 2015 Shekhar Gulati <shekhargulati84@gmail.com>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.shekhargulati.reactivex.rx_docker_client.samples; public class CreateExposePortsAndStartContainer { public static void main(String[] args) {
// Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/RxDockerClient.java // public interface RxDockerClient extends MiscOperations, ContainerOperations, ImageOperations { // // String DEFAULT_DOCKER_HOST = "127.0.0.1"; // int DEFAULT_DOCKER_PORT = 2375; // // /** // * Builds the client using DOCKER_HOST and DOCKER_CERT_PATH environment variables // * // * @return a new instance of DefaultRxDockerClient // */ // static RxDockerClient fromDefaultEnv() { // return newDockerClient(System.getenv("DOCKER_HOST"), System.getenv("DOCKER_CERT_PATH")); // } // // static DefaultRxDockerClient newDockerClient(final String dockerHost, final String dockerCertPath) { // return new DefaultRxDockerClient(dockerHost, dockerCertPath); // } // // String getApiUri(); // // } // Path: samples/src/main/java/com/shekhargulati/reactivex/rx_docker_client/samples/CreateExposePortsAndStartContainer.java import com.shekhargulati.reactivex.docker.client.RxDockerClient; import com.shekhargulati.reactivex.docker.client.representations.*; import java.util.*; /* * The MIT License * * Copyright 2015 Shekhar Gulati <shekhargulati84@gmail.com>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.shekhargulati.reactivex.rx_docker_client.samples; public class CreateExposePortsAndStartContainer { public static void main(String[] args) {
RxDockerClient client = RxDockerClient.fromDefaultEnv();
shekhargulati/rx-docker-client
rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/HostAndPort.java
// Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Strings.java // public abstract class Strings { // // public static boolean isEmptyOrNull(String str) { // Optional<String> optional = Optional.ofNullable(str); // return optional.flatMap(s -> s.trim().length() == 0 ? Optional.of(true) : Optional.of(false)).orElse(true); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Validations.java // public abstract class Validations { // // public static <T> void validate(T t, Predicate<T> predicate, String message) throws IllegalArgumentException { // if (predicate.test(t)) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void validate(T t, Predicate<T> predicate, Supplier<String> messageSupplier) throws IllegalArgumentException { // validate(t, predicate, messageSupplier.get()); // } // // }
import com.shekhargulati.reactivex.docker.client.utils.Strings; import com.shekhargulati.reactivex.docker.client.utils.Validations;
/* * The MIT License * * Copyright 2015 Shekhar Gulati <shekhargulati84@gmail.com>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.shekhargulati.reactivex.docker.client; public final class HostAndPort { private final String host; private final int port; public HostAndPort(String host, int port) { this.host = host; this.port = port; } public static HostAndPort using(String host, int port) { return new HostAndPort(host, port); } public static HostAndPort from(String hostPortString) {
// Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Strings.java // public abstract class Strings { // // public static boolean isEmptyOrNull(String str) { // Optional<String> optional = Optional.ofNullable(str); // return optional.flatMap(s -> s.trim().length() == 0 ? Optional.of(true) : Optional.of(false)).orElse(true); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Validations.java // public abstract class Validations { // // public static <T> void validate(T t, Predicate<T> predicate, String message) throws IllegalArgumentException { // if (predicate.test(t)) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void validate(T t, Predicate<T> predicate, Supplier<String> messageSupplier) throws IllegalArgumentException { // validate(t, predicate, messageSupplier.get()); // } // // } // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/HostAndPort.java import com.shekhargulati.reactivex.docker.client.utils.Strings; import com.shekhargulati.reactivex.docker.client.utils.Validations; /* * The MIT License * * Copyright 2015 Shekhar Gulati <shekhargulati84@gmail.com>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.shekhargulati.reactivex.docker.client; public final class HostAndPort { private final String host; private final int port; public HostAndPort(String host, int port) { this.host = host; this.port = port; } public static HostAndPort using(String host, int port) { return new HostAndPort(host, port); } public static HostAndPort from(String hostPortString) {
Validations.validate(hostPortString, Strings::isEmptyOrNull, "hostPortString can't be null");
shekhargulati/rx-docker-client
rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/HostAndPort.java
// Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Strings.java // public abstract class Strings { // // public static boolean isEmptyOrNull(String str) { // Optional<String> optional = Optional.ofNullable(str); // return optional.flatMap(s -> s.trim().length() == 0 ? Optional.of(true) : Optional.of(false)).orElse(true); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Validations.java // public abstract class Validations { // // public static <T> void validate(T t, Predicate<T> predicate, String message) throws IllegalArgumentException { // if (predicate.test(t)) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void validate(T t, Predicate<T> predicate, Supplier<String> messageSupplier) throws IllegalArgumentException { // validate(t, predicate, messageSupplier.get()); // } // // }
import com.shekhargulati.reactivex.docker.client.utils.Strings; import com.shekhargulati.reactivex.docker.client.utils.Validations;
/* * The MIT License * * Copyright 2015 Shekhar Gulati <shekhargulati84@gmail.com>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.shekhargulati.reactivex.docker.client; public final class HostAndPort { private final String host; private final int port; public HostAndPort(String host, int port) { this.host = host; this.port = port; } public static HostAndPort using(String host, int port) { return new HostAndPort(host, port); } public static HostAndPort from(String hostPortString) {
// Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Strings.java // public abstract class Strings { // // public static boolean isEmptyOrNull(String str) { // Optional<String> optional = Optional.ofNullable(str); // return optional.flatMap(s -> s.trim().length() == 0 ? Optional.of(true) : Optional.of(false)).orElse(true); // } // } // // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/utils/Validations.java // public abstract class Validations { // // public static <T> void validate(T t, Predicate<T> predicate, String message) throws IllegalArgumentException { // if (predicate.test(t)) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void validate(T t, Predicate<T> predicate, Supplier<String> messageSupplier) throws IllegalArgumentException { // validate(t, predicate, messageSupplier.get()); // } // // } // Path: rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/HostAndPort.java import com.shekhargulati.reactivex.docker.client.utils.Strings; import com.shekhargulati.reactivex.docker.client.utils.Validations; /* * The MIT License * * Copyright 2015 Shekhar Gulati <shekhargulati84@gmail.com>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.shekhargulati.reactivex.docker.client; public final class HostAndPort { private final String host; private final int port; public HostAndPort(String host, int port) { this.host = host; this.port = port; } public static HostAndPort using(String host, int port) { return new HostAndPort(host, port); } public static HostAndPort from(String hostPortString) {
Validations.validate(hostPortString, Strings::isEmptyOrNull, "hostPortString can't be null");
welkinbai/BsonMapper
src/main/java/me/welkinbai/bsonmapper/BsonValueConverterRepertory.java
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // }
import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; import org.bson.BsonDbPointer; import org.bson.BsonRegularExpression; import org.bson.BsonTimestamp; import org.bson.BsonType; import org.bson.BsonUndefined; import org.bson.BsonValue; import org.bson.codecs.BsonTypeClassMap; import org.bson.types.Binary; import org.bson.types.Code; import org.bson.types.CodeWithScope; import org.bson.types.Decimal128; import org.bson.types.MaxKey; import org.bson.types.MinKey; import org.bson.types.ObjectId; import org.bson.types.Symbol; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Map;
CLASS_BSON_CONVERTER_MAP.put(Long.class, BsonLongConverter.getInstance()); CLASS_BSON_CONVERTER_MAP.put(long.class, BsonLongConverter.getInstance()); CLASS_BSON_CONVERTER_MAP.put(BsonTimestamp.class, BsonTimestampConverter.getInstance()); CLASS_BSON_CONVERTER_MAP.put(Decimal128.class, BsonBigDecimalConverter.getInstance()); CLASS_BSON_CONVERTER_MAP.put(MinKey.class, BsonMinKeyConverter.getInstance()); CLASS_BSON_CONVERTER_MAP.put(MaxKey.class, BsonMaxKeyConverter.getInstance()); CLASS_BSON_CONVERTER_MAP.put(StringObjectId.class, BsonStringObjectIdConverter.getInstance()); } static BsonValueConverter getValueConverterByBsonType(BsonType bsonType) { Class<?> clazz = getClazzByBsonType(bsonType); return (BsonValueConverter) CLASS_BSON_CONVERTER_MAP.get(clazz); } static <T, V extends BsonValue> BsonValueConverter<T, V> getValueConverterByClazz(Class<?> clazz) { return (BsonValueConverter<T, V>) CLASS_BSON_CONVERTER_MAP.get(clazz); } static BsonByteIOConverter getByteIOConverterByBsonType(BsonType bsonType) { Class<?> clazz = getClazzByBsonType(bsonType); return (BsonByteIOConverter) CLASS_BSON_CONVERTER_MAP.get(clazz); } static <T> BsonByteIOConverter<T> getByteIOConverterByClazz(Class<?> clazz) { return (BsonByteIOConverter<T>) CLASS_BSON_CONVERTER_MAP.get(clazz); } private static Class<?> getClazzByBsonType(BsonType bsonType) { Class<?> clazz = BSON_TYPE_CLASS_MAP.get(bsonType); if (clazz == null) {
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/me/welkinbai/bsonmapper/BsonValueConverterRepertory.java import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; import org.bson.BsonDbPointer; import org.bson.BsonRegularExpression; import org.bson.BsonTimestamp; import org.bson.BsonType; import org.bson.BsonUndefined; import org.bson.BsonValue; import org.bson.codecs.BsonTypeClassMap; import org.bson.types.Binary; import org.bson.types.Code; import org.bson.types.CodeWithScope; import org.bson.types.Decimal128; import org.bson.types.MaxKey; import org.bson.types.MinKey; import org.bson.types.ObjectId; import org.bson.types.Symbol; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Map; CLASS_BSON_CONVERTER_MAP.put(Long.class, BsonLongConverter.getInstance()); CLASS_BSON_CONVERTER_MAP.put(long.class, BsonLongConverter.getInstance()); CLASS_BSON_CONVERTER_MAP.put(BsonTimestamp.class, BsonTimestampConverter.getInstance()); CLASS_BSON_CONVERTER_MAP.put(Decimal128.class, BsonBigDecimalConverter.getInstance()); CLASS_BSON_CONVERTER_MAP.put(MinKey.class, BsonMinKeyConverter.getInstance()); CLASS_BSON_CONVERTER_MAP.put(MaxKey.class, BsonMaxKeyConverter.getInstance()); CLASS_BSON_CONVERTER_MAP.put(StringObjectId.class, BsonStringObjectIdConverter.getInstance()); } static BsonValueConverter getValueConverterByBsonType(BsonType bsonType) { Class<?> clazz = getClazzByBsonType(bsonType); return (BsonValueConverter) CLASS_BSON_CONVERTER_MAP.get(clazz); } static <T, V extends BsonValue> BsonValueConverter<T, V> getValueConverterByClazz(Class<?> clazz) { return (BsonValueConverter<T, V>) CLASS_BSON_CONVERTER_MAP.get(clazz); } static BsonByteIOConverter getByteIOConverterByBsonType(BsonType bsonType) { Class<?> clazz = getClazzByBsonType(bsonType); return (BsonByteIOConverter) CLASS_BSON_CONVERTER_MAP.get(clazz); } static <T> BsonByteIOConverter<T> getByteIOConverterByClazz(Class<?> clazz) { return (BsonByteIOConverter<T>) CLASS_BSON_CONVERTER_MAP.get(clazz); } private static Class<?> getClazzByBsonType(BsonType bsonType) { Class<?> clazz = BSON_TYPE_CLASS_MAP.get(bsonType); if (clazz == null) {
throw new BsonMapperConverterException("can not find BsonValueConverter for bsonType:" + bsonType);
welkinbai/BsonMapper
src/main/java/me/welkinbai/bsonmapper/MapperLayerCounter.java
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // }
import me.welkinbai.bsonmapper.exception.BsonMapperConverterException;
package me.welkinbai.bsonmapper; /** * Created by welkinbai on 2017/6/17. */ public enum MapperLayerCounter { MAPPER_LAYER_COUNTER; private final ThreadLocal<Integer> threadLocalCount = new ThreadLocal<Integer>(); public void addCount(BsonMapperConfig bsonMapperConfig) { Integer count = threadLocalCount.get(); if (count == null) { threadLocalCount.set(1); return; } count++; if (count > bsonMapperConfig.getMaxMapperLayerNum()) { threadLocalCount.remove();
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/me/welkinbai/bsonmapper/MapperLayerCounter.java import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; package me.welkinbai.bsonmapper; /** * Created by welkinbai on 2017/6/17. */ public enum MapperLayerCounter { MAPPER_LAYER_COUNTER; private final ThreadLocal<Integer> threadLocalCount = new ThreadLocal<Integer>(); public void addCount(BsonMapperConfig bsonMapperConfig) { Integer count = threadLocalCount.get(); if (count == null) { threadLocalCount.set(1); return; } count++; if (count > bsonMapperConfig.getMaxMapperLayerNum()) { threadLocalCount.remove();
throw new BsonMapperConverterException(String.format("exceed max layer in bsonMapperConfig.current layer is %s.max layer is %s", count, bsonMapperConfig.getMaxMapperLayerNum()));
welkinbai/BsonMapper
src/main/java/me/welkinbai/bsonmapper/DefaultBsonMapper.java
// Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static void checkIsSupportClazz(Class<?> targetClazz, String message) { // if (BsonValueConverterRepertory.isValueSupportClazz(targetClazz)) { // throw new BsonMapperConverterException(message); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static void checkNotNull(Object object, String message) { // if (object == null) { // throw new NullPointerException(message); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static boolean isStrEmpty(String str) { // return str == null || str.length() == 0; // }
import org.bson.BsonBinaryReader; import org.bson.BsonBinaryWriter; import org.bson.BsonBinaryWriterSettings; import org.bson.BsonDocument; import org.bson.BsonValue; import org.bson.BsonWriter; import org.bson.BsonWriterSettings; import org.bson.Document; import org.bson.codecs.DocumentCodec; import org.bson.codecs.configuration.CodecRegistries; import org.bson.io.BasicOutputBuffer; import org.bson.io.BsonInput; import org.bson.io.BsonOutput; import org.bson.json.JsonReader; import org.bson.json.JsonWriter; import org.bson.json.JsonWriterSettings; import java.io.StringWriter; import java.nio.ByteBuffer; import java.util.Map.Entry; import static me.welkinbai.bsonmapper.Utils.checkIsSupportClazz; import static me.welkinbai.bsonmapper.Utils.checkNotNull; import static me.welkinbai.bsonmapper.Utils.isStrEmpty;
package me.welkinbai.bsonmapper; /** * Created by welkinbai on 2017/3/21. */ public class DefaultBsonMapper implements BsonMapper, MongoBsonMapper { private static final String NOT_NULL_MSG = "targetClazz should not be Null!"; private static final String NOT_SUPPORT_CLAZZ_MSG = "targetClazz should not be a common value Clazz or Collection/Array Clazz.It should be a real Object.clazz name:"; private final BsonMapperConfig bsonMapperConfig; private DefaultBsonMapper(BsonMapperConfig bsonMapperConfig) { this.bsonMapperConfig = bsonMapperConfig; } public static BsonMapper defaultBsonMapper() { return new DefaultBsonMapper(BsonMapperConfig.DEFALUT); } public static BsonMapper defaultBsonMapper(BsonMapperConfig userCustomizedConfig) { return new DefaultBsonMapper(userCustomizedConfig); } public static MongoBsonMapper defaultMongoBsonMapper() { return new DefaultBsonMapper(BsonMapperConfig.DEFALUT); } public static MongoBsonMapper defaultMongoBsonMapper(BsonMapperConfig userCustomizedConfig) { return new DefaultBsonMapper(userCustomizedConfig); } @Override public <T> T readFrom(BsonDocument bsonDocument, Class<T> targetClazz) { if (bsonDocument == null) { return null; }
// Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static void checkIsSupportClazz(Class<?> targetClazz, String message) { // if (BsonValueConverterRepertory.isValueSupportClazz(targetClazz)) { // throw new BsonMapperConverterException(message); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static void checkNotNull(Object object, String message) { // if (object == null) { // throw new NullPointerException(message); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static boolean isStrEmpty(String str) { // return str == null || str.length() == 0; // } // Path: src/main/java/me/welkinbai/bsonmapper/DefaultBsonMapper.java import org.bson.BsonBinaryReader; import org.bson.BsonBinaryWriter; import org.bson.BsonBinaryWriterSettings; import org.bson.BsonDocument; import org.bson.BsonValue; import org.bson.BsonWriter; import org.bson.BsonWriterSettings; import org.bson.Document; import org.bson.codecs.DocumentCodec; import org.bson.codecs.configuration.CodecRegistries; import org.bson.io.BasicOutputBuffer; import org.bson.io.BsonInput; import org.bson.io.BsonOutput; import org.bson.json.JsonReader; import org.bson.json.JsonWriter; import org.bson.json.JsonWriterSettings; import java.io.StringWriter; import java.nio.ByteBuffer; import java.util.Map.Entry; import static me.welkinbai.bsonmapper.Utils.checkIsSupportClazz; import static me.welkinbai.bsonmapper.Utils.checkNotNull; import static me.welkinbai.bsonmapper.Utils.isStrEmpty; package me.welkinbai.bsonmapper; /** * Created by welkinbai on 2017/3/21. */ public class DefaultBsonMapper implements BsonMapper, MongoBsonMapper { private static final String NOT_NULL_MSG = "targetClazz should not be Null!"; private static final String NOT_SUPPORT_CLAZZ_MSG = "targetClazz should not be a common value Clazz or Collection/Array Clazz.It should be a real Object.clazz name:"; private final BsonMapperConfig bsonMapperConfig; private DefaultBsonMapper(BsonMapperConfig bsonMapperConfig) { this.bsonMapperConfig = bsonMapperConfig; } public static BsonMapper defaultBsonMapper() { return new DefaultBsonMapper(BsonMapperConfig.DEFALUT); } public static BsonMapper defaultBsonMapper(BsonMapperConfig userCustomizedConfig) { return new DefaultBsonMapper(userCustomizedConfig); } public static MongoBsonMapper defaultMongoBsonMapper() { return new DefaultBsonMapper(BsonMapperConfig.DEFALUT); } public static MongoBsonMapper defaultMongoBsonMapper(BsonMapperConfig userCustomizedConfig) { return new DefaultBsonMapper(userCustomizedConfig); } @Override public <T> T readFrom(BsonDocument bsonDocument, Class<T> targetClazz) { if (bsonDocument == null) { return null; }
checkNotNull(targetClazz, NOT_NULL_MSG);
welkinbai/BsonMapper
src/main/java/me/welkinbai/bsonmapper/DefaultBsonMapper.java
// Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static void checkIsSupportClazz(Class<?> targetClazz, String message) { // if (BsonValueConverterRepertory.isValueSupportClazz(targetClazz)) { // throw new BsonMapperConverterException(message); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static void checkNotNull(Object object, String message) { // if (object == null) { // throw new NullPointerException(message); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static boolean isStrEmpty(String str) { // return str == null || str.length() == 0; // }
import org.bson.BsonBinaryReader; import org.bson.BsonBinaryWriter; import org.bson.BsonBinaryWriterSettings; import org.bson.BsonDocument; import org.bson.BsonValue; import org.bson.BsonWriter; import org.bson.BsonWriterSettings; import org.bson.Document; import org.bson.codecs.DocumentCodec; import org.bson.codecs.configuration.CodecRegistries; import org.bson.io.BasicOutputBuffer; import org.bson.io.BsonInput; import org.bson.io.BsonOutput; import org.bson.json.JsonReader; import org.bson.json.JsonWriter; import org.bson.json.JsonWriterSettings; import java.io.StringWriter; import java.nio.ByteBuffer; import java.util.Map.Entry; import static me.welkinbai.bsonmapper.Utils.checkIsSupportClazz; import static me.welkinbai.bsonmapper.Utils.checkNotNull; import static me.welkinbai.bsonmapper.Utils.isStrEmpty;
package me.welkinbai.bsonmapper; /** * Created by welkinbai on 2017/3/21. */ public class DefaultBsonMapper implements BsonMapper, MongoBsonMapper { private static final String NOT_NULL_MSG = "targetClazz should not be Null!"; private static final String NOT_SUPPORT_CLAZZ_MSG = "targetClazz should not be a common value Clazz or Collection/Array Clazz.It should be a real Object.clazz name:"; private final BsonMapperConfig bsonMapperConfig; private DefaultBsonMapper(BsonMapperConfig bsonMapperConfig) { this.bsonMapperConfig = bsonMapperConfig; } public static BsonMapper defaultBsonMapper() { return new DefaultBsonMapper(BsonMapperConfig.DEFALUT); } public static BsonMapper defaultBsonMapper(BsonMapperConfig userCustomizedConfig) { return new DefaultBsonMapper(userCustomizedConfig); } public static MongoBsonMapper defaultMongoBsonMapper() { return new DefaultBsonMapper(BsonMapperConfig.DEFALUT); } public static MongoBsonMapper defaultMongoBsonMapper(BsonMapperConfig userCustomizedConfig) { return new DefaultBsonMapper(userCustomizedConfig); } @Override public <T> T readFrom(BsonDocument bsonDocument, Class<T> targetClazz) { if (bsonDocument == null) { return null; } checkNotNull(targetClazz, NOT_NULL_MSG);
// Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static void checkIsSupportClazz(Class<?> targetClazz, String message) { // if (BsonValueConverterRepertory.isValueSupportClazz(targetClazz)) { // throw new BsonMapperConverterException(message); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static void checkNotNull(Object object, String message) { // if (object == null) { // throw new NullPointerException(message); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static boolean isStrEmpty(String str) { // return str == null || str.length() == 0; // } // Path: src/main/java/me/welkinbai/bsonmapper/DefaultBsonMapper.java import org.bson.BsonBinaryReader; import org.bson.BsonBinaryWriter; import org.bson.BsonBinaryWriterSettings; import org.bson.BsonDocument; import org.bson.BsonValue; import org.bson.BsonWriter; import org.bson.BsonWriterSettings; import org.bson.Document; import org.bson.codecs.DocumentCodec; import org.bson.codecs.configuration.CodecRegistries; import org.bson.io.BasicOutputBuffer; import org.bson.io.BsonInput; import org.bson.io.BsonOutput; import org.bson.json.JsonReader; import org.bson.json.JsonWriter; import org.bson.json.JsonWriterSettings; import java.io.StringWriter; import java.nio.ByteBuffer; import java.util.Map.Entry; import static me.welkinbai.bsonmapper.Utils.checkIsSupportClazz; import static me.welkinbai.bsonmapper.Utils.checkNotNull; import static me.welkinbai.bsonmapper.Utils.isStrEmpty; package me.welkinbai.bsonmapper; /** * Created by welkinbai on 2017/3/21. */ public class DefaultBsonMapper implements BsonMapper, MongoBsonMapper { private static final String NOT_NULL_MSG = "targetClazz should not be Null!"; private static final String NOT_SUPPORT_CLAZZ_MSG = "targetClazz should not be a common value Clazz or Collection/Array Clazz.It should be a real Object.clazz name:"; private final BsonMapperConfig bsonMapperConfig; private DefaultBsonMapper(BsonMapperConfig bsonMapperConfig) { this.bsonMapperConfig = bsonMapperConfig; } public static BsonMapper defaultBsonMapper() { return new DefaultBsonMapper(BsonMapperConfig.DEFALUT); } public static BsonMapper defaultBsonMapper(BsonMapperConfig userCustomizedConfig) { return new DefaultBsonMapper(userCustomizedConfig); } public static MongoBsonMapper defaultMongoBsonMapper() { return new DefaultBsonMapper(BsonMapperConfig.DEFALUT); } public static MongoBsonMapper defaultMongoBsonMapper(BsonMapperConfig userCustomizedConfig) { return new DefaultBsonMapper(userCustomizedConfig); } @Override public <T> T readFrom(BsonDocument bsonDocument, Class<T> targetClazz) { if (bsonDocument == null) { return null; } checkNotNull(targetClazz, NOT_NULL_MSG);
checkIsSupportClazz(targetClazz, NOT_SUPPORT_CLAZZ_MSG + targetClazz.getName());
welkinbai/BsonMapper
src/main/java/me/welkinbai/bsonmapper/DefaultBsonMapper.java
// Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static void checkIsSupportClazz(Class<?> targetClazz, String message) { // if (BsonValueConverterRepertory.isValueSupportClazz(targetClazz)) { // throw new BsonMapperConverterException(message); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static void checkNotNull(Object object, String message) { // if (object == null) { // throw new NullPointerException(message); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static boolean isStrEmpty(String str) { // return str == null || str.length() == 0; // }
import org.bson.BsonBinaryReader; import org.bson.BsonBinaryWriter; import org.bson.BsonBinaryWriterSettings; import org.bson.BsonDocument; import org.bson.BsonValue; import org.bson.BsonWriter; import org.bson.BsonWriterSettings; import org.bson.Document; import org.bson.codecs.DocumentCodec; import org.bson.codecs.configuration.CodecRegistries; import org.bson.io.BasicOutputBuffer; import org.bson.io.BsonInput; import org.bson.io.BsonOutput; import org.bson.json.JsonReader; import org.bson.json.JsonWriter; import org.bson.json.JsonWriterSettings; import java.io.StringWriter; import java.nio.ByteBuffer; import java.util.Map.Entry; import static me.welkinbai.bsonmapper.Utils.checkIsSupportClazz; import static me.welkinbai.bsonmapper.Utils.checkNotNull; import static me.welkinbai.bsonmapper.Utils.isStrEmpty;
} checkNotNull(targetClazz, NOT_NULL_MSG); checkIsSupportClazz(targetClazz, NOT_SUPPORT_CLAZZ_MSG + targetClazz.getName()); return BsonValueConverterRepertory.getBsonDocumentConverter().decode(bsonDocument, targetClazz, bsonMapperConfig); } @Override public <T> T readFrom(ByteBuffer byteBuffer, Class<T> targetClazz) { if (byteBuffer == null) { return null; } checkNotNull(targetClazz, NOT_NULL_MSG); checkIsSupportClazz(targetClazz, NOT_SUPPORT_CLAZZ_MSG + targetClazz.getName()); BsonBinaryReader bsonBinaryReader = new BsonBinaryReader(byteBuffer); return BsonValueConverterRepertory.getBsonDocumentConverter().decode(bsonBinaryReader, targetClazz, bsonMapperConfig); } @Override public <T> T readFrom(BsonInput bsonInput, Class<T> targetClazz) { if (bsonInput == null) { return null; } checkNotNull(targetClazz, NOT_NULL_MSG); checkIsSupportClazz(targetClazz, NOT_SUPPORT_CLAZZ_MSG + targetClazz.getName()); BsonBinaryReader bsonBinaryReader = new BsonBinaryReader(bsonInput); return BsonValueConverterRepertory.getBsonDocumentConverter().decode(bsonBinaryReader, targetClazz, bsonMapperConfig); } @Override public <T> T readFrom(String jsonString, Class<T> targetClazz) {
// Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static void checkIsSupportClazz(Class<?> targetClazz, String message) { // if (BsonValueConverterRepertory.isValueSupportClazz(targetClazz)) { // throw new BsonMapperConverterException(message); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static void checkNotNull(Object object, String message) { // if (object == null) { // throw new NullPointerException(message); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static boolean isStrEmpty(String str) { // return str == null || str.length() == 0; // } // Path: src/main/java/me/welkinbai/bsonmapper/DefaultBsonMapper.java import org.bson.BsonBinaryReader; import org.bson.BsonBinaryWriter; import org.bson.BsonBinaryWriterSettings; import org.bson.BsonDocument; import org.bson.BsonValue; import org.bson.BsonWriter; import org.bson.BsonWriterSettings; import org.bson.Document; import org.bson.codecs.DocumentCodec; import org.bson.codecs.configuration.CodecRegistries; import org.bson.io.BasicOutputBuffer; import org.bson.io.BsonInput; import org.bson.io.BsonOutput; import org.bson.json.JsonReader; import org.bson.json.JsonWriter; import org.bson.json.JsonWriterSettings; import java.io.StringWriter; import java.nio.ByteBuffer; import java.util.Map.Entry; import static me.welkinbai.bsonmapper.Utils.checkIsSupportClazz; import static me.welkinbai.bsonmapper.Utils.checkNotNull; import static me.welkinbai.bsonmapper.Utils.isStrEmpty; } checkNotNull(targetClazz, NOT_NULL_MSG); checkIsSupportClazz(targetClazz, NOT_SUPPORT_CLAZZ_MSG + targetClazz.getName()); return BsonValueConverterRepertory.getBsonDocumentConverter().decode(bsonDocument, targetClazz, bsonMapperConfig); } @Override public <T> T readFrom(ByteBuffer byteBuffer, Class<T> targetClazz) { if (byteBuffer == null) { return null; } checkNotNull(targetClazz, NOT_NULL_MSG); checkIsSupportClazz(targetClazz, NOT_SUPPORT_CLAZZ_MSG + targetClazz.getName()); BsonBinaryReader bsonBinaryReader = new BsonBinaryReader(byteBuffer); return BsonValueConverterRepertory.getBsonDocumentConverter().decode(bsonBinaryReader, targetClazz, bsonMapperConfig); } @Override public <T> T readFrom(BsonInput bsonInput, Class<T> targetClazz) { if (bsonInput == null) { return null; } checkNotNull(targetClazz, NOT_NULL_MSG); checkIsSupportClazz(targetClazz, NOT_SUPPORT_CLAZZ_MSG + targetClazz.getName()); BsonBinaryReader bsonBinaryReader = new BsonBinaryReader(bsonInput); return BsonValueConverterRepertory.getBsonDocumentConverter().decode(bsonBinaryReader, targetClazz, bsonMapperConfig); } @Override public <T> T readFrom(String jsonString, Class<T> targetClazz) {
if (isStrEmpty(jsonString)) {
welkinbai/BsonMapper
src/main/java/me/welkinbai/bsonmapper/Utils.java
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // }
import me.welkinbai.bsonmapper.annotations.BsonArrayField; import me.welkinbai.bsonmapper.annotations.BsonField; import me.welkinbai.bsonmapper.annotations.BsonIgnore; import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; import org.bson.types.ObjectId; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import static com.sun.javafx.fxml.BeanAdapter.IS_PREFIX;
return IS_PREFIX + name.substring(0, 1).toUpperCase() + name.substring(1); } public static void checkNotNull(Object object, String message) { if (object == null) { throw new NullPointerException(message); } } public static List<Field> getAllField(Class<?> tClass) { Field[] tClassDeclaredFields = tClass.getDeclaredFields(); List<Field> result = new ArrayList<Field>(); result.addAll(Arrays.asList(tClassDeclaredFields)); Class<?> superClass; while ((superClass = tClass.getSuperclass()) != null) { for (Field field : superClass.getDeclaredFields()) { int modifiers = field.getModifiers(); if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) { result.add(field); } } tClass = superClass; } return result; } public static <T> T newInstanceByClazz(Class<T> targetClazz) { try { return targetClazz.newInstance(); } catch (InstantiationException e) {
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java import me.welkinbai.bsonmapper.annotations.BsonArrayField; import me.welkinbai.bsonmapper.annotations.BsonField; import me.welkinbai.bsonmapper.annotations.BsonIgnore; import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; import org.bson.types.ObjectId; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import static com.sun.javafx.fxml.BeanAdapter.IS_PREFIX; return IS_PREFIX + name.substring(0, 1).toUpperCase() + name.substring(1); } public static void checkNotNull(Object object, String message) { if (object == null) { throw new NullPointerException(message); } } public static List<Field> getAllField(Class<?> tClass) { Field[] tClassDeclaredFields = tClass.getDeclaredFields(); List<Field> result = new ArrayList<Field>(); result.addAll(Arrays.asList(tClassDeclaredFields)); Class<?> superClass; while ((superClass = tClass.getSuperclass()) != null) { for (Field field : superClass.getDeclaredFields()) { int modifiers = field.getModifiers(); if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) { result.add(field); } } tClass = superClass; } return result; } public static <T> T newInstanceByClazz(Class<T> targetClazz) { try { return targetClazz.newInstance(); } catch (InstantiationException e) {
throw new BsonMapperConverterException("should never happen.", e);
welkinbai/BsonMapper
src/main/java/me/welkinbai/bsonmapper/BsonCodeWithScopeConverter.java
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // }
import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; import org.bson.BsonDocument; import org.bson.BsonJavaScriptWithScope; import org.bson.BsonReader; import org.bson.BsonValue; import org.bson.BsonWriter; import org.bson.Document; import org.bson.types.CodeWithScope;
package me.welkinbai.bsonmapper; /** * Created by welkinbai on 2017/3/25. */ final class BsonCodeWithScopeConverter extends AbstractBsonConverter<CodeWithScope, BsonJavaScriptWithScope> { private BsonCodeWithScopeConverter() { } public static BsonCodeWithScopeConverter getInstance() { return new BsonCodeWithScopeConverter(); } @Override public CodeWithScope decode(BsonValue bsonValue) { BsonJavaScriptWithScope bsonJavaScriptWithScope = bsonValue.asJavaScriptWithScope(); return new CodeWithScope(bsonJavaScriptWithScope.getCode(), Document.parse(bsonJavaScriptWithScope.getScope().toJson())); } @Override public BsonJavaScriptWithScope encode(CodeWithScope object) { return new BsonJavaScriptWithScope(object.getCode(), BsonDocument.parse(object.getScope().toJson())); } /** * JavaScriptWithScope seems a "live" Javascript function in a MongoDB which refers to variables which exist outside the function. * detail:https://stackoverflow.com/questions/39155290/what-is-javascript-with-scope-in-mongodb * still can't support convert this type because don't know how it is work. * * @param bsonReader * @return */ @Override public CodeWithScope decode(BsonReader bsonReader) {
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/me/welkinbai/bsonmapper/BsonCodeWithScopeConverter.java import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; import org.bson.BsonDocument; import org.bson.BsonJavaScriptWithScope; import org.bson.BsonReader; import org.bson.BsonValue; import org.bson.BsonWriter; import org.bson.Document; import org.bson.types.CodeWithScope; package me.welkinbai.bsonmapper; /** * Created by welkinbai on 2017/3/25. */ final class BsonCodeWithScopeConverter extends AbstractBsonConverter<CodeWithScope, BsonJavaScriptWithScope> { private BsonCodeWithScopeConverter() { } public static BsonCodeWithScopeConverter getInstance() { return new BsonCodeWithScopeConverter(); } @Override public CodeWithScope decode(BsonValue bsonValue) { BsonJavaScriptWithScope bsonJavaScriptWithScope = bsonValue.asJavaScriptWithScope(); return new CodeWithScope(bsonJavaScriptWithScope.getCode(), Document.parse(bsonJavaScriptWithScope.getScope().toJson())); } @Override public BsonJavaScriptWithScope encode(CodeWithScope object) { return new BsonJavaScriptWithScope(object.getCode(), BsonDocument.parse(object.getScope().toJson())); } /** * JavaScriptWithScope seems a "live" Javascript function in a MongoDB which refers to variables which exist outside the function. * detail:https://stackoverflow.com/questions/39155290/what-is-javascript-with-scope-in-mongodb * still can't support convert this type because don't know how it is work. * * @param bsonReader * @return */ @Override public CodeWithScope decode(BsonReader bsonReader) {
throw new BsonMapperConverterException("could not convert to CodeWithScope when use BsonBinaryReader.BsonBinaryReader haven't gave us scope.");
welkinbai/BsonMapper
src/main/java/me/welkinbai/bsonmapper/BsonArrayConverter.java
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // }
import me.welkinbai.bsonmapper.annotations.BsonArrayField; import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonReader; import org.bson.BsonType; import org.bson.BsonValue; import org.bson.BsonWriter; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import static me.welkinbai.bsonmapper.MapperLayerCounter.MAPPER_LAYER_COUNTER;
package me.welkinbai.bsonmapper; /** * Created by welkinbai on 2017/3/23. */ final class BsonArrayConverter { private BsonArrayConverter() { } static BsonArrayConverter getInstance() { return new BsonArrayConverter(); } Object decode(BsonArray bsonArray, Field field, BsonMapperConfig bsonMapperConfig) { MAPPER_LAYER_COUNTER.addCount(bsonMapperConfig); try { Class<?> fieldType = field.getType(); if (fieldType.isArray()) { return handleArrayForBsonArray(bsonArray, field, bsonMapperConfig); } else if (Collection.class.isAssignableFrom(fieldType)) { return handleCollectionForBsonArray(bsonArray, field, bsonMapperConfig); } else {
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/me/welkinbai/bsonmapper/BsonArrayConverter.java import me.welkinbai.bsonmapper.annotations.BsonArrayField; import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonReader; import org.bson.BsonType; import org.bson.BsonValue; import org.bson.BsonWriter; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import static me.welkinbai.bsonmapper.MapperLayerCounter.MAPPER_LAYER_COUNTER; package me.welkinbai.bsonmapper; /** * Created by welkinbai on 2017/3/23. */ final class BsonArrayConverter { private BsonArrayConverter() { } static BsonArrayConverter getInstance() { return new BsonArrayConverter(); } Object decode(BsonArray bsonArray, Field field, BsonMapperConfig bsonMapperConfig) { MAPPER_LAYER_COUNTER.addCount(bsonMapperConfig); try { Class<?> fieldType = field.getType(); if (fieldType.isArray()) { return handleArrayForBsonArray(bsonArray, field, bsonMapperConfig); } else if (Collection.class.isAssignableFrom(fieldType)) { return handleCollectionForBsonArray(bsonArray, field, bsonMapperConfig); } else {
throw new BsonMapperConverterException(
welkinbai/BsonMapper
src/main/java/me/welkinbai/bsonmapper/BsonDocumentConverter.java
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static String getBsonName(Field field) { // String bsonName = field.getName(); // BsonField bsonField = field.getAnnotation(BsonField.class); // if (bsonField != null && !isStrEmpty(bsonField.value())) { // bsonName = bsonField.value(); // } // return bsonName; // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static Object getObjectIdByRealType(Class<?> fieldType, ObjectId objectId) { // if (fieldType == String.class || fieldType == StringObjectId.class) { // return objectId.toHexString(); // } else if (fieldType == ObjectId.class) { // return objectId; // } else { // throw new BsonMapperConverterException("BsonValue ObjectId just can be converted to String or ObjectId."); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static boolean isIgnored(Field field) { // BsonIgnore bsonIgnore = field.getAnnotation(BsonIgnore.class); // return bsonIgnore != null; // }
import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonReader; import org.bson.BsonType; import org.bson.BsonValue; import org.bson.BsonWriter; import org.bson.types.ObjectId; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import static me.welkinbai.bsonmapper.MapperLayerCounter.MAPPER_LAYER_COUNTER; import static me.welkinbai.bsonmapper.Utils.getBsonName; import static me.welkinbai.bsonmapper.Utils.getObjectIdByRealType; import static me.welkinbai.bsonmapper.Utils.isIgnored;
package me.welkinbai.bsonmapper; /** * Created by baixiaoxuan on 2017/3/23. */ final class BsonDocumentConverter { private BsonDocumentConverter() { } static BsonDocumentConverter getInstance() { return new BsonDocumentConverter(); } /** * ๅๅบๅˆ—ๅŒ–BsonDocumentๅˆฐPOJO/decode BsonDocument->POJO * * @param bsonDocument * @param targetClazz * @param bsonMapperConfig * @param <T> * @return */ <T> T decode(BsonDocument bsonDocument, Class<T> targetClazz, BsonMapperConfig bsonMapperConfig) { MAPPER_LAYER_COUNTER.addCount(bsonMapperConfig); try { List<Field> allField = Utils.getAllField(targetClazz); T target = Utils.newInstanceByClazz(targetClazz); for (Field field : allField) {
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static String getBsonName(Field field) { // String bsonName = field.getName(); // BsonField bsonField = field.getAnnotation(BsonField.class); // if (bsonField != null && !isStrEmpty(bsonField.value())) { // bsonName = bsonField.value(); // } // return bsonName; // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static Object getObjectIdByRealType(Class<?> fieldType, ObjectId objectId) { // if (fieldType == String.class || fieldType == StringObjectId.class) { // return objectId.toHexString(); // } else if (fieldType == ObjectId.class) { // return objectId; // } else { // throw new BsonMapperConverterException("BsonValue ObjectId just can be converted to String or ObjectId."); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static boolean isIgnored(Field field) { // BsonIgnore bsonIgnore = field.getAnnotation(BsonIgnore.class); // return bsonIgnore != null; // } // Path: src/main/java/me/welkinbai/bsonmapper/BsonDocumentConverter.java import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonReader; import org.bson.BsonType; import org.bson.BsonValue; import org.bson.BsonWriter; import org.bson.types.ObjectId; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import static me.welkinbai.bsonmapper.MapperLayerCounter.MAPPER_LAYER_COUNTER; import static me.welkinbai.bsonmapper.Utils.getBsonName; import static me.welkinbai.bsonmapper.Utils.getObjectIdByRealType; import static me.welkinbai.bsonmapper.Utils.isIgnored; package me.welkinbai.bsonmapper; /** * Created by baixiaoxuan on 2017/3/23. */ final class BsonDocumentConverter { private BsonDocumentConverter() { } static BsonDocumentConverter getInstance() { return new BsonDocumentConverter(); } /** * ๅๅบๅˆ—ๅŒ–BsonDocumentๅˆฐPOJO/decode BsonDocument->POJO * * @param bsonDocument * @param targetClazz * @param bsonMapperConfig * @param <T> * @return */ <T> T decode(BsonDocument bsonDocument, Class<T> targetClazz, BsonMapperConfig bsonMapperConfig) { MAPPER_LAYER_COUNTER.addCount(bsonMapperConfig); try { List<Field> allField = Utils.getAllField(targetClazz); T target = Utils.newInstanceByClazz(targetClazz); for (Field field : allField) {
if (isIgnored(field)) {
welkinbai/BsonMapper
src/main/java/me/welkinbai/bsonmapper/BsonDocumentConverter.java
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static String getBsonName(Field field) { // String bsonName = field.getName(); // BsonField bsonField = field.getAnnotation(BsonField.class); // if (bsonField != null && !isStrEmpty(bsonField.value())) { // bsonName = bsonField.value(); // } // return bsonName; // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static Object getObjectIdByRealType(Class<?> fieldType, ObjectId objectId) { // if (fieldType == String.class || fieldType == StringObjectId.class) { // return objectId.toHexString(); // } else if (fieldType == ObjectId.class) { // return objectId; // } else { // throw new BsonMapperConverterException("BsonValue ObjectId just can be converted to String or ObjectId."); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static boolean isIgnored(Field field) { // BsonIgnore bsonIgnore = field.getAnnotation(BsonIgnore.class); // return bsonIgnore != null; // }
import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonReader; import org.bson.BsonType; import org.bson.BsonValue; import org.bson.BsonWriter; import org.bson.types.ObjectId; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import static me.welkinbai.bsonmapper.MapperLayerCounter.MAPPER_LAYER_COUNTER; import static me.welkinbai.bsonmapper.Utils.getBsonName; import static me.welkinbai.bsonmapper.Utils.getObjectIdByRealType; import static me.welkinbai.bsonmapper.Utils.isIgnored;
package me.welkinbai.bsonmapper; /** * Created by baixiaoxuan on 2017/3/23. */ final class BsonDocumentConverter { private BsonDocumentConverter() { } static BsonDocumentConverter getInstance() { return new BsonDocumentConverter(); } /** * ๅๅบๅˆ—ๅŒ–BsonDocumentๅˆฐPOJO/decode BsonDocument->POJO * * @param bsonDocument * @param targetClazz * @param bsonMapperConfig * @param <T> * @return */ <T> T decode(BsonDocument bsonDocument, Class<T> targetClazz, BsonMapperConfig bsonMapperConfig) { MAPPER_LAYER_COUNTER.addCount(bsonMapperConfig); try { List<Field> allField = Utils.getAllField(targetClazz); T target = Utils.newInstanceByClazz(targetClazz); for (Field field : allField) { if (isIgnored(field)) { continue; }
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static String getBsonName(Field field) { // String bsonName = field.getName(); // BsonField bsonField = field.getAnnotation(BsonField.class); // if (bsonField != null && !isStrEmpty(bsonField.value())) { // bsonName = bsonField.value(); // } // return bsonName; // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static Object getObjectIdByRealType(Class<?> fieldType, ObjectId objectId) { // if (fieldType == String.class || fieldType == StringObjectId.class) { // return objectId.toHexString(); // } else if (fieldType == ObjectId.class) { // return objectId; // } else { // throw new BsonMapperConverterException("BsonValue ObjectId just can be converted to String or ObjectId."); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static boolean isIgnored(Field field) { // BsonIgnore bsonIgnore = field.getAnnotation(BsonIgnore.class); // return bsonIgnore != null; // } // Path: src/main/java/me/welkinbai/bsonmapper/BsonDocumentConverter.java import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonReader; import org.bson.BsonType; import org.bson.BsonValue; import org.bson.BsonWriter; import org.bson.types.ObjectId; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import static me.welkinbai.bsonmapper.MapperLayerCounter.MAPPER_LAYER_COUNTER; import static me.welkinbai.bsonmapper.Utils.getBsonName; import static me.welkinbai.bsonmapper.Utils.getObjectIdByRealType; import static me.welkinbai.bsonmapper.Utils.isIgnored; package me.welkinbai.bsonmapper; /** * Created by baixiaoxuan on 2017/3/23. */ final class BsonDocumentConverter { private BsonDocumentConverter() { } static BsonDocumentConverter getInstance() { return new BsonDocumentConverter(); } /** * ๅๅบๅˆ—ๅŒ–BsonDocumentๅˆฐPOJO/decode BsonDocument->POJO * * @param bsonDocument * @param targetClazz * @param bsonMapperConfig * @param <T> * @return */ <T> T decode(BsonDocument bsonDocument, Class<T> targetClazz, BsonMapperConfig bsonMapperConfig) { MAPPER_LAYER_COUNTER.addCount(bsonMapperConfig); try { List<Field> allField = Utils.getAllField(targetClazz); T target = Utils.newInstanceByClazz(targetClazz); for (Field field : allField) { if (isIgnored(field)) { continue; }
String bsonName = getBsonName(field);
welkinbai/BsonMapper
src/main/java/me/welkinbai/bsonmapper/BsonDocumentConverter.java
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static String getBsonName(Field field) { // String bsonName = field.getName(); // BsonField bsonField = field.getAnnotation(BsonField.class); // if (bsonField != null && !isStrEmpty(bsonField.value())) { // bsonName = bsonField.value(); // } // return bsonName; // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static Object getObjectIdByRealType(Class<?> fieldType, ObjectId objectId) { // if (fieldType == String.class || fieldType == StringObjectId.class) { // return objectId.toHexString(); // } else if (fieldType == ObjectId.class) { // return objectId; // } else { // throw new BsonMapperConverterException("BsonValue ObjectId just can be converted to String or ObjectId."); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static boolean isIgnored(Field field) { // BsonIgnore bsonIgnore = field.getAnnotation(BsonIgnore.class); // return bsonIgnore != null; // }
import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonReader; import org.bson.BsonType; import org.bson.BsonValue; import org.bson.BsonWriter; import org.bson.types.ObjectId; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import static me.welkinbai.bsonmapper.MapperLayerCounter.MAPPER_LAYER_COUNTER; import static me.welkinbai.bsonmapper.Utils.getBsonName; import static me.welkinbai.bsonmapper.Utils.getObjectIdByRealType; import static me.welkinbai.bsonmapper.Utils.isIgnored;
package me.welkinbai.bsonmapper; /** * Created by baixiaoxuan on 2017/3/23. */ final class BsonDocumentConverter { private BsonDocumentConverter() { } static BsonDocumentConverter getInstance() { return new BsonDocumentConverter(); } /** * ๅๅบๅˆ—ๅŒ–BsonDocumentๅˆฐPOJO/decode BsonDocument->POJO * * @param bsonDocument * @param targetClazz * @param bsonMapperConfig * @param <T> * @return */ <T> T decode(BsonDocument bsonDocument, Class<T> targetClazz, BsonMapperConfig bsonMapperConfig) { MAPPER_LAYER_COUNTER.addCount(bsonMapperConfig); try { List<Field> allField = Utils.getAllField(targetClazz); T target = Utils.newInstanceByClazz(targetClazz); for (Field field : allField) { if (isIgnored(field)) { continue; } String bsonName = getBsonName(field); BsonValue bsonValue = bsonDocument.get(bsonName); if (bsonValue == null || bsonValue.isNull()) { continue; } Object javaValue; try { javaValue = getJavaValueFromBsonValue(bsonValue, field, bsonMapperConfig);
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static String getBsonName(Field field) { // String bsonName = field.getName(); // BsonField bsonField = field.getAnnotation(BsonField.class); // if (bsonField != null && !isStrEmpty(bsonField.value())) { // bsonName = bsonField.value(); // } // return bsonName; // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static Object getObjectIdByRealType(Class<?> fieldType, ObjectId objectId) { // if (fieldType == String.class || fieldType == StringObjectId.class) { // return objectId.toHexString(); // } else if (fieldType == ObjectId.class) { // return objectId; // } else { // throw new BsonMapperConverterException("BsonValue ObjectId just can be converted to String or ObjectId."); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static boolean isIgnored(Field field) { // BsonIgnore bsonIgnore = field.getAnnotation(BsonIgnore.class); // return bsonIgnore != null; // } // Path: src/main/java/me/welkinbai/bsonmapper/BsonDocumentConverter.java import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonReader; import org.bson.BsonType; import org.bson.BsonValue; import org.bson.BsonWriter; import org.bson.types.ObjectId; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import static me.welkinbai.bsonmapper.MapperLayerCounter.MAPPER_LAYER_COUNTER; import static me.welkinbai.bsonmapper.Utils.getBsonName; import static me.welkinbai.bsonmapper.Utils.getObjectIdByRealType; import static me.welkinbai.bsonmapper.Utils.isIgnored; package me.welkinbai.bsonmapper; /** * Created by baixiaoxuan on 2017/3/23. */ final class BsonDocumentConverter { private BsonDocumentConverter() { } static BsonDocumentConverter getInstance() { return new BsonDocumentConverter(); } /** * ๅๅบๅˆ—ๅŒ–BsonDocumentๅˆฐPOJO/decode BsonDocument->POJO * * @param bsonDocument * @param targetClazz * @param bsonMapperConfig * @param <T> * @return */ <T> T decode(BsonDocument bsonDocument, Class<T> targetClazz, BsonMapperConfig bsonMapperConfig) { MAPPER_LAYER_COUNTER.addCount(bsonMapperConfig); try { List<Field> allField = Utils.getAllField(targetClazz); T target = Utils.newInstanceByClazz(targetClazz); for (Field field : allField) { if (isIgnored(field)) { continue; } String bsonName = getBsonName(field); BsonValue bsonValue = bsonDocument.get(bsonName); if (bsonValue == null || bsonValue.isNull()) { continue; } Object javaValue; try { javaValue = getJavaValueFromBsonValue(bsonValue, field, bsonMapperConfig);
} catch (BsonMapperConverterException e) {
welkinbai/BsonMapper
src/main/java/me/welkinbai/bsonmapper/BsonDocumentConverter.java
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static String getBsonName(Field field) { // String bsonName = field.getName(); // BsonField bsonField = field.getAnnotation(BsonField.class); // if (bsonField != null && !isStrEmpty(bsonField.value())) { // bsonName = bsonField.value(); // } // return bsonName; // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static Object getObjectIdByRealType(Class<?> fieldType, ObjectId objectId) { // if (fieldType == String.class || fieldType == StringObjectId.class) { // return objectId.toHexString(); // } else if (fieldType == ObjectId.class) { // return objectId; // } else { // throw new BsonMapperConverterException("BsonValue ObjectId just can be converted to String or ObjectId."); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static boolean isIgnored(Field field) { // BsonIgnore bsonIgnore = field.getAnnotation(BsonIgnore.class); // return bsonIgnore != null; // }
import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonReader; import org.bson.BsonType; import org.bson.BsonValue; import org.bson.BsonWriter; import org.bson.types.ObjectId; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import static me.welkinbai.bsonmapper.MapperLayerCounter.MAPPER_LAYER_COUNTER; import static me.welkinbai.bsonmapper.Utils.getBsonName; import static me.welkinbai.bsonmapper.Utils.getObjectIdByRealType; import static me.welkinbai.bsonmapper.Utils.isIgnored;
continue; } String bsonName = getBsonName(field); BsonValue bsonValue = bsonDocument.get(bsonName); if (bsonValue == null || bsonValue.isNull()) { continue; } Object javaValue; try { javaValue = getJavaValueFromBsonValue(bsonValue, field, bsonMapperConfig); } catch (BsonMapperConverterException e) { throw new BsonMapperConverterException("error when try to get java value from Bson.BsonName:" + bsonName, e); } setJavaValueToField(targetClazz, target, field, javaValue); } return target; } finally { MAPPER_LAYER_COUNTER.reduceCount(); } } private Object getJavaValueFromBsonValue(BsonValue bsonValue, Field field, BsonMapperConfig bsonMapperConfig) { if (bsonValue.isArray()) { return BsonValueConverterRepertory.getBsonArrayConverter().decode(bsonValue.asArray(), field, bsonMapperConfig); } if (bsonValue.isDocument()) { return BsonValueConverterRepertory.getBsonDocumentConverter().decode(bsonValue.asDocument(), field.getType(), bsonMapperConfig); } if (bsonValue.isObjectId() && Utils.fieldIsObjectId(field)) { ObjectId objectId = (ObjectId) BsonValueConverterRepertory.getValueConverterByBsonType(bsonValue.getBsonType()).decode(bsonValue);
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static String getBsonName(Field field) { // String bsonName = field.getName(); // BsonField bsonField = field.getAnnotation(BsonField.class); // if (bsonField != null && !isStrEmpty(bsonField.value())) { // bsonName = bsonField.value(); // } // return bsonName; // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static Object getObjectIdByRealType(Class<?> fieldType, ObjectId objectId) { // if (fieldType == String.class || fieldType == StringObjectId.class) { // return objectId.toHexString(); // } else if (fieldType == ObjectId.class) { // return objectId; // } else { // throw new BsonMapperConverterException("BsonValue ObjectId just can be converted to String or ObjectId."); // } // } // // Path: src/main/java/me/welkinbai/bsonmapper/Utils.java // public static boolean isIgnored(Field field) { // BsonIgnore bsonIgnore = field.getAnnotation(BsonIgnore.class); // return bsonIgnore != null; // } // Path: src/main/java/me/welkinbai/bsonmapper/BsonDocumentConverter.java import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonReader; import org.bson.BsonType; import org.bson.BsonValue; import org.bson.BsonWriter; import org.bson.types.ObjectId; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import static me.welkinbai.bsonmapper.MapperLayerCounter.MAPPER_LAYER_COUNTER; import static me.welkinbai.bsonmapper.Utils.getBsonName; import static me.welkinbai.bsonmapper.Utils.getObjectIdByRealType; import static me.welkinbai.bsonmapper.Utils.isIgnored; continue; } String bsonName = getBsonName(field); BsonValue bsonValue = bsonDocument.get(bsonName); if (bsonValue == null || bsonValue.isNull()) { continue; } Object javaValue; try { javaValue = getJavaValueFromBsonValue(bsonValue, field, bsonMapperConfig); } catch (BsonMapperConverterException e) { throw new BsonMapperConverterException("error when try to get java value from Bson.BsonName:" + bsonName, e); } setJavaValueToField(targetClazz, target, field, javaValue); } return target; } finally { MAPPER_LAYER_COUNTER.reduceCount(); } } private Object getJavaValueFromBsonValue(BsonValue bsonValue, Field field, BsonMapperConfig bsonMapperConfig) { if (bsonValue.isArray()) { return BsonValueConverterRepertory.getBsonArrayConverter().decode(bsonValue.asArray(), field, bsonMapperConfig); } if (bsonValue.isDocument()) { return BsonValueConverterRepertory.getBsonDocumentConverter().decode(bsonValue.asDocument(), field.getType(), bsonMapperConfig); } if (bsonValue.isObjectId() && Utils.fieldIsObjectId(field)) { ObjectId objectId = (ObjectId) BsonValueConverterRepertory.getValueConverterByBsonType(bsonValue.getBsonType()).decode(bsonValue);
return getObjectIdByRealType(field.getType(), objectId);
welkinbai/BsonMapper
src/main/java/me/welkinbai/bsonmapper/BsonUndefinedConverter.java
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // }
import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; import org.bson.BsonReader; import org.bson.BsonUndefined; import org.bson.BsonValue; import org.bson.BsonWriter;
package me.welkinbai.bsonmapper; /** * Created by welkinbai on 2017/3/25. */ final class BsonUndefinedConverter extends AbstractBsonConverter<BsonUndefined, BsonUndefined> { private BsonUndefinedConverter() { } public static BsonUndefinedConverter getInstance() { return new BsonUndefinedConverter(); } @Override public BsonUndefined decode(BsonValue bsonValue) {
// Path: src/main/java/me/welkinbai/bsonmapper/exception/BsonMapperConverterException.java // public class BsonMapperConverterException extends RuntimeException { // // public BsonMapperConverterException() { // super(); // } // // public BsonMapperConverterException(String message) { // super(message); // } // // public BsonMapperConverterException(String message, Throwable cause) { // super(message, cause); // } // // public BsonMapperConverterException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/me/welkinbai/bsonmapper/BsonUndefinedConverter.java import me.welkinbai.bsonmapper.exception.BsonMapperConverterException; import org.bson.BsonReader; import org.bson.BsonUndefined; import org.bson.BsonValue; import org.bson.BsonWriter; package me.welkinbai.bsonmapper; /** * Created by welkinbai on 2017/3/25. */ final class BsonUndefinedConverter extends AbstractBsonConverter<BsonUndefined, BsonUndefined> { private BsonUndefinedConverter() { } public static BsonUndefinedConverter getInstance() { return new BsonUndefinedConverter(); } @Override public BsonUndefined decode(BsonValue bsonValue) {
throw new BsonMapperConverterException("BsonUndefined type is not support");
bitcraze/crazyflie-android-client
src/se/bitcraze/crazyflie/lib/toc/TocCache.java
// Path: src/se/bitcraze/crazyflie/lib/crtp/CrtpPort.java // public enum CrtpPort { // CONSOLE(0), // PARAMETERS(2), // COMMANDER(3), // MEMORY(4), // LOGGING(5), // COMMANDER_GENERIC(7), // DEBUGDRIVER(14), // LINKCTRL(15), // ALL(255), // UNKNOWN(-1); //FIXME // // private byte mNumber; // // private CrtpPort(int number) { // this.mNumber = (byte) number; // } // // /** // * Get the number associated with this port. // * // * @return the number of the port // */ // public byte getNumber() { // return mNumber; // } // // /** // * Get the port with a specific number. // * // * @param number // * the number of the port. // * @return the port or <code>null</code> if no port with the specified number exists. // */ // public static CrtpPort getByNumber(byte number) { // for (CrtpPort p : CrtpPort.values()) { // if (p.getNumber() == number) { // return p; // } // } // return null; // } // }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import se.bitcraze.crazyflie.lib.crtp.CrtpPort; import java.io.File; import java.io.FilenameFilter; import java.io.IOException;
/** * || ____ _ __ * +------+ / __ )(_) /_______________ _____ ___ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ * * Copyright (C) 2015 Bitcraze AB * * Crazyflie Nano Quadcopter Client * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package se.bitcraze.crazyflie.lib.toc; /** * Access to TOC cache. To turn off the cache functionality don't supply any directories. * * Heavily based on toccache.py * * */ public class TocCache { final Logger mLogger = LoggerFactory.getLogger("TocCache"); private List<File> mCacheFiles = new ArrayList<File>(); private File mCacheDir = null; private static final String PARAM_CACHE_DIR = "paramCache"; private static final String LOG_CACHE_DIR = "logCache"; private ObjectMapper mMapper = new ObjectMapper(); // can reuse, share globally public TocCache(File cacheDir) { this.mCacheDir = cacheDir; //TODO: should it be possible to change the name of the dirs? addExistingCacheFiles(LOG_CACHE_DIR); addExistingCacheFiles(PARAM_CACHE_DIR); } private void addExistingCacheFiles(String cachePath) { if (cachePath != null) { //use cache dir if it's not null File cachePathFile = (mCacheDir != null) ? new File(mCacheDir, cachePath) : new File(cachePath); if(cachePathFile.exists()) { this.mCacheFiles.addAll(Arrays.asList(cachePathFile.listFiles(jsonFilter))); } } } FilenameFilter jsonFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".json"); } }; /** * Try to get a hit in the cache, return None otherwise * * @param crc CRC code of the TOC * @param port CrtpPort of the TOC */
// Path: src/se/bitcraze/crazyflie/lib/crtp/CrtpPort.java // public enum CrtpPort { // CONSOLE(0), // PARAMETERS(2), // COMMANDER(3), // MEMORY(4), // LOGGING(5), // COMMANDER_GENERIC(7), // DEBUGDRIVER(14), // LINKCTRL(15), // ALL(255), // UNKNOWN(-1); //FIXME // // private byte mNumber; // // private CrtpPort(int number) { // this.mNumber = (byte) number; // } // // /** // * Get the number associated with this port. // * // * @return the number of the port // */ // public byte getNumber() { // return mNumber; // } // // /** // * Get the port with a specific number. // * // * @param number // * the number of the port. // * @return the port or <code>null</code> if no port with the specified number exists. // */ // public static CrtpPort getByNumber(byte number) { // for (CrtpPort p : CrtpPort.values()) { // if (p.getNumber() == number) { // return p; // } // } // return null; // } // } // Path: src/se/bitcraze/crazyflie/lib/toc/TocCache.java import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import se.bitcraze.crazyflie.lib.crtp.CrtpPort; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; /** * || ____ _ __ * +------+ / __ )(_) /_______________ _____ ___ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ * * Copyright (C) 2015 Bitcraze AB * * Crazyflie Nano Quadcopter Client * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package se.bitcraze.crazyflie.lib.toc; /** * Access to TOC cache. To turn off the cache functionality don't supply any directories. * * Heavily based on toccache.py * * */ public class TocCache { final Logger mLogger = LoggerFactory.getLogger("TocCache"); private List<File> mCacheFiles = new ArrayList<File>(); private File mCacheDir = null; private static final String PARAM_CACHE_DIR = "paramCache"; private static final String LOG_CACHE_DIR = "logCache"; private ObjectMapper mMapper = new ObjectMapper(); // can reuse, share globally public TocCache(File cacheDir) { this.mCacheDir = cacheDir; //TODO: should it be possible to change the name of the dirs? addExistingCacheFiles(LOG_CACHE_DIR); addExistingCacheFiles(PARAM_CACHE_DIR); } private void addExistingCacheFiles(String cachePath) { if (cachePath != null) { //use cache dir if it's not null File cachePathFile = (mCacheDir != null) ? new File(mCacheDir, cachePath) : new File(cachePath); if(cachePathFile.exists()) { this.mCacheFiles.addAll(Arrays.asList(cachePathFile.listFiles(jsonFilter))); } } } FilenameFilter jsonFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".json"); } }; /** * Try to get a hit in the cache, return None otherwise * * @param crc CRC code of the TOC * @param port CrtpPort of the TOC */
public Toc fetch(int crc, CrtpPort port) {
bitcraze/crazyflie-android-client
src/se/bitcraze/crazyflie/lib/toc/TocElement.java
// Path: src/se/bitcraze/crazyflie/lib/crtp/CrtpPort.java // public enum CrtpPort { // CONSOLE(0), // PARAMETERS(2), // COMMANDER(3), // MEMORY(4), // LOGGING(5), // COMMANDER_GENERIC(7), // DEBUGDRIVER(14), // LINKCTRL(15), // ALL(255), // UNKNOWN(-1); //FIXME // // private byte mNumber; // // private CrtpPort(int number) { // this.mNumber = (byte) number; // } // // /** // * Get the number associated with this port. // * // * @return the number of the port // */ // public byte getNumber() { // return mNumber; // } // // /** // * Get the port with a specific number. // * // * @param number // * the number of the port. // * @return the port or <code>null</code> if no port with the specified number exists. // */ // public static CrtpPort getByNumber(byte number) { // for (CrtpPort p : CrtpPort.values()) { // if (p.getNumber() == number) { // return p; // } // } // return null; // } // }
import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonIgnore; import se.bitcraze.crazyflie.lib.crtp.CrtpPort; import java.nio.charset.Charset; import org.slf4j.Logger;
/** * || ____ _ __ * +------+ / __ )(_) /_______________ _____ ___ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ * * Copyright (C) 2015 Bitcraze AB * * Crazyflie Nano Quadcopter Client * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package se.bitcraze.crazyflie.lib.toc; /** * An element in the TOC * */ public class TocElement implements Comparable<TocElement> { final Logger mLogger = LoggerFactory.getLogger("TocElement"); public static final int RW_ACCESS = 1; public static final int RO_ACCESS = 0; private int mIdent = 0; private String mGroup = ""; private String mName = ""; private VariableType mCtype; private int mAccess = RO_ACCESS; public TocElement() { } /** * TocElement creator * * @param data the binary payload of the element */
// Path: src/se/bitcraze/crazyflie/lib/crtp/CrtpPort.java // public enum CrtpPort { // CONSOLE(0), // PARAMETERS(2), // COMMANDER(3), // MEMORY(4), // LOGGING(5), // COMMANDER_GENERIC(7), // DEBUGDRIVER(14), // LINKCTRL(15), // ALL(255), // UNKNOWN(-1); //FIXME // // private byte mNumber; // // private CrtpPort(int number) { // this.mNumber = (byte) number; // } // // /** // * Get the number associated with this port. // * // * @return the number of the port // */ // public byte getNumber() { // return mNumber; // } // // /** // * Get the port with a specific number. // * // * @param number // * the number of the port. // * @return the port or <code>null</code> if no port with the specified number exists. // */ // public static CrtpPort getByNumber(byte number) { // for (CrtpPort p : CrtpPort.values()) { // if (p.getNumber() == number) { // return p; // } // } // return null; // } // } // Path: src/se/bitcraze/crazyflie/lib/toc/TocElement.java import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonIgnore; import se.bitcraze.crazyflie.lib.crtp.CrtpPort; import java.nio.charset.Charset; import org.slf4j.Logger; /** * || ____ _ __ * +------+ / __ )(_) /_______________ _____ ___ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ * * Copyright (C) 2015 Bitcraze AB * * Crazyflie Nano Quadcopter Client * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package se.bitcraze.crazyflie.lib.toc; /** * An element in the TOC * */ public class TocElement implements Comparable<TocElement> { final Logger mLogger = LoggerFactory.getLogger("TocElement"); public static final int RW_ACCESS = 1; public static final int RO_ACCESS = 0; private int mIdent = 0; private String mGroup = ""; private String mName = ""; private VariableType mCtype; private int mAccess = RO_ACCESS; public TocElement() { } /** * TocElement creator * * @param data the binary payload of the element */
public TocElement(CrtpPort port, byte[] data) {
bitcraze/crazyflie-android-client
src/se/bitcraze/crazyflie/lib/log/LogVariable.java
// Path: src/se/bitcraze/crazyflie/lib/toc/VariableType.java // public enum VariableType { // UINT8_T (1), // UINT16_T (2), // UINT32_T (4), // UINT64_T (8), // INT8_T (1), // INT16_T (2), // INT32_T (4), // INT64_T (8), // FLOAT (4), // DOUBLE (8); // // int mSize; // // VariableType(int size) { // this.mSize = size; // } // // final Logger mLogger = LoggerFactory.getLogger(this.getClass().getSimpleName()); // // /** // * Parse one variable of the given type. // * // * @param buffer the buffer to read raw data from // * @return the parsed variable // */ // public Number parse(ByteBuffer buffer) { // if (buffer.capacity() < this.getSize()) { // throw new IllegalStateException("Size of buffer (" + buffer.capacity() + ") must match the size of VariableType " + this.name() + " (" + this.getSize() +")"); // } // if (buffer.remaining() < this.getSize()) { // throw new IllegalStateException("Size of remaining buffer elements (" + buffer.remaining() + ") must match the size of VariableType " + this.name() + " (" + this.getSize() +")"); // } // buffer.order(CrtpPacket.BYTE_ORDER); // switch (this) { // case UINT8_T: // return (buffer.get()) & 0xff; // case UINT16_T: // return (buffer.getShort()) & 0xffff; // case UINT32_T: // return (buffer.getInt()) & 0xffffffffL; // case UINT64_T: // // TODO: throw exception // mLogger.warn("UINT64_T not yet implemented"); // return -1; // case INT8_T: // return buffer.get(); // case INT16_T: // return buffer.getShort(); // case INT32_T: // return buffer.getInt(); // case INT64_T: // return buffer.getLong(); // case FLOAT: // return buffer.getFloat(); // case DOUBLE: // return buffer.getDouble(); // default: // // TODO: throw exception // mLogger.warn("Parsing " + this.name() + " is not yet implemented"); // break; // } // return -1; // } // // /** // * Parse one variable of the given type. // * // * @param value // * @return // */ // public byte[] parse(Number value) { // ByteBuffer tempBuffer4 = ByteBuffer.allocate(4).order(CrtpPacket.BYTE_ORDER); // // //Use ByteBuffer with 8 bytes for INT64_T and DOUBLE // ByteBuffer tempBuffer8 = ByteBuffer.allocate(8).order(CrtpPacket.BYTE_ORDER); // // switch (this) { // case UINT8_T: // tempBuffer4.putShort((short) (value.byteValue() & 0xff)); // break; // case UINT16_T: // tempBuffer4.putInt(value.shortValue() & 0xffff); // break; // case UINT32_T: // tempBuffer4.putInt((int) ((value.intValue()) & 0xffffffffL)); // //tempBuffer.putLong((long) (value.intValue() & 0xffffffffL)); //only works if ByteBuffer is 8 bytes long // break; // case UINT64_T: // // TODO: throw exception // mLogger.warn("UINT64_T not yet implemented"); // break; // case INT8_T: // tempBuffer4.put(value.byteValue()); // break; // case INT16_T: // tempBuffer4.putShort(value.shortValue()); // break; // case INT32_T: // tempBuffer4.putInt(value.intValue()); // break; // case INT64_T: // tempBuffer8.putLong(value.longValue()); // tempBuffer8.rewind(); // return tempBuffer8.array(); // case FLOAT: // tempBuffer4.putFloat(value.floatValue()); // break; // case DOUBLE: // tempBuffer8.putDouble(value.doubleValue()); // tempBuffer8.rewind(); // return tempBuffer8.array(); // default: // // TODO: throw exception // mLogger.warn("Parsing " + this.name() + " is not yet implemented"); // break; // } // tempBuffer4.rewind(); // return tempBuffer4.array(); // } // // public int getSize() { // if (this == UINT64_T) { // mLogger.warn("UINT64_T not yet implemented"); // } // return this.mSize; // } // }
import se.bitcraze.crazyflie.lib.toc.VariableType;
/** * || ____ _ __ * +------+ / __ )(_) /_______________ _____ ___ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ * * Copyright (C) 2015 Bitcraze AB * * Crazyflie Nano Quadcopter Client * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package se.bitcraze.crazyflie.lib.log; /** * A LogVariable is an element of a {@link LogConfig} * * Instead of fetch_as/stored_as this class uses VariableType (not to be confused with LogVariable.getType()) * * TODO: does LogVariable need to store the ID? */ public class LogVariable { public final static int TOC_TYPE = 0; public final static int MEM_TYPE = 1; private String mName;
// Path: src/se/bitcraze/crazyflie/lib/toc/VariableType.java // public enum VariableType { // UINT8_T (1), // UINT16_T (2), // UINT32_T (4), // UINT64_T (8), // INT8_T (1), // INT16_T (2), // INT32_T (4), // INT64_T (8), // FLOAT (4), // DOUBLE (8); // // int mSize; // // VariableType(int size) { // this.mSize = size; // } // // final Logger mLogger = LoggerFactory.getLogger(this.getClass().getSimpleName()); // // /** // * Parse one variable of the given type. // * // * @param buffer the buffer to read raw data from // * @return the parsed variable // */ // public Number parse(ByteBuffer buffer) { // if (buffer.capacity() < this.getSize()) { // throw new IllegalStateException("Size of buffer (" + buffer.capacity() + ") must match the size of VariableType " + this.name() + " (" + this.getSize() +")"); // } // if (buffer.remaining() < this.getSize()) { // throw new IllegalStateException("Size of remaining buffer elements (" + buffer.remaining() + ") must match the size of VariableType " + this.name() + " (" + this.getSize() +")"); // } // buffer.order(CrtpPacket.BYTE_ORDER); // switch (this) { // case UINT8_T: // return (buffer.get()) & 0xff; // case UINT16_T: // return (buffer.getShort()) & 0xffff; // case UINT32_T: // return (buffer.getInt()) & 0xffffffffL; // case UINT64_T: // // TODO: throw exception // mLogger.warn("UINT64_T not yet implemented"); // return -1; // case INT8_T: // return buffer.get(); // case INT16_T: // return buffer.getShort(); // case INT32_T: // return buffer.getInt(); // case INT64_T: // return buffer.getLong(); // case FLOAT: // return buffer.getFloat(); // case DOUBLE: // return buffer.getDouble(); // default: // // TODO: throw exception // mLogger.warn("Parsing " + this.name() + " is not yet implemented"); // break; // } // return -1; // } // // /** // * Parse one variable of the given type. // * // * @param value // * @return // */ // public byte[] parse(Number value) { // ByteBuffer tempBuffer4 = ByteBuffer.allocate(4).order(CrtpPacket.BYTE_ORDER); // // //Use ByteBuffer with 8 bytes for INT64_T and DOUBLE // ByteBuffer tempBuffer8 = ByteBuffer.allocate(8).order(CrtpPacket.BYTE_ORDER); // // switch (this) { // case UINT8_T: // tempBuffer4.putShort((short) (value.byteValue() & 0xff)); // break; // case UINT16_T: // tempBuffer4.putInt(value.shortValue() & 0xffff); // break; // case UINT32_T: // tempBuffer4.putInt((int) ((value.intValue()) & 0xffffffffL)); // //tempBuffer.putLong((long) (value.intValue() & 0xffffffffL)); //only works if ByteBuffer is 8 bytes long // break; // case UINT64_T: // // TODO: throw exception // mLogger.warn("UINT64_T not yet implemented"); // break; // case INT8_T: // tempBuffer4.put(value.byteValue()); // break; // case INT16_T: // tempBuffer4.putShort(value.shortValue()); // break; // case INT32_T: // tempBuffer4.putInt(value.intValue()); // break; // case INT64_T: // tempBuffer8.putLong(value.longValue()); // tempBuffer8.rewind(); // return tempBuffer8.array(); // case FLOAT: // tempBuffer4.putFloat(value.floatValue()); // break; // case DOUBLE: // tempBuffer8.putDouble(value.doubleValue()); // tempBuffer8.rewind(); // return tempBuffer8.array(); // default: // // TODO: throw exception // mLogger.warn("Parsing " + this.name() + " is not yet implemented"); // break; // } // tempBuffer4.rewind(); // return tempBuffer4.array(); // } // // public int getSize() { // if (this == UINT64_T) { // mLogger.warn("UINT64_T not yet implemented"); // } // return this.mSize; // } // } // Path: src/se/bitcraze/crazyflie/lib/log/LogVariable.java import se.bitcraze.crazyflie.lib.toc.VariableType; /** * || ____ _ __ * +------+ / __ )(_) /_______________ _____ ___ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ * * Copyright (C) 2015 Bitcraze AB * * Crazyflie Nano Quadcopter Client * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package se.bitcraze.crazyflie.lib.log; /** * A LogVariable is an element of a {@link LogConfig} * * Instead of fetch_as/stored_as this class uses VariableType (not to be confused with LogVariable.getType()) * * TODO: does LogVariable need to store the ID? */ public class LogVariable { public final static int TOC_TYPE = 0; public final static int MEM_TYPE = 1; private String mName;
private VariableType mVariableType;
flyou/Girls
app/src/main/java/com/flyou/girls/ui/typeImageList/persenter/TypeImageListPersenterImpl.java
// Path: app/src/main/java/com/flyou/girls/ui/typeImageList/domain/TypeImageDomain.java // public class TypeImageDomain implements Parcelable { // private int width; // private int height; // private String url; // private String fullSizeUrl; // // public TypeImageDomain(int width, int height, String url, String fullSizeUrl) { // this.width = width; // this.height = height; // this.url = url; // this.fullSizeUrl = fullSizeUrl; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getFullSizeUrl() { // return fullSizeUrl; // } // // public void setFullSizeUrl(String fullSizeUrl) { // this.fullSizeUrl = fullSizeUrl; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.width); // dest.writeInt(this.height); // dest.writeString(this.url); // dest.writeString(this.fullSizeUrl); // } // // protected TypeImageDomain(Parcel in) { // this.width = in.readInt(); // this.height = in.readInt(); // this.url = in.readString(); // this.fullSizeUrl = in.readString(); // } // // public static final Parcelable.Creator<TypeImageDomain> CREATOR = new Parcelable.Creator<TypeImageDomain>() { // @Override // public TypeImageDomain createFromParcel(Parcel source) { // return new TypeImageDomain(source); // } // // @Override // public TypeImageDomain[] newArray(int size) { // return new TypeImageDomain[size]; // } // }; // } // // Path: app/src/main/java/com/flyou/girls/ui/typeImageList/model/TypeImageListModel.java // public interface TypeImageListModel { // void getTypeImageList(String url,TypeImageListModelImpl.OnGetTypeImageListener litener); // } // // Path: app/src/main/java/com/flyou/girls/ui/typeImageList/model/TypeImageListModelImpl.java // public class TypeImageListModelImpl implements TypeImageListModel { // @Override // public void getTypeImageList(final String url, final TypeImageListModelImpl.OnGetTypeImageListener litener) { // // // Observable<List<TypeImageDomain>> observable = Observable.create(new Observable.OnSubscribe<List<TypeImageDomain>>() { // @Override // public void call(Subscriber<? super List<TypeImageDomain>> subscriber) { // List<TypeImageDomain> typeImageDomains = new ArrayList(); // try { // Document document = Jsoup.connect(url).get(); // Element element = document.getElementById("gallery-1"); // Elements elementsA = element.getElementsByTag("a"); // // for (Element a : elementsA) { // String linkUrl = a.attr("abs:href"); // // Elements img = a.getElementsByTag("img"); // String src = img.attr("src"); // String width = img.attr("width"); // String height = img.attr("height"); // typeImageDomains.add(new TypeImageDomain(Integer.valueOf(width), Integer.valueOf(height), src,linkUrl)); // } // } catch (IOException e) { // subscriber.onError(e); // } // System.out.print(typeImageDomains.get(0).getHeight()); // subscriber.onNext(typeImageDomains); // } // }); // // // Subscriber<List<TypeImageDomain>> subscriber = new Subscriber<List<TypeImageDomain>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // litener.OnError((Exception) e); // } // // @Override // public void onNext(List<TypeImageDomain> typeImageDomains) { // litener.onSuccess(typeImageDomains); // // } // }; // // // observable // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(subscriber); // } // // public interface OnGetTypeImageListener { // void onSuccess(List<TypeImageDomain> imageDomainList); // // void OnError(Exception e); // } // } // // Path: app/src/main/java/com/flyou/girls/ui/typeImageList/view/TypeImageListView.java // public interface TypeImageListView { // void showLaoding(); // // void hideLoading(); // // void showLoadFaild( Exception e); // // void receiveImageList(List<TypeImageDomain> typeImageDomains); // // }
import com.flyou.girls.ui.typeImageList.domain.TypeImageDomain; import com.flyou.girls.ui.typeImageList.model.TypeImageListModel; import com.flyou.girls.ui.typeImageList.model.TypeImageListModelImpl; import com.flyou.girls.ui.typeImageList.view.TypeImageListView; import java.util.List;
package com.flyou.girls.ui.typeImageList.persenter; /** * ============================================================ * ้กน็›ฎๅ็งฐ๏ผšGirls * ๅŒ…ๅ็งฐ๏ผšcom.flyou.girls.ui.typeImageList.persenter * ๆ–‡ไปถๅ๏ผšTypeImageListPersenterImpl * ็ฑปๆ่ฟฐ๏ผš * ๅˆ›ๅปบไบบ๏ผšflyou * ้‚ฎ็ฎฑ๏ผšfangjaylong@gmail.com * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2016/4/20 14:48 * ไฟฎๆ”นๅค‡ๆณจ๏ผš * ็‰ˆๆœฌ๏ผš@version V1.0 * ============================================================ **/ public class TypeImageListPersenterImpl implements TypeImageListModelImpl.OnGetTypeImageListener,TypeImageListPersenter { private TypeImageListView mTypeImageListView;
// Path: app/src/main/java/com/flyou/girls/ui/typeImageList/domain/TypeImageDomain.java // public class TypeImageDomain implements Parcelable { // private int width; // private int height; // private String url; // private String fullSizeUrl; // // public TypeImageDomain(int width, int height, String url, String fullSizeUrl) { // this.width = width; // this.height = height; // this.url = url; // this.fullSizeUrl = fullSizeUrl; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getFullSizeUrl() { // return fullSizeUrl; // } // // public void setFullSizeUrl(String fullSizeUrl) { // this.fullSizeUrl = fullSizeUrl; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.width); // dest.writeInt(this.height); // dest.writeString(this.url); // dest.writeString(this.fullSizeUrl); // } // // protected TypeImageDomain(Parcel in) { // this.width = in.readInt(); // this.height = in.readInt(); // this.url = in.readString(); // this.fullSizeUrl = in.readString(); // } // // public static final Parcelable.Creator<TypeImageDomain> CREATOR = new Parcelable.Creator<TypeImageDomain>() { // @Override // public TypeImageDomain createFromParcel(Parcel source) { // return new TypeImageDomain(source); // } // // @Override // public TypeImageDomain[] newArray(int size) { // return new TypeImageDomain[size]; // } // }; // } // // Path: app/src/main/java/com/flyou/girls/ui/typeImageList/model/TypeImageListModel.java // public interface TypeImageListModel { // void getTypeImageList(String url,TypeImageListModelImpl.OnGetTypeImageListener litener); // } // // Path: app/src/main/java/com/flyou/girls/ui/typeImageList/model/TypeImageListModelImpl.java // public class TypeImageListModelImpl implements TypeImageListModel { // @Override // public void getTypeImageList(final String url, final TypeImageListModelImpl.OnGetTypeImageListener litener) { // // // Observable<List<TypeImageDomain>> observable = Observable.create(new Observable.OnSubscribe<List<TypeImageDomain>>() { // @Override // public void call(Subscriber<? super List<TypeImageDomain>> subscriber) { // List<TypeImageDomain> typeImageDomains = new ArrayList(); // try { // Document document = Jsoup.connect(url).get(); // Element element = document.getElementById("gallery-1"); // Elements elementsA = element.getElementsByTag("a"); // // for (Element a : elementsA) { // String linkUrl = a.attr("abs:href"); // // Elements img = a.getElementsByTag("img"); // String src = img.attr("src"); // String width = img.attr("width"); // String height = img.attr("height"); // typeImageDomains.add(new TypeImageDomain(Integer.valueOf(width), Integer.valueOf(height), src,linkUrl)); // } // } catch (IOException e) { // subscriber.onError(e); // } // System.out.print(typeImageDomains.get(0).getHeight()); // subscriber.onNext(typeImageDomains); // } // }); // // // Subscriber<List<TypeImageDomain>> subscriber = new Subscriber<List<TypeImageDomain>>() { // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // litener.OnError((Exception) e); // } // // @Override // public void onNext(List<TypeImageDomain> typeImageDomains) { // litener.onSuccess(typeImageDomains); // // } // }; // // // observable // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(subscriber); // } // // public interface OnGetTypeImageListener { // void onSuccess(List<TypeImageDomain> imageDomainList); // // void OnError(Exception e); // } // } // // Path: app/src/main/java/com/flyou/girls/ui/typeImageList/view/TypeImageListView.java // public interface TypeImageListView { // void showLaoding(); // // void hideLoading(); // // void showLoadFaild( Exception e); // // void receiveImageList(List<TypeImageDomain> typeImageDomains); // // } // Path: app/src/main/java/com/flyou/girls/ui/typeImageList/persenter/TypeImageListPersenterImpl.java import com.flyou.girls.ui.typeImageList.domain.TypeImageDomain; import com.flyou.girls.ui.typeImageList.model.TypeImageListModel; import com.flyou.girls.ui.typeImageList.model.TypeImageListModelImpl; import com.flyou.girls.ui.typeImageList.view.TypeImageListView; import java.util.List; package com.flyou.girls.ui.typeImageList.persenter; /** * ============================================================ * ้กน็›ฎๅ็งฐ๏ผšGirls * ๅŒ…ๅ็งฐ๏ผšcom.flyou.girls.ui.typeImageList.persenter * ๆ–‡ไปถๅ๏ผšTypeImageListPersenterImpl * ็ฑปๆ่ฟฐ๏ผš * ๅˆ›ๅปบไบบ๏ผšflyou * ้‚ฎ็ฎฑ๏ผšfangjaylong@gmail.com * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2016/4/20 14:48 * ไฟฎๆ”นๅค‡ๆณจ๏ผš * ็‰ˆๆœฌ๏ผš@version V1.0 * ============================================================ **/ public class TypeImageListPersenterImpl implements TypeImageListModelImpl.OnGetTypeImageListener,TypeImageListPersenter { private TypeImageListView mTypeImageListView;
private TypeImageListModel mTypeImageListModel;
flyou/Girls
app/src/main/java/com/flyou/girls/ui/mainImageList/persenter/ImageListPersenterImpl.java
// Path: app/src/main/java/com/flyou/girls/ui/mainImageList/domain/ImageListDomain.java // public class ImageListDomain implements Parcelable { // private String linkUrl; // private String imageUrl; // private String imgaeTitle; // // // // public String getLinkUrl() { // return linkUrl; // } // // public void setLinkUrl(String linkUrl) { // this.linkUrl = linkUrl; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImgaeTitle() { // return imgaeTitle; // } // // public void setImgaeTitle(String imgaeTitle) { // this.imgaeTitle = imgaeTitle; // } // // public ImageListDomain(String linkUrl, String imageUrl, String imgaeTitle) { // this.linkUrl = linkUrl; // this.imageUrl = imageUrl; // this.imgaeTitle = imgaeTitle; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.linkUrl); // dest.writeString(this.imageUrl); // dest.writeString(this.imgaeTitle); // } // // protected ImageListDomain(Parcel in) { // this.linkUrl = in.readString(); // this.imageUrl = in.readString(); // this.imgaeTitle = in.readString(); // } // // public static final Parcelable.Creator<ImageListDomain> CREATOR = new Parcelable.Creator<ImageListDomain>() { // @Override // public ImageListDomain createFromParcel(Parcel source) { // return new ImageListDomain(source); // } // // @Override // public ImageListDomain[] newArray(int size) { // return new ImageListDomain[size]; // } // }; // } // // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/model/ImageListModel.java // public interface ImageListModel { // void GetImageList(String type,int page,ImageListModelImpl.GetImageListenter listener); // } // // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/model/ImageListModelImpl.java // public class ImageListModelImpl implements ImageListModel { // // // @Override // public void GetImageList(final String type, final int page, final GetImageListenter listener) { // // // Observable<List<ImageListDomain>> observable = Observable.create(new Observable.OnSubscribe<List<ImageListDomain>>() { // @Override // public void call(Subscriber<? super List<ImageListDomain>> subscriber) { // List<ImageListDomain> imageListDomainList = new ArrayList(); // try { // Document document = Jsoup.connect(Constant.BASE_URL + type+page).get(); // Element imageListelement = document.getElementById("blog-grid"); // // Elements imageListElements = imageListelement.getElementsByAttributeValueContaining("class","col-lg-4 col-md-4 three-columns post-box"); // for (Element imageListElement : imageListElements) { // Element link = imageListElement.select("a[href]").first(); // Element image = imageListElement.select("img").first(); // String linkUrl = link.attr("abs:href"); // String imageUrl = image.attr("abs:src"); // String imageTitle = image.attr("alt").trim(); // imageListDomainList.add(new ImageListDomain(linkUrl, imageUrl, imageTitle)); // // } // subscriber.onNext(imageListDomainList); // // } catch (IOException e) { // subscriber.onError(e); // // } // // } // }); // // Subscriber<List<ImageListDomain>> subscriber = new Subscriber<List<ImageListDomain>>() { // @Override // public void onCompleted() { // } // // @Override // public void onError(Throwable e) { // listener.OnError((Exception) e); // } // // @Override // public void onNext(List<ImageListDomain> imageListDomains) { // listener.onSuccess(imageListDomains); // } // }; // // observable // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(subscriber); // // // } // // public interface GetImageListenter { // void onSuccess(List<ImageListDomain> imageList); // // void OnError(Exception e); // } // } // // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/view/ImageListView.java // public interface ImageListView { // void showLaoding(); // // void hideLoading(); // // void showLoadFaild( Exception e); // // void receiveImageList(List<ImageListDomain> imageListDomains); // // }
import com.flyou.girls.ui.mainImageList.domain.ImageListDomain; import com.flyou.girls.ui.mainImageList.model.ImageListModel; import com.flyou.girls.ui.mainImageList.model.ImageListModelImpl; import com.flyou.girls.ui.mainImageList.view.ImageListView; import java.util.List;
package com.flyou.girls.ui.mainImageList.persenter; /** * ============================================================ * ้กน็›ฎๅ็งฐ๏ผšGirls * ๅŒ…ๅ็งฐ๏ผšcom.flyou.girls.ui.ImageList.persenter * ๆ–‡ไปถๅ๏ผšImageListPersenterImpl * ็ฑปๆ่ฟฐ๏ผš * ๅˆ›ๅปบไบบ๏ผšflyou * ้‚ฎ็ฎฑ๏ผšfangjaylong@gmail.com * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2016/4/19 16:48 * ไฟฎๆ”นๅค‡ๆณจ๏ผš * ็‰ˆๆœฌ๏ผš@version V1.0 * ============================================================ **/ public class ImageListPersenterImpl implements ImageListModelImpl.GetImageListenter,ImageListPersenter{ private ImageListView imageListView;
// Path: app/src/main/java/com/flyou/girls/ui/mainImageList/domain/ImageListDomain.java // public class ImageListDomain implements Parcelable { // private String linkUrl; // private String imageUrl; // private String imgaeTitle; // // // // public String getLinkUrl() { // return linkUrl; // } // // public void setLinkUrl(String linkUrl) { // this.linkUrl = linkUrl; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImgaeTitle() { // return imgaeTitle; // } // // public void setImgaeTitle(String imgaeTitle) { // this.imgaeTitle = imgaeTitle; // } // // public ImageListDomain(String linkUrl, String imageUrl, String imgaeTitle) { // this.linkUrl = linkUrl; // this.imageUrl = imageUrl; // this.imgaeTitle = imgaeTitle; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.linkUrl); // dest.writeString(this.imageUrl); // dest.writeString(this.imgaeTitle); // } // // protected ImageListDomain(Parcel in) { // this.linkUrl = in.readString(); // this.imageUrl = in.readString(); // this.imgaeTitle = in.readString(); // } // // public static final Parcelable.Creator<ImageListDomain> CREATOR = new Parcelable.Creator<ImageListDomain>() { // @Override // public ImageListDomain createFromParcel(Parcel source) { // return new ImageListDomain(source); // } // // @Override // public ImageListDomain[] newArray(int size) { // return new ImageListDomain[size]; // } // }; // } // // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/model/ImageListModel.java // public interface ImageListModel { // void GetImageList(String type,int page,ImageListModelImpl.GetImageListenter listener); // } // // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/model/ImageListModelImpl.java // public class ImageListModelImpl implements ImageListModel { // // // @Override // public void GetImageList(final String type, final int page, final GetImageListenter listener) { // // // Observable<List<ImageListDomain>> observable = Observable.create(new Observable.OnSubscribe<List<ImageListDomain>>() { // @Override // public void call(Subscriber<? super List<ImageListDomain>> subscriber) { // List<ImageListDomain> imageListDomainList = new ArrayList(); // try { // Document document = Jsoup.connect(Constant.BASE_URL + type+page).get(); // Element imageListelement = document.getElementById("blog-grid"); // // Elements imageListElements = imageListelement.getElementsByAttributeValueContaining("class","col-lg-4 col-md-4 three-columns post-box"); // for (Element imageListElement : imageListElements) { // Element link = imageListElement.select("a[href]").first(); // Element image = imageListElement.select("img").first(); // String linkUrl = link.attr("abs:href"); // String imageUrl = image.attr("abs:src"); // String imageTitle = image.attr("alt").trim(); // imageListDomainList.add(new ImageListDomain(linkUrl, imageUrl, imageTitle)); // // } // subscriber.onNext(imageListDomainList); // // } catch (IOException e) { // subscriber.onError(e); // // } // // } // }); // // Subscriber<List<ImageListDomain>> subscriber = new Subscriber<List<ImageListDomain>>() { // @Override // public void onCompleted() { // } // // @Override // public void onError(Throwable e) { // listener.OnError((Exception) e); // } // // @Override // public void onNext(List<ImageListDomain> imageListDomains) { // listener.onSuccess(imageListDomains); // } // }; // // observable // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(subscriber); // // // } // // public interface GetImageListenter { // void onSuccess(List<ImageListDomain> imageList); // // void OnError(Exception e); // } // } // // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/view/ImageListView.java // public interface ImageListView { // void showLaoding(); // // void hideLoading(); // // void showLoadFaild( Exception e); // // void receiveImageList(List<ImageListDomain> imageListDomains); // // } // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/persenter/ImageListPersenterImpl.java import com.flyou.girls.ui.mainImageList.domain.ImageListDomain; import com.flyou.girls.ui.mainImageList.model.ImageListModel; import com.flyou.girls.ui.mainImageList.model.ImageListModelImpl; import com.flyou.girls.ui.mainImageList.view.ImageListView; import java.util.List; package com.flyou.girls.ui.mainImageList.persenter; /** * ============================================================ * ้กน็›ฎๅ็งฐ๏ผšGirls * ๅŒ…ๅ็งฐ๏ผšcom.flyou.girls.ui.ImageList.persenter * ๆ–‡ไปถๅ๏ผšImageListPersenterImpl * ็ฑปๆ่ฟฐ๏ผš * ๅˆ›ๅปบไบบ๏ผšflyou * ้‚ฎ็ฎฑ๏ผšfangjaylong@gmail.com * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2016/4/19 16:48 * ไฟฎๆ”นๅค‡ๆณจ๏ผš * ็‰ˆๆœฌ๏ผš@version V1.0 * ============================================================ **/ public class ImageListPersenterImpl implements ImageListModelImpl.GetImageListenter,ImageListPersenter{ private ImageListView imageListView;
private ImageListModel imageListModel;
flyou/Girls
app/src/main/java/com/flyou/girls/ui/mainImageList/persenter/ImageListPersenterImpl.java
// Path: app/src/main/java/com/flyou/girls/ui/mainImageList/domain/ImageListDomain.java // public class ImageListDomain implements Parcelable { // private String linkUrl; // private String imageUrl; // private String imgaeTitle; // // // // public String getLinkUrl() { // return linkUrl; // } // // public void setLinkUrl(String linkUrl) { // this.linkUrl = linkUrl; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImgaeTitle() { // return imgaeTitle; // } // // public void setImgaeTitle(String imgaeTitle) { // this.imgaeTitle = imgaeTitle; // } // // public ImageListDomain(String linkUrl, String imageUrl, String imgaeTitle) { // this.linkUrl = linkUrl; // this.imageUrl = imageUrl; // this.imgaeTitle = imgaeTitle; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.linkUrl); // dest.writeString(this.imageUrl); // dest.writeString(this.imgaeTitle); // } // // protected ImageListDomain(Parcel in) { // this.linkUrl = in.readString(); // this.imageUrl = in.readString(); // this.imgaeTitle = in.readString(); // } // // public static final Parcelable.Creator<ImageListDomain> CREATOR = new Parcelable.Creator<ImageListDomain>() { // @Override // public ImageListDomain createFromParcel(Parcel source) { // return new ImageListDomain(source); // } // // @Override // public ImageListDomain[] newArray(int size) { // return new ImageListDomain[size]; // } // }; // } // // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/model/ImageListModel.java // public interface ImageListModel { // void GetImageList(String type,int page,ImageListModelImpl.GetImageListenter listener); // } // // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/model/ImageListModelImpl.java // public class ImageListModelImpl implements ImageListModel { // // // @Override // public void GetImageList(final String type, final int page, final GetImageListenter listener) { // // // Observable<List<ImageListDomain>> observable = Observable.create(new Observable.OnSubscribe<List<ImageListDomain>>() { // @Override // public void call(Subscriber<? super List<ImageListDomain>> subscriber) { // List<ImageListDomain> imageListDomainList = new ArrayList(); // try { // Document document = Jsoup.connect(Constant.BASE_URL + type+page).get(); // Element imageListelement = document.getElementById("blog-grid"); // // Elements imageListElements = imageListelement.getElementsByAttributeValueContaining("class","col-lg-4 col-md-4 three-columns post-box"); // for (Element imageListElement : imageListElements) { // Element link = imageListElement.select("a[href]").first(); // Element image = imageListElement.select("img").first(); // String linkUrl = link.attr("abs:href"); // String imageUrl = image.attr("abs:src"); // String imageTitle = image.attr("alt").trim(); // imageListDomainList.add(new ImageListDomain(linkUrl, imageUrl, imageTitle)); // // } // subscriber.onNext(imageListDomainList); // // } catch (IOException e) { // subscriber.onError(e); // // } // // } // }); // // Subscriber<List<ImageListDomain>> subscriber = new Subscriber<List<ImageListDomain>>() { // @Override // public void onCompleted() { // } // // @Override // public void onError(Throwable e) { // listener.OnError((Exception) e); // } // // @Override // public void onNext(List<ImageListDomain> imageListDomains) { // listener.onSuccess(imageListDomains); // } // }; // // observable // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(subscriber); // // // } // // public interface GetImageListenter { // void onSuccess(List<ImageListDomain> imageList); // // void OnError(Exception e); // } // } // // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/view/ImageListView.java // public interface ImageListView { // void showLaoding(); // // void hideLoading(); // // void showLoadFaild( Exception e); // // void receiveImageList(List<ImageListDomain> imageListDomains); // // }
import com.flyou.girls.ui.mainImageList.domain.ImageListDomain; import com.flyou.girls.ui.mainImageList.model.ImageListModel; import com.flyou.girls.ui.mainImageList.model.ImageListModelImpl; import com.flyou.girls.ui.mainImageList.view.ImageListView; import java.util.List;
package com.flyou.girls.ui.mainImageList.persenter; /** * ============================================================ * ้กน็›ฎๅ็งฐ๏ผšGirls * ๅŒ…ๅ็งฐ๏ผšcom.flyou.girls.ui.ImageList.persenter * ๆ–‡ไปถๅ๏ผšImageListPersenterImpl * ็ฑปๆ่ฟฐ๏ผš * ๅˆ›ๅปบไบบ๏ผšflyou * ้‚ฎ็ฎฑ๏ผšfangjaylong@gmail.com * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2016/4/19 16:48 * ไฟฎๆ”นๅค‡ๆณจ๏ผš * ็‰ˆๆœฌ๏ผš@version V1.0 * ============================================================ **/ public class ImageListPersenterImpl implements ImageListModelImpl.GetImageListenter,ImageListPersenter{ private ImageListView imageListView; private ImageListModel imageListModel; public ImageListPersenterImpl(ImageListView imageListView) { this.imageListView = imageListView; this.imageListModel=new ImageListModelImpl(); } @Override
// Path: app/src/main/java/com/flyou/girls/ui/mainImageList/domain/ImageListDomain.java // public class ImageListDomain implements Parcelable { // private String linkUrl; // private String imageUrl; // private String imgaeTitle; // // // // public String getLinkUrl() { // return linkUrl; // } // // public void setLinkUrl(String linkUrl) { // this.linkUrl = linkUrl; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImgaeTitle() { // return imgaeTitle; // } // // public void setImgaeTitle(String imgaeTitle) { // this.imgaeTitle = imgaeTitle; // } // // public ImageListDomain(String linkUrl, String imageUrl, String imgaeTitle) { // this.linkUrl = linkUrl; // this.imageUrl = imageUrl; // this.imgaeTitle = imgaeTitle; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.linkUrl); // dest.writeString(this.imageUrl); // dest.writeString(this.imgaeTitle); // } // // protected ImageListDomain(Parcel in) { // this.linkUrl = in.readString(); // this.imageUrl = in.readString(); // this.imgaeTitle = in.readString(); // } // // public static final Parcelable.Creator<ImageListDomain> CREATOR = new Parcelable.Creator<ImageListDomain>() { // @Override // public ImageListDomain createFromParcel(Parcel source) { // return new ImageListDomain(source); // } // // @Override // public ImageListDomain[] newArray(int size) { // return new ImageListDomain[size]; // } // }; // } // // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/model/ImageListModel.java // public interface ImageListModel { // void GetImageList(String type,int page,ImageListModelImpl.GetImageListenter listener); // } // // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/model/ImageListModelImpl.java // public class ImageListModelImpl implements ImageListModel { // // // @Override // public void GetImageList(final String type, final int page, final GetImageListenter listener) { // // // Observable<List<ImageListDomain>> observable = Observable.create(new Observable.OnSubscribe<List<ImageListDomain>>() { // @Override // public void call(Subscriber<? super List<ImageListDomain>> subscriber) { // List<ImageListDomain> imageListDomainList = new ArrayList(); // try { // Document document = Jsoup.connect(Constant.BASE_URL + type+page).get(); // Element imageListelement = document.getElementById("blog-grid"); // // Elements imageListElements = imageListelement.getElementsByAttributeValueContaining("class","col-lg-4 col-md-4 three-columns post-box"); // for (Element imageListElement : imageListElements) { // Element link = imageListElement.select("a[href]").first(); // Element image = imageListElement.select("img").first(); // String linkUrl = link.attr("abs:href"); // String imageUrl = image.attr("abs:src"); // String imageTitle = image.attr("alt").trim(); // imageListDomainList.add(new ImageListDomain(linkUrl, imageUrl, imageTitle)); // // } // subscriber.onNext(imageListDomainList); // // } catch (IOException e) { // subscriber.onError(e); // // } // // } // }); // // Subscriber<List<ImageListDomain>> subscriber = new Subscriber<List<ImageListDomain>>() { // @Override // public void onCompleted() { // } // // @Override // public void onError(Throwable e) { // listener.OnError((Exception) e); // } // // @Override // public void onNext(List<ImageListDomain> imageListDomains) { // listener.onSuccess(imageListDomains); // } // }; // // observable // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(subscriber); // // // } // // public interface GetImageListenter { // void onSuccess(List<ImageListDomain> imageList); // // void OnError(Exception e); // } // } // // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/view/ImageListView.java // public interface ImageListView { // void showLaoding(); // // void hideLoading(); // // void showLoadFaild( Exception e); // // void receiveImageList(List<ImageListDomain> imageListDomains); // // } // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/persenter/ImageListPersenterImpl.java import com.flyou.girls.ui.mainImageList.domain.ImageListDomain; import com.flyou.girls.ui.mainImageList.model.ImageListModel; import com.flyou.girls.ui.mainImageList.model.ImageListModelImpl; import com.flyou.girls.ui.mainImageList.view.ImageListView; import java.util.List; package com.flyou.girls.ui.mainImageList.persenter; /** * ============================================================ * ้กน็›ฎๅ็งฐ๏ผšGirls * ๅŒ…ๅ็งฐ๏ผšcom.flyou.girls.ui.ImageList.persenter * ๆ–‡ไปถๅ๏ผšImageListPersenterImpl * ็ฑปๆ่ฟฐ๏ผš * ๅˆ›ๅปบไบบ๏ผšflyou * ้‚ฎ็ฎฑ๏ผšfangjaylong@gmail.com * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2016/4/19 16:48 * ไฟฎๆ”นๅค‡ๆณจ๏ผš * ็‰ˆๆœฌ๏ผš@version V1.0 * ============================================================ **/ public class ImageListPersenterImpl implements ImageListModelImpl.GetImageListenter,ImageListPersenter{ private ImageListView imageListView; private ImageListModel imageListModel; public ImageListPersenterImpl(ImageListView imageListView) { this.imageListView = imageListView; this.imageListModel=new ImageListModelImpl(); } @Override
public void onSuccess(List<ImageListDomain> imageList) {
flyou/Girls
app/src/main/java/com/flyou/girls/ui/mainImageList/model/ImageListModelImpl.java
// Path: app/src/main/java/com/flyou/girls/Constant.java // public class Constant { // public static final String BASE_URL="http://m.xxxiao.com"; // public static final String NEW="/page/"; // public static final String XINGGAN="/cat/xinggan/page/"; // public static final String SHAONV="/cat/shaonv/page/"; // public static final String MRXT="/cat/mrxt/page/"; // public static final String SWMT="/cat/swmt/page/"; // public static final String WMXZ="/cat/wmxz/page/"; // public static final String WALLPAPER="/cat/wallpaper/page"; // } // // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/domain/ImageListDomain.java // public class ImageListDomain implements Parcelable { // private String linkUrl; // private String imageUrl; // private String imgaeTitle; // // // // public String getLinkUrl() { // return linkUrl; // } // // public void setLinkUrl(String linkUrl) { // this.linkUrl = linkUrl; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImgaeTitle() { // return imgaeTitle; // } // // public void setImgaeTitle(String imgaeTitle) { // this.imgaeTitle = imgaeTitle; // } // // public ImageListDomain(String linkUrl, String imageUrl, String imgaeTitle) { // this.linkUrl = linkUrl; // this.imageUrl = imageUrl; // this.imgaeTitle = imgaeTitle; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.linkUrl); // dest.writeString(this.imageUrl); // dest.writeString(this.imgaeTitle); // } // // protected ImageListDomain(Parcel in) { // this.linkUrl = in.readString(); // this.imageUrl = in.readString(); // this.imgaeTitle = in.readString(); // } // // public static final Parcelable.Creator<ImageListDomain> CREATOR = new Parcelable.Creator<ImageListDomain>() { // @Override // public ImageListDomain createFromParcel(Parcel source) { // return new ImageListDomain(source); // } // // @Override // public ImageListDomain[] newArray(int size) { // return new ImageListDomain[size]; // } // }; // }
import com.flyou.girls.Constant; import com.flyou.girls.ui.mainImageList.domain.ImageListDomain; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package com.flyou.girls.ui.mainImageList.model; /** * ============================================================ * ้กน็›ฎๅ็งฐ๏ผšGirls * ๅŒ…ๅ็งฐ๏ผšcom.flyou.girls.ui.ImageList.domain * ๆ–‡ไปถๅ๏ผšImageListModelImpl * ็ฑปๆ่ฟฐ๏ผš * ๅˆ›ๅปบไบบ๏ผšflyou * ้‚ฎ็ฎฑ๏ผšfangjaylong@gmail.com * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2016/4/19 15:45 * ไฟฎๆ”นๅค‡ๆณจ๏ผš * ็‰ˆๆœฌ๏ผš@version V1.0 * ============================================================ **/ public class ImageListModelImpl implements ImageListModel { @Override public void GetImageList(final String type, final int page, final GetImageListenter listener) {
// Path: app/src/main/java/com/flyou/girls/Constant.java // public class Constant { // public static final String BASE_URL="http://m.xxxiao.com"; // public static final String NEW="/page/"; // public static final String XINGGAN="/cat/xinggan/page/"; // public static final String SHAONV="/cat/shaonv/page/"; // public static final String MRXT="/cat/mrxt/page/"; // public static final String SWMT="/cat/swmt/page/"; // public static final String WMXZ="/cat/wmxz/page/"; // public static final String WALLPAPER="/cat/wallpaper/page"; // } // // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/domain/ImageListDomain.java // public class ImageListDomain implements Parcelable { // private String linkUrl; // private String imageUrl; // private String imgaeTitle; // // // // public String getLinkUrl() { // return linkUrl; // } // // public void setLinkUrl(String linkUrl) { // this.linkUrl = linkUrl; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImgaeTitle() { // return imgaeTitle; // } // // public void setImgaeTitle(String imgaeTitle) { // this.imgaeTitle = imgaeTitle; // } // // public ImageListDomain(String linkUrl, String imageUrl, String imgaeTitle) { // this.linkUrl = linkUrl; // this.imageUrl = imageUrl; // this.imgaeTitle = imgaeTitle; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.linkUrl); // dest.writeString(this.imageUrl); // dest.writeString(this.imgaeTitle); // } // // protected ImageListDomain(Parcel in) { // this.linkUrl = in.readString(); // this.imageUrl = in.readString(); // this.imgaeTitle = in.readString(); // } // // public static final Parcelable.Creator<ImageListDomain> CREATOR = new Parcelable.Creator<ImageListDomain>() { // @Override // public ImageListDomain createFromParcel(Parcel source) { // return new ImageListDomain(source); // } // // @Override // public ImageListDomain[] newArray(int size) { // return new ImageListDomain[size]; // } // }; // } // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/model/ImageListModelImpl.java import com.flyou.girls.Constant; import com.flyou.girls.ui.mainImageList.domain.ImageListDomain; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; package com.flyou.girls.ui.mainImageList.model; /** * ============================================================ * ้กน็›ฎๅ็งฐ๏ผšGirls * ๅŒ…ๅ็งฐ๏ผšcom.flyou.girls.ui.ImageList.domain * ๆ–‡ไปถๅ๏ผšImageListModelImpl * ็ฑปๆ่ฟฐ๏ผš * ๅˆ›ๅปบไบบ๏ผšflyou * ้‚ฎ็ฎฑ๏ผšfangjaylong@gmail.com * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2016/4/19 15:45 * ไฟฎๆ”นๅค‡ๆณจ๏ผš * ็‰ˆๆœฌ๏ผš@version V1.0 * ============================================================ **/ public class ImageListModelImpl implements ImageListModel { @Override public void GetImageList(final String type, final int page, final GetImageListenter listener) {
Observable<List<ImageListDomain>> observable = Observable.create(new Observable.OnSubscribe<List<ImageListDomain>>() {
flyou/Girls
app/src/main/java/com/flyou/girls/ui/mainImageList/model/ImageListModelImpl.java
// Path: app/src/main/java/com/flyou/girls/Constant.java // public class Constant { // public static final String BASE_URL="http://m.xxxiao.com"; // public static final String NEW="/page/"; // public static final String XINGGAN="/cat/xinggan/page/"; // public static final String SHAONV="/cat/shaonv/page/"; // public static final String MRXT="/cat/mrxt/page/"; // public static final String SWMT="/cat/swmt/page/"; // public static final String WMXZ="/cat/wmxz/page/"; // public static final String WALLPAPER="/cat/wallpaper/page"; // } // // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/domain/ImageListDomain.java // public class ImageListDomain implements Parcelable { // private String linkUrl; // private String imageUrl; // private String imgaeTitle; // // // // public String getLinkUrl() { // return linkUrl; // } // // public void setLinkUrl(String linkUrl) { // this.linkUrl = linkUrl; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImgaeTitle() { // return imgaeTitle; // } // // public void setImgaeTitle(String imgaeTitle) { // this.imgaeTitle = imgaeTitle; // } // // public ImageListDomain(String linkUrl, String imageUrl, String imgaeTitle) { // this.linkUrl = linkUrl; // this.imageUrl = imageUrl; // this.imgaeTitle = imgaeTitle; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.linkUrl); // dest.writeString(this.imageUrl); // dest.writeString(this.imgaeTitle); // } // // protected ImageListDomain(Parcel in) { // this.linkUrl = in.readString(); // this.imageUrl = in.readString(); // this.imgaeTitle = in.readString(); // } // // public static final Parcelable.Creator<ImageListDomain> CREATOR = new Parcelable.Creator<ImageListDomain>() { // @Override // public ImageListDomain createFromParcel(Parcel source) { // return new ImageListDomain(source); // } // // @Override // public ImageListDomain[] newArray(int size) { // return new ImageListDomain[size]; // } // }; // }
import com.flyou.girls.Constant; import com.flyou.girls.ui.mainImageList.domain.ImageListDomain; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package com.flyou.girls.ui.mainImageList.model; /** * ============================================================ * ้กน็›ฎๅ็งฐ๏ผšGirls * ๅŒ…ๅ็งฐ๏ผšcom.flyou.girls.ui.ImageList.domain * ๆ–‡ไปถๅ๏ผšImageListModelImpl * ็ฑปๆ่ฟฐ๏ผš * ๅˆ›ๅปบไบบ๏ผšflyou * ้‚ฎ็ฎฑ๏ผšfangjaylong@gmail.com * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2016/4/19 15:45 * ไฟฎๆ”นๅค‡ๆณจ๏ผš * ็‰ˆๆœฌ๏ผš@version V1.0 * ============================================================ **/ public class ImageListModelImpl implements ImageListModel { @Override public void GetImageList(final String type, final int page, final GetImageListenter listener) { Observable<List<ImageListDomain>> observable = Observable.create(new Observable.OnSubscribe<List<ImageListDomain>>() { @Override public void call(Subscriber<? super List<ImageListDomain>> subscriber) { List<ImageListDomain> imageListDomainList = new ArrayList(); try {
// Path: app/src/main/java/com/flyou/girls/Constant.java // public class Constant { // public static final String BASE_URL="http://m.xxxiao.com"; // public static final String NEW="/page/"; // public static final String XINGGAN="/cat/xinggan/page/"; // public static final String SHAONV="/cat/shaonv/page/"; // public static final String MRXT="/cat/mrxt/page/"; // public static final String SWMT="/cat/swmt/page/"; // public static final String WMXZ="/cat/wmxz/page/"; // public static final String WALLPAPER="/cat/wallpaper/page"; // } // // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/domain/ImageListDomain.java // public class ImageListDomain implements Parcelable { // private String linkUrl; // private String imageUrl; // private String imgaeTitle; // // // // public String getLinkUrl() { // return linkUrl; // } // // public void setLinkUrl(String linkUrl) { // this.linkUrl = linkUrl; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImgaeTitle() { // return imgaeTitle; // } // // public void setImgaeTitle(String imgaeTitle) { // this.imgaeTitle = imgaeTitle; // } // // public ImageListDomain(String linkUrl, String imageUrl, String imgaeTitle) { // this.linkUrl = linkUrl; // this.imageUrl = imageUrl; // this.imgaeTitle = imgaeTitle; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.linkUrl); // dest.writeString(this.imageUrl); // dest.writeString(this.imgaeTitle); // } // // protected ImageListDomain(Parcel in) { // this.linkUrl = in.readString(); // this.imageUrl = in.readString(); // this.imgaeTitle = in.readString(); // } // // public static final Parcelable.Creator<ImageListDomain> CREATOR = new Parcelable.Creator<ImageListDomain>() { // @Override // public ImageListDomain createFromParcel(Parcel source) { // return new ImageListDomain(source); // } // // @Override // public ImageListDomain[] newArray(int size) { // return new ImageListDomain[size]; // } // }; // } // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/model/ImageListModelImpl.java import com.flyou.girls.Constant; import com.flyou.girls.ui.mainImageList.domain.ImageListDomain; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; package com.flyou.girls.ui.mainImageList.model; /** * ============================================================ * ้กน็›ฎๅ็งฐ๏ผšGirls * ๅŒ…ๅ็งฐ๏ผšcom.flyou.girls.ui.ImageList.domain * ๆ–‡ไปถๅ๏ผšImageListModelImpl * ็ฑปๆ่ฟฐ๏ผš * ๅˆ›ๅปบไบบ๏ผšflyou * ้‚ฎ็ฎฑ๏ผšfangjaylong@gmail.com * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2016/4/19 15:45 * ไฟฎๆ”นๅค‡ๆณจ๏ผš * ็‰ˆๆœฌ๏ผš@version V1.0 * ============================================================ **/ public class ImageListModelImpl implements ImageListModel { @Override public void GetImageList(final String type, final int page, final GetImageListenter listener) { Observable<List<ImageListDomain>> observable = Observable.create(new Observable.OnSubscribe<List<ImageListDomain>>() { @Override public void call(Subscriber<? super List<ImageListDomain>> subscriber) { List<ImageListDomain> imageListDomainList = new ArrayList(); try {
Document document = Jsoup.connect(Constant.BASE_URL + type+page).get();
flyou/Girls
app/src/main/java/com/flyou/girls/ui/mainImageList/view/ImageListView.java
// Path: app/src/main/java/com/flyou/girls/ui/mainImageList/domain/ImageListDomain.java // public class ImageListDomain implements Parcelable { // private String linkUrl; // private String imageUrl; // private String imgaeTitle; // // // // public String getLinkUrl() { // return linkUrl; // } // // public void setLinkUrl(String linkUrl) { // this.linkUrl = linkUrl; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImgaeTitle() { // return imgaeTitle; // } // // public void setImgaeTitle(String imgaeTitle) { // this.imgaeTitle = imgaeTitle; // } // // public ImageListDomain(String linkUrl, String imageUrl, String imgaeTitle) { // this.linkUrl = linkUrl; // this.imageUrl = imageUrl; // this.imgaeTitle = imgaeTitle; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.linkUrl); // dest.writeString(this.imageUrl); // dest.writeString(this.imgaeTitle); // } // // protected ImageListDomain(Parcel in) { // this.linkUrl = in.readString(); // this.imageUrl = in.readString(); // this.imgaeTitle = in.readString(); // } // // public static final Parcelable.Creator<ImageListDomain> CREATOR = new Parcelable.Creator<ImageListDomain>() { // @Override // public ImageListDomain createFromParcel(Parcel source) { // return new ImageListDomain(source); // } // // @Override // public ImageListDomain[] newArray(int size) { // return new ImageListDomain[size]; // } // }; // }
import com.flyou.girls.ui.mainImageList.domain.ImageListDomain; import java.util.List;
package com.flyou.girls.ui.mainImageList.view; /** * ============================================================ * ้กน็›ฎๅ็งฐ๏ผšGirls * ๅŒ…ๅ็งฐ๏ผšcom.flyou.girls.ui.ImageList.view * ๆ–‡ไปถๅ๏ผšImageListView * ็ฑปๆ่ฟฐ๏ผš * ๅˆ›ๅปบไบบ๏ผšflyou * ้‚ฎ็ฎฑ๏ผšfangjaylong@gmail.com * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2016/4/19 16:42 * ไฟฎๆ”นๅค‡ๆณจ๏ผš * ็‰ˆๆœฌ๏ผš@version V1.0 * ============================================================ **/ public interface ImageListView { void showLaoding(); void hideLoading(); void showLoadFaild( Exception e);
// Path: app/src/main/java/com/flyou/girls/ui/mainImageList/domain/ImageListDomain.java // public class ImageListDomain implements Parcelable { // private String linkUrl; // private String imageUrl; // private String imgaeTitle; // // // // public String getLinkUrl() { // return linkUrl; // } // // public void setLinkUrl(String linkUrl) { // this.linkUrl = linkUrl; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImgaeTitle() { // return imgaeTitle; // } // // public void setImgaeTitle(String imgaeTitle) { // this.imgaeTitle = imgaeTitle; // } // // public ImageListDomain(String linkUrl, String imageUrl, String imgaeTitle) { // this.linkUrl = linkUrl; // this.imageUrl = imageUrl; // this.imgaeTitle = imgaeTitle; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.linkUrl); // dest.writeString(this.imageUrl); // dest.writeString(this.imgaeTitle); // } // // protected ImageListDomain(Parcel in) { // this.linkUrl = in.readString(); // this.imageUrl = in.readString(); // this.imgaeTitle = in.readString(); // } // // public static final Parcelable.Creator<ImageListDomain> CREATOR = new Parcelable.Creator<ImageListDomain>() { // @Override // public ImageListDomain createFromParcel(Parcel source) { // return new ImageListDomain(source); // } // // @Override // public ImageListDomain[] newArray(int size) { // return new ImageListDomain[size]; // } // }; // } // Path: app/src/main/java/com/flyou/girls/ui/mainImageList/view/ImageListView.java import com.flyou.girls.ui.mainImageList.domain.ImageListDomain; import java.util.List; package com.flyou.girls.ui.mainImageList.view; /** * ============================================================ * ้กน็›ฎๅ็งฐ๏ผšGirls * ๅŒ…ๅ็งฐ๏ผšcom.flyou.girls.ui.ImageList.view * ๆ–‡ไปถๅ๏ผšImageListView * ็ฑปๆ่ฟฐ๏ผš * ๅˆ›ๅปบไบบ๏ผšflyou * ้‚ฎ็ฎฑ๏ผšfangjaylong@gmail.com * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2016/4/19 16:42 * ไฟฎๆ”นๅค‡ๆณจ๏ผš * ็‰ˆๆœฌ๏ผš@version V1.0 * ============================================================ **/ public interface ImageListView { void showLaoding(); void hideLoading(); void showLoadFaild( Exception e);
void receiveImageList(List<ImageListDomain> imageListDomains);
flyou/Girls
app/src/main/java/com/flyou/girls/ui/ImageViewPagerActivity.java
// Path: app/src/main/java/com/flyou/girls/ui/typeImageList/domain/TypeImageDomain.java // public class TypeImageDomain implements Parcelable { // private int width; // private int height; // private String url; // private String fullSizeUrl; // // public TypeImageDomain(int width, int height, String url, String fullSizeUrl) { // this.width = width; // this.height = height; // this.url = url; // this.fullSizeUrl = fullSizeUrl; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getFullSizeUrl() { // return fullSizeUrl; // } // // public void setFullSizeUrl(String fullSizeUrl) { // this.fullSizeUrl = fullSizeUrl; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.width); // dest.writeInt(this.height); // dest.writeString(this.url); // dest.writeString(this.fullSizeUrl); // } // // protected TypeImageDomain(Parcel in) { // this.width = in.readInt(); // this.height = in.readInt(); // this.url = in.readString(); // this.fullSizeUrl = in.readString(); // } // // public static final Parcelable.Creator<TypeImageDomain> CREATOR = new Parcelable.Creator<TypeImageDomain>() { // @Override // public TypeImageDomain createFromParcel(Parcel source) { // return new TypeImageDomain(source); // } // // @Override // public TypeImageDomain[] newArray(int size) { // return new TypeImageDomain[size]; // } // }; // }
import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; import com.flyou.girls.R; import com.flyou.girls.ui.typeImageList.domain.TypeImageDomain; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import uk.co.senab.photoview.PhotoViewAttacher;
package com.flyou.girls.ui; public class ImageViewPagerActivity extends AppCompatActivity { private ViewPager mViewPager; private TextView mNumTV;
// Path: app/src/main/java/com/flyou/girls/ui/typeImageList/domain/TypeImageDomain.java // public class TypeImageDomain implements Parcelable { // private int width; // private int height; // private String url; // private String fullSizeUrl; // // public TypeImageDomain(int width, int height, String url, String fullSizeUrl) { // this.width = width; // this.height = height; // this.url = url; // this.fullSizeUrl = fullSizeUrl; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getFullSizeUrl() { // return fullSizeUrl; // } // // public void setFullSizeUrl(String fullSizeUrl) { // this.fullSizeUrl = fullSizeUrl; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.width); // dest.writeInt(this.height); // dest.writeString(this.url); // dest.writeString(this.fullSizeUrl); // } // // protected TypeImageDomain(Parcel in) { // this.width = in.readInt(); // this.height = in.readInt(); // this.url = in.readString(); // this.fullSizeUrl = in.readString(); // } // // public static final Parcelable.Creator<TypeImageDomain> CREATOR = new Parcelable.Creator<TypeImageDomain>() { // @Override // public TypeImageDomain createFromParcel(Parcel source) { // return new TypeImageDomain(source); // } // // @Override // public TypeImageDomain[] newArray(int size) { // return new TypeImageDomain[size]; // } // }; // } // Path: app/src/main/java/com/flyou/girls/ui/ImageViewPagerActivity.java import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; import com.flyou.girls.R; import com.flyou.girls.ui.typeImageList.domain.TypeImageDomain; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import uk.co.senab.photoview.PhotoViewAttacher; package com.flyou.girls.ui; public class ImageViewPagerActivity extends AppCompatActivity { private ViewPager mViewPager; private TextView mNumTV;
private ArrayList<TypeImageDomain> mImageList;
flyou/Girls
app/src/main/java/com/flyou/girls/ui/typeImageList/model/TypeImageListModelImpl.java
// Path: app/src/main/java/com/flyou/girls/ui/typeImageList/domain/TypeImageDomain.java // public class TypeImageDomain implements Parcelable { // private int width; // private int height; // private String url; // private String fullSizeUrl; // // public TypeImageDomain(int width, int height, String url, String fullSizeUrl) { // this.width = width; // this.height = height; // this.url = url; // this.fullSizeUrl = fullSizeUrl; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getFullSizeUrl() { // return fullSizeUrl; // } // // public void setFullSizeUrl(String fullSizeUrl) { // this.fullSizeUrl = fullSizeUrl; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.width); // dest.writeInt(this.height); // dest.writeString(this.url); // dest.writeString(this.fullSizeUrl); // } // // protected TypeImageDomain(Parcel in) { // this.width = in.readInt(); // this.height = in.readInt(); // this.url = in.readString(); // this.fullSizeUrl = in.readString(); // } // // public static final Parcelable.Creator<TypeImageDomain> CREATOR = new Parcelable.Creator<TypeImageDomain>() { // @Override // public TypeImageDomain createFromParcel(Parcel source) { // return new TypeImageDomain(source); // } // // @Override // public TypeImageDomain[] newArray(int size) { // return new TypeImageDomain[size]; // } // }; // }
import com.flyou.girls.ui.typeImageList.domain.TypeImageDomain; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers;
package com.flyou.girls.ui.typeImageList.model; /** * ============================================================ * ้กน็›ฎๅ็งฐ๏ผšGirls * ๅŒ…ๅ็งฐ๏ผšcom.flyou.girls.ui.typeImageList.model * ๆ–‡ไปถๅ๏ผšTypeImageListModelImpl * ็ฑปๆ่ฟฐ๏ผš * ๅˆ›ๅปบไบบ๏ผšflyou * ้‚ฎ็ฎฑ๏ผšfangjaylong@gmail.com * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2016/4/20 14:43 * ไฟฎๆ”นๅค‡ๆณจ๏ผš * ็‰ˆๆœฌ๏ผš@version V1.0 * ============================================================ **/ public class TypeImageListModelImpl implements TypeImageListModel { @Override public void getTypeImageList(final String url, final TypeImageListModelImpl.OnGetTypeImageListener litener) {
// Path: app/src/main/java/com/flyou/girls/ui/typeImageList/domain/TypeImageDomain.java // public class TypeImageDomain implements Parcelable { // private int width; // private int height; // private String url; // private String fullSizeUrl; // // public TypeImageDomain(int width, int height, String url, String fullSizeUrl) { // this.width = width; // this.height = height; // this.url = url; // this.fullSizeUrl = fullSizeUrl; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getFullSizeUrl() { // return fullSizeUrl; // } // // public void setFullSizeUrl(String fullSizeUrl) { // this.fullSizeUrl = fullSizeUrl; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.width); // dest.writeInt(this.height); // dest.writeString(this.url); // dest.writeString(this.fullSizeUrl); // } // // protected TypeImageDomain(Parcel in) { // this.width = in.readInt(); // this.height = in.readInt(); // this.url = in.readString(); // this.fullSizeUrl = in.readString(); // } // // public static final Parcelable.Creator<TypeImageDomain> CREATOR = new Parcelable.Creator<TypeImageDomain>() { // @Override // public TypeImageDomain createFromParcel(Parcel source) { // return new TypeImageDomain(source); // } // // @Override // public TypeImageDomain[] newArray(int size) { // return new TypeImageDomain[size]; // } // }; // } // Path: app/src/main/java/com/flyou/girls/ui/typeImageList/model/TypeImageListModelImpl.java import com.flyou.girls.ui.typeImageList.domain.TypeImageDomain; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; package com.flyou.girls.ui.typeImageList.model; /** * ============================================================ * ้กน็›ฎๅ็งฐ๏ผšGirls * ๅŒ…ๅ็งฐ๏ผšcom.flyou.girls.ui.typeImageList.model * ๆ–‡ไปถๅ๏ผšTypeImageListModelImpl * ็ฑปๆ่ฟฐ๏ผš * ๅˆ›ๅปบไบบ๏ผšflyou * ้‚ฎ็ฎฑ๏ผšfangjaylong@gmail.com * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2016/4/20 14:43 * ไฟฎๆ”นๅค‡ๆณจ๏ผš * ็‰ˆๆœฌ๏ผš@version V1.0 * ============================================================ **/ public class TypeImageListModelImpl implements TypeImageListModel { @Override public void getTypeImageList(final String url, final TypeImageListModelImpl.OnGetTypeImageListener litener) {
Observable<List<TypeImageDomain>> observable = Observable.create(new Observable.OnSubscribe<List<TypeImageDomain>>() {
flyou/Girls
app/src/main/java/com/flyou/girls/ui/typeImageList/view/TypeImageListView.java
// Path: app/src/main/java/com/flyou/girls/ui/typeImageList/domain/TypeImageDomain.java // public class TypeImageDomain implements Parcelable { // private int width; // private int height; // private String url; // private String fullSizeUrl; // // public TypeImageDomain(int width, int height, String url, String fullSizeUrl) { // this.width = width; // this.height = height; // this.url = url; // this.fullSizeUrl = fullSizeUrl; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getFullSizeUrl() { // return fullSizeUrl; // } // // public void setFullSizeUrl(String fullSizeUrl) { // this.fullSizeUrl = fullSizeUrl; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.width); // dest.writeInt(this.height); // dest.writeString(this.url); // dest.writeString(this.fullSizeUrl); // } // // protected TypeImageDomain(Parcel in) { // this.width = in.readInt(); // this.height = in.readInt(); // this.url = in.readString(); // this.fullSizeUrl = in.readString(); // } // // public static final Parcelable.Creator<TypeImageDomain> CREATOR = new Parcelable.Creator<TypeImageDomain>() { // @Override // public TypeImageDomain createFromParcel(Parcel source) { // return new TypeImageDomain(source); // } // // @Override // public TypeImageDomain[] newArray(int size) { // return new TypeImageDomain[size]; // } // }; // }
import com.flyou.girls.ui.typeImageList.domain.TypeImageDomain; import java.util.List;
package com.flyou.girls.ui.typeImageList.view; /** * ============================================================ * ้กน็›ฎๅ็งฐ๏ผšGirls * ๅŒ…ๅ็งฐ๏ผšcom.flyou.girls.ui.typeImageList.view * ๆ–‡ไปถๅ๏ผšTypeImageListView * ็ฑปๆ่ฟฐ๏ผš * ๅˆ›ๅปบไบบ๏ผšflyou * ้‚ฎ็ฎฑ๏ผšfangjaylong@gmail.com * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2016/4/20 14:46 * ไฟฎๆ”นๅค‡ๆณจ๏ผš * ็‰ˆๆœฌ๏ผš@version V1.0 * ============================================================ **/ public interface TypeImageListView { void showLaoding(); void hideLoading(); void showLoadFaild( Exception e);
// Path: app/src/main/java/com/flyou/girls/ui/typeImageList/domain/TypeImageDomain.java // public class TypeImageDomain implements Parcelable { // private int width; // private int height; // private String url; // private String fullSizeUrl; // // public TypeImageDomain(int width, int height, String url, String fullSizeUrl) { // this.width = width; // this.height = height; // this.url = url; // this.fullSizeUrl = fullSizeUrl; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getFullSizeUrl() { // return fullSizeUrl; // } // // public void setFullSizeUrl(String fullSizeUrl) { // this.fullSizeUrl = fullSizeUrl; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.width); // dest.writeInt(this.height); // dest.writeString(this.url); // dest.writeString(this.fullSizeUrl); // } // // protected TypeImageDomain(Parcel in) { // this.width = in.readInt(); // this.height = in.readInt(); // this.url = in.readString(); // this.fullSizeUrl = in.readString(); // } // // public static final Parcelable.Creator<TypeImageDomain> CREATOR = new Parcelable.Creator<TypeImageDomain>() { // @Override // public TypeImageDomain createFromParcel(Parcel source) { // return new TypeImageDomain(source); // } // // @Override // public TypeImageDomain[] newArray(int size) { // return new TypeImageDomain[size]; // } // }; // } // Path: app/src/main/java/com/flyou/girls/ui/typeImageList/view/TypeImageListView.java import com.flyou.girls.ui.typeImageList.domain.TypeImageDomain; import java.util.List; package com.flyou.girls.ui.typeImageList.view; /** * ============================================================ * ้กน็›ฎๅ็งฐ๏ผšGirls * ๅŒ…ๅ็งฐ๏ผšcom.flyou.girls.ui.typeImageList.view * ๆ–‡ไปถๅ๏ผšTypeImageListView * ็ฑปๆ่ฟฐ๏ผš * ๅˆ›ๅปบไบบ๏ผšflyou * ้‚ฎ็ฎฑ๏ผšfangjaylong@gmail.com * ๅˆ›ๅปบๆ—ถ้—ด๏ผš2016/4/20 14:46 * ไฟฎๆ”นๅค‡ๆณจ๏ผš * ็‰ˆๆœฌ๏ผš@version V1.0 * ============================================================ **/ public interface TypeImageListView { void showLaoding(); void hideLoading(); void showLoadFaild( Exception e);
void receiveImageList(List<TypeImageDomain> typeImageDomains);
HujiangTechnology/RestVolley
restvolley/src/main/java/com/hujiang/restvolley/image/ImageLoaderCompat.java
// Path: restvolley/src/main/java/com/hujiang/restvolley/TaskScheduler.java // public class TaskScheduler { // // private static Handler mHandler = new Handler(Looper.getMainLooper()); // private static ThreadPool mThreadPool = new ThreadPool("com.hujiang.restvolley.task_scheduler"); // // /** // * ไปฅ่ฝป้‡็บง็š„ๆ–นๅผๆ‰ง่กŒไธ€ไธชๅผ‚ๆญฅไปปๅŠก. // * @param backgroundTaskRunnable ๅผ‚ๆญฅไปปๅŠก // */ // public static void execute(final Runnable backgroundTaskRunnable) { // if (backgroundTaskRunnable != null) { // mThreadPool.addTask(backgroundTaskRunnable); // } // } // // /** // * execute a task. // * @param backgroundRunnable background task // * @param foregroundRunnable foreground task // */ // public static void execute(final Runnable backgroundRunnable, final Runnable foregroundRunnable) { // mThreadPool.addTask(new Runnable() { // @Override // public void run() { // if (backgroundRunnable != null) { // backgroundRunnable.run(); // } // // if (foregroundRunnable != null) { // mHandler.post(foregroundRunnable); // } // } // }); // } // // /** // * execute a task. // * @param task {@link Task} // * @param <IT> in paramter's type // * @param <OT> out paramter's type // */ // public static <IT, OT> void execute(final Task<IT, OT> task) { // exec(task); // } // // private static <IT, OT> void exec(final Task<IT, OT> task) { // if (task != null) { // mThreadPool.addTask(new Runnable() { // @Override // public void run() { // final OT out = task.onDoInBackground(task.mInput); // mHandler.post(new Runnable() { // @Override // public void run() { // task.onPostExecuteForeground(out); // } // }); // // } // }); // } // } // }
import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.widget.ImageView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.RequestFuture; import com.hujiang.restvolley.R; import com.hujiang.restvolley.TaskScheduler; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; import java.util.Locale; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException;
public ImageContainer load(String requestUri, final ImageListener listener) { return load(requestUri, listener, null); } /** * Issues a bitmap request with the given uri if that image is not available * in the cache, and returns a bitmap container that contains all of the data * relating to the request (as well as the default image if the requested * image is not available). * @param requestUri The uri of the remote image * @param imageListener The listener to call when the remote image is loaded * @param imageLoadOption image load option. * @return A container object that contains all of the properties of the request, as well as * the currently available image (default if remote is not loaded). */ public ImageContainer load(final String requestUri, final ImageListener imageListener, final ImageLoadOption imageLoadOption) { final int maxWidth = getMaxWidth(imageLoadOption); final int maxHeight = getMaxHeight(imageLoadOption); final ImageView.ScaleType scaleType = getScaleType(imageLoadOption); final boolean isCacheEnable = isCacheEnable(imageLoadOption); final String cacheKey = generateCacheKey(requestUri, maxWidth, maxHeight, scaleType); // The bitmap did not exist in the cache, fetch it! final ImageContainer imageContainer = new ImageContainer(null, requestUri, cacheKey, LoadFrom.UNKNOWN, imageListener); // Update the caller to let them know that they should use the default bitmap. responseOnUiThread(imageContainer, true, imageListener);
// Path: restvolley/src/main/java/com/hujiang/restvolley/TaskScheduler.java // public class TaskScheduler { // // private static Handler mHandler = new Handler(Looper.getMainLooper()); // private static ThreadPool mThreadPool = new ThreadPool("com.hujiang.restvolley.task_scheduler"); // // /** // * ไปฅ่ฝป้‡็บง็š„ๆ–นๅผๆ‰ง่กŒไธ€ไธชๅผ‚ๆญฅไปปๅŠก. // * @param backgroundTaskRunnable ๅผ‚ๆญฅไปปๅŠก // */ // public static void execute(final Runnable backgroundTaskRunnable) { // if (backgroundTaskRunnable != null) { // mThreadPool.addTask(backgroundTaskRunnable); // } // } // // /** // * execute a task. // * @param backgroundRunnable background task // * @param foregroundRunnable foreground task // */ // public static void execute(final Runnable backgroundRunnable, final Runnable foregroundRunnable) { // mThreadPool.addTask(new Runnable() { // @Override // public void run() { // if (backgroundRunnable != null) { // backgroundRunnable.run(); // } // // if (foregroundRunnable != null) { // mHandler.post(foregroundRunnable); // } // } // }); // } // // /** // * execute a task. // * @param task {@link Task} // * @param <IT> in paramter's type // * @param <OT> out paramter's type // */ // public static <IT, OT> void execute(final Task<IT, OT> task) { // exec(task); // } // // private static <IT, OT> void exec(final Task<IT, OT> task) { // if (task != null) { // mThreadPool.addTask(new Runnable() { // @Override // public void run() { // final OT out = task.onDoInBackground(task.mInput); // mHandler.post(new Runnable() { // @Override // public void run() { // task.onPostExecuteForeground(out); // } // }); // // } // }); // } // } // } // Path: restvolley/src/main/java/com/hujiang/restvolley/image/ImageLoaderCompat.java import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.widget.ImageView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.RequestFuture; import com.hujiang.restvolley.R; import com.hujiang.restvolley.TaskScheduler; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; import java.util.Locale; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; public ImageContainer load(String requestUri, final ImageListener listener) { return load(requestUri, listener, null); } /** * Issues a bitmap request with the given uri if that image is not available * in the cache, and returns a bitmap container that contains all of the data * relating to the request (as well as the default image if the requested * image is not available). * @param requestUri The uri of the remote image * @param imageListener The listener to call when the remote image is loaded * @param imageLoadOption image load option. * @return A container object that contains all of the properties of the request, as well as * the currently available image (default if remote is not loaded). */ public ImageContainer load(final String requestUri, final ImageListener imageListener, final ImageLoadOption imageLoadOption) { final int maxWidth = getMaxWidth(imageLoadOption); final int maxHeight = getMaxHeight(imageLoadOption); final ImageView.ScaleType scaleType = getScaleType(imageLoadOption); final boolean isCacheEnable = isCacheEnable(imageLoadOption); final String cacheKey = generateCacheKey(requestUri, maxWidth, maxHeight, scaleType); // The bitmap did not exist in the cache, fetch it! final ImageContainer imageContainer = new ImageContainer(null, requestUri, cacheKey, LoadFrom.UNKNOWN, imageListener); // Update the caller to let them know that they should use the default bitmap. responseOnUiThread(imageContainer, true, imageListener);
TaskScheduler.execute(new Runnable() {
HujiangTechnology/RestVolley
restvolley/src/main/java/com/hujiang/restvolley/compat/RVNetwork.java
// Path: restvolley/src/main/java/com/android/volley/RetryError.java // public class RetryError extends VolleyError { // }
import android.os.SystemClock; import com.android.volley.AuthFailureError; import com.android.volley.Cache; import com.android.volley.Network; import com.android.volley.NetworkError; import com.android.volley.NetworkResponse; import com.android.volley.NoConnectionError; import com.android.volley.RedirectError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.RetryError; import com.android.volley.RetryPolicy; import com.android.volley.ServerError; import com.android.volley.TimeoutError; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.ByteArrayPool; import com.android.volley.toolbox.HttpStack; import com.android.volley.toolbox.PoolingByteArrayOutputStream; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.impl.cookie.DateUtils; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.TreeMap;
VolleyLog.d("HTTP response for request=<%s> [lifetime=%d], [size=%s], " + "[rc=%d], [retryCount=%s]", request, requestLifetime, responseContents != null ? responseContents.length : "null", statusLine.getStatusCode(), request.getRetryPolicy().getCurrentRetryCount()); } } /** * Attempts to prepare the request for a retry. If there are no more attempts remaining in the * request's retry policy, a timeout exception is thrown. * @param request The request to use. */ protected static void attemptRetryOnException(String logPrefix, Request<?> request, VolleyError exception) throws VolleyError { RetryPolicy retryPolicy = request.getRetryPolicy(); int oldTimeout = request.getTimeoutMs(); try { retryPolicy.retry(exception); } catch (VolleyError e) { request.addMarker(String.format("%s-timeout-giveup [timeout=%s]", logPrefix, oldTimeout)); throw e; } request.addMarker(String.format("%s-retry [timeout=%s]", logPrefix, oldTimeout)); //reentry the requestQueue RequestQueue requestQueue = getRequestQueue(request); if (requestQueue != null) { requestQueue.add(request); }
// Path: restvolley/src/main/java/com/android/volley/RetryError.java // public class RetryError extends VolleyError { // } // Path: restvolley/src/main/java/com/hujiang/restvolley/compat/RVNetwork.java import android.os.SystemClock; import com.android.volley.AuthFailureError; import com.android.volley.Cache; import com.android.volley.Network; import com.android.volley.NetworkError; import com.android.volley.NetworkResponse; import com.android.volley.NoConnectionError; import com.android.volley.RedirectError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.RetryError; import com.android.volley.RetryPolicy; import com.android.volley.ServerError; import com.android.volley.TimeoutError; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.ByteArrayPool; import com.android.volley.toolbox.HttpStack; import com.android.volley.toolbox.PoolingByteArrayOutputStream; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.impl.cookie.DateUtils; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; VolleyLog.d("HTTP response for request=<%s> [lifetime=%d], [size=%s], " + "[rc=%d], [retryCount=%s]", request, requestLifetime, responseContents != null ? responseContents.length : "null", statusLine.getStatusCode(), request.getRetryPolicy().getCurrentRetryCount()); } } /** * Attempts to prepare the request for a retry. If there are no more attempts remaining in the * request's retry policy, a timeout exception is thrown. * @param request The request to use. */ protected static void attemptRetryOnException(String logPrefix, Request<?> request, VolleyError exception) throws VolleyError { RetryPolicy retryPolicy = request.getRetryPolicy(); int oldTimeout = request.getTimeoutMs(); try { retryPolicy.retry(exception); } catch (VolleyError e) { request.addMarker(String.format("%s-timeout-giveup [timeout=%s]", logPrefix, oldTimeout)); throw e; } request.addMarker(String.format("%s-retry [timeout=%s]", logPrefix, oldTimeout)); //reentry the requestQueue RequestQueue requestQueue = getRequestQueue(request); if (requestQueue != null) { requestQueue.add(request); }
throw new RetryError();
HujiangTechnology/RestVolley
restvolley/src/main/java/com/hujiang/restvolley/image/RestVolleyImageCache.java
// Path: restvolley/src/main/java/com/hujiang/restvolley/MD5Utils.java // public class MD5Utils { // // private static final int HEX_FF = 0xFF; // // /** // * // * @param key for disk. // * @return hash key. // */ // public static String hashKeyForDisk(String key) { // String cacheKey; // try { // final MessageDigest mDigest = MessageDigest.getInstance("MD5"); // mDigest.update(key.getBytes()); // cacheKey = bytesToHexString(mDigest.digest()); // } catch (NoSuchAlgorithmException e) { // cacheKey = String.valueOf(key.hashCode()); // } // return cacheKey; // } // // private static String bytesToHexString(byte[] bytes) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < bytes.length; i++) { // String hex = Integer.toHexString(HEX_FF & bytes[i]); // if (hex.length() == 1) { // sb.append('0'); // } // sb.append(hex); // } // return sb.toString(); // } // // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/TaskScheduler.java // public class TaskScheduler { // // private static Handler mHandler = new Handler(Looper.getMainLooper()); // private static ThreadPool mThreadPool = new ThreadPool("com.hujiang.restvolley.task_scheduler"); // // /** // * ไปฅ่ฝป้‡็บง็š„ๆ–นๅผๆ‰ง่กŒไธ€ไธชๅผ‚ๆญฅไปปๅŠก. // * @param backgroundTaskRunnable ๅผ‚ๆญฅไปปๅŠก // */ // public static void execute(final Runnable backgroundTaskRunnable) { // if (backgroundTaskRunnable != null) { // mThreadPool.addTask(backgroundTaskRunnable); // } // } // // /** // * execute a task. // * @param backgroundRunnable background task // * @param foregroundRunnable foreground task // */ // public static void execute(final Runnable backgroundRunnable, final Runnable foregroundRunnable) { // mThreadPool.addTask(new Runnable() { // @Override // public void run() { // if (backgroundRunnable != null) { // backgroundRunnable.run(); // } // // if (foregroundRunnable != null) { // mHandler.post(foregroundRunnable); // } // } // }); // } // // /** // * execute a task. // * @param task {@link Task} // * @param <IT> in paramter's type // * @param <OT> out paramter's type // */ // public static <IT, OT> void execute(final Task<IT, OT> task) { // exec(task); // } // // private static <IT, OT> void exec(final Task<IT, OT> task) { // if (task != null) { // mThreadPool.addTask(new Runnable() { // @Override // public void run() { // final OT out = task.onDoInBackground(task.mInput); // mHandler.post(new Runnable() { // @Override // public void run() { // task.onPostExecuteForeground(out); // } // }); // // } // }); // } // } // }
import android.content.Context; import android.graphics.Bitmap; import android.os.Build; import android.os.Environment; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.LruCache; import android.widget.ImageView; import com.android.volley.VolleyLog; import com.hujiang.restvolley.MD5Utils; import com.hujiang.restvolley.TaskScheduler; import com.jakewharton.disklrucache.DiskLruCache; import java.io.File; import java.io.IOException; import java.io.OutputStream;
} public static int getMaxBitmapCacheSize(Context context) { return getDefaultCacheSize(context, 2); } /** * get bitmap size. * * @param bitmap Bitmap * @return bitmapSize */ public static int getBitmapSize(Bitmap bitmap) { if (bitmap == null) { return 0; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //API 19 return bitmap.getAllocationByteCount(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { //API 12 return bitmap.getByteCount(); } //earlier version return bitmap.getRowBytes() * bitmap.getHeight(); } private void putBitmapToDiskLruCache(final String key, final Bitmap bitmap) {
// Path: restvolley/src/main/java/com/hujiang/restvolley/MD5Utils.java // public class MD5Utils { // // private static final int HEX_FF = 0xFF; // // /** // * // * @param key for disk. // * @return hash key. // */ // public static String hashKeyForDisk(String key) { // String cacheKey; // try { // final MessageDigest mDigest = MessageDigest.getInstance("MD5"); // mDigest.update(key.getBytes()); // cacheKey = bytesToHexString(mDigest.digest()); // } catch (NoSuchAlgorithmException e) { // cacheKey = String.valueOf(key.hashCode()); // } // return cacheKey; // } // // private static String bytesToHexString(byte[] bytes) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < bytes.length; i++) { // String hex = Integer.toHexString(HEX_FF & bytes[i]); // if (hex.length() == 1) { // sb.append('0'); // } // sb.append(hex); // } // return sb.toString(); // } // // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/TaskScheduler.java // public class TaskScheduler { // // private static Handler mHandler = new Handler(Looper.getMainLooper()); // private static ThreadPool mThreadPool = new ThreadPool("com.hujiang.restvolley.task_scheduler"); // // /** // * ไปฅ่ฝป้‡็บง็š„ๆ–นๅผๆ‰ง่กŒไธ€ไธชๅผ‚ๆญฅไปปๅŠก. // * @param backgroundTaskRunnable ๅผ‚ๆญฅไปปๅŠก // */ // public static void execute(final Runnable backgroundTaskRunnable) { // if (backgroundTaskRunnable != null) { // mThreadPool.addTask(backgroundTaskRunnable); // } // } // // /** // * execute a task. // * @param backgroundRunnable background task // * @param foregroundRunnable foreground task // */ // public static void execute(final Runnable backgroundRunnable, final Runnable foregroundRunnable) { // mThreadPool.addTask(new Runnable() { // @Override // public void run() { // if (backgroundRunnable != null) { // backgroundRunnable.run(); // } // // if (foregroundRunnable != null) { // mHandler.post(foregroundRunnable); // } // } // }); // } // // /** // * execute a task. // * @param task {@link Task} // * @param <IT> in paramter's type // * @param <OT> out paramter's type // */ // public static <IT, OT> void execute(final Task<IT, OT> task) { // exec(task); // } // // private static <IT, OT> void exec(final Task<IT, OT> task) { // if (task != null) { // mThreadPool.addTask(new Runnable() { // @Override // public void run() { // final OT out = task.onDoInBackground(task.mInput); // mHandler.post(new Runnable() { // @Override // public void run() { // task.onPostExecuteForeground(out); // } // }); // // } // }); // } // } // } // Path: restvolley/src/main/java/com/hujiang/restvolley/image/RestVolleyImageCache.java import android.content.Context; import android.graphics.Bitmap; import android.os.Build; import android.os.Environment; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.LruCache; import android.widget.ImageView; import com.android.volley.VolleyLog; import com.hujiang.restvolley.MD5Utils; import com.hujiang.restvolley.TaskScheduler; import com.jakewharton.disklrucache.DiskLruCache; import java.io.File; import java.io.IOException; import java.io.OutputStream; } public static int getMaxBitmapCacheSize(Context context) { return getDefaultCacheSize(context, 2); } /** * get bitmap size. * * @param bitmap Bitmap * @return bitmapSize */ public static int getBitmapSize(Bitmap bitmap) { if (bitmap == null) { return 0; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //API 19 return bitmap.getAllocationByteCount(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { //API 12 return bitmap.getByteCount(); } //earlier version return bitmap.getRowBytes() * bitmap.getHeight(); } private void putBitmapToDiskLruCache(final String key, final Bitmap bitmap) {
TaskScheduler.execute(new Runnable() {
HujiangTechnology/RestVolley
restvolley/src/main/java/com/hujiang/restvolley/image/RestVolleyImageCache.java
// Path: restvolley/src/main/java/com/hujiang/restvolley/MD5Utils.java // public class MD5Utils { // // private static final int HEX_FF = 0xFF; // // /** // * // * @param key for disk. // * @return hash key. // */ // public static String hashKeyForDisk(String key) { // String cacheKey; // try { // final MessageDigest mDigest = MessageDigest.getInstance("MD5"); // mDigest.update(key.getBytes()); // cacheKey = bytesToHexString(mDigest.digest()); // } catch (NoSuchAlgorithmException e) { // cacheKey = String.valueOf(key.hashCode()); // } // return cacheKey; // } // // private static String bytesToHexString(byte[] bytes) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < bytes.length; i++) { // String hex = Integer.toHexString(HEX_FF & bytes[i]); // if (hex.length() == 1) { // sb.append('0'); // } // sb.append(hex); // } // return sb.toString(); // } // // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/TaskScheduler.java // public class TaskScheduler { // // private static Handler mHandler = new Handler(Looper.getMainLooper()); // private static ThreadPool mThreadPool = new ThreadPool("com.hujiang.restvolley.task_scheduler"); // // /** // * ไปฅ่ฝป้‡็บง็š„ๆ–นๅผๆ‰ง่กŒไธ€ไธชๅผ‚ๆญฅไปปๅŠก. // * @param backgroundTaskRunnable ๅผ‚ๆญฅไปปๅŠก // */ // public static void execute(final Runnable backgroundTaskRunnable) { // if (backgroundTaskRunnable != null) { // mThreadPool.addTask(backgroundTaskRunnable); // } // } // // /** // * execute a task. // * @param backgroundRunnable background task // * @param foregroundRunnable foreground task // */ // public static void execute(final Runnable backgroundRunnable, final Runnable foregroundRunnable) { // mThreadPool.addTask(new Runnable() { // @Override // public void run() { // if (backgroundRunnable != null) { // backgroundRunnable.run(); // } // // if (foregroundRunnable != null) { // mHandler.post(foregroundRunnable); // } // } // }); // } // // /** // * execute a task. // * @param task {@link Task} // * @param <IT> in paramter's type // * @param <OT> out paramter's type // */ // public static <IT, OT> void execute(final Task<IT, OT> task) { // exec(task); // } // // private static <IT, OT> void exec(final Task<IT, OT> task) { // if (task != null) { // mThreadPool.addTask(new Runnable() { // @Override // public void run() { // final OT out = task.onDoInBackground(task.mInput); // mHandler.post(new Runnable() { // @Override // public void run() { // task.onPostExecuteForeground(out); // } // }); // // } // }); // } // } // }
import android.content.Context; import android.graphics.Bitmap; import android.os.Build; import android.os.Environment; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.LruCache; import android.widget.ImageView; import com.android.volley.VolleyLog; import com.hujiang.restvolley.MD5Utils; import com.hujiang.restvolley.TaskScheduler; import com.jakewharton.disklrucache.DiskLruCache; import java.io.File; import java.io.IOException; import java.io.OutputStream;
} } } catch (Exception e) { e.printStackTrace(); } } }); } private Bitmap getBitmapFromDiskLruCache(String key) { if (getDiskCache() == null) { return null; } String cachePath = new StringBuilder(getDiskCachePath()).append(File.separator).append(key).append(".0").toString(); File cacheFile = new File(cachePath); try { if (cacheFile.exists()) { return ImageProcessor.decode(cachePath); } } catch (Exception e) { e.printStackTrace(); } catch (OutOfMemoryError error) { VolleyLog.e("Caught OOM for %d byte image, uri=%s", cacheFile.length(), cachePath); } return null; } private String generateKey(String target) {
// Path: restvolley/src/main/java/com/hujiang/restvolley/MD5Utils.java // public class MD5Utils { // // private static final int HEX_FF = 0xFF; // // /** // * // * @param key for disk. // * @return hash key. // */ // public static String hashKeyForDisk(String key) { // String cacheKey; // try { // final MessageDigest mDigest = MessageDigest.getInstance("MD5"); // mDigest.update(key.getBytes()); // cacheKey = bytesToHexString(mDigest.digest()); // } catch (NoSuchAlgorithmException e) { // cacheKey = String.valueOf(key.hashCode()); // } // return cacheKey; // } // // private static String bytesToHexString(byte[] bytes) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < bytes.length; i++) { // String hex = Integer.toHexString(HEX_FF & bytes[i]); // if (hex.length() == 1) { // sb.append('0'); // } // sb.append(hex); // } // return sb.toString(); // } // // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/TaskScheduler.java // public class TaskScheduler { // // private static Handler mHandler = new Handler(Looper.getMainLooper()); // private static ThreadPool mThreadPool = new ThreadPool("com.hujiang.restvolley.task_scheduler"); // // /** // * ไปฅ่ฝป้‡็บง็š„ๆ–นๅผๆ‰ง่กŒไธ€ไธชๅผ‚ๆญฅไปปๅŠก. // * @param backgroundTaskRunnable ๅผ‚ๆญฅไปปๅŠก // */ // public static void execute(final Runnable backgroundTaskRunnable) { // if (backgroundTaskRunnable != null) { // mThreadPool.addTask(backgroundTaskRunnable); // } // } // // /** // * execute a task. // * @param backgroundRunnable background task // * @param foregroundRunnable foreground task // */ // public static void execute(final Runnable backgroundRunnable, final Runnable foregroundRunnable) { // mThreadPool.addTask(new Runnable() { // @Override // public void run() { // if (backgroundRunnable != null) { // backgroundRunnable.run(); // } // // if (foregroundRunnable != null) { // mHandler.post(foregroundRunnable); // } // } // }); // } // // /** // * execute a task. // * @param task {@link Task} // * @param <IT> in paramter's type // * @param <OT> out paramter's type // */ // public static <IT, OT> void execute(final Task<IT, OT> task) { // exec(task); // } // // private static <IT, OT> void exec(final Task<IT, OT> task) { // if (task != null) { // mThreadPool.addTask(new Runnable() { // @Override // public void run() { // final OT out = task.onDoInBackground(task.mInput); // mHandler.post(new Runnable() { // @Override // public void run() { // task.onPostExecuteForeground(out); // } // }); // // } // }); // } // } // } // Path: restvolley/src/main/java/com/hujiang/restvolley/image/RestVolleyImageCache.java import android.content.Context; import android.graphics.Bitmap; import android.os.Build; import android.os.Environment; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.LruCache; import android.widget.ImageView; import com.android.volley.VolleyLog; import com.hujiang.restvolley.MD5Utils; import com.hujiang.restvolley.TaskScheduler; import com.jakewharton.disklrucache.DiskLruCache; import java.io.File; import java.io.IOException; import java.io.OutputStream; } } } catch (Exception e) { e.printStackTrace(); } } }); } private Bitmap getBitmapFromDiskLruCache(String key) { if (getDiskCache() == null) { return null; } String cachePath = new StringBuilder(getDiskCachePath()).append(File.separator).append(key).append(".0").toString(); File cacheFile = new File(cachePath); try { if (cacheFile.exists()) { return ImageProcessor.decode(cachePath); } } catch (Exception e) { e.printStackTrace(); } catch (OutOfMemoryError error) { VolleyLog.e("Caught OOM for %d byte image, uri=%s", cacheFile.length(), cachePath); } return null; } private String generateKey(String target) {
return MD5Utils.hashKeyForDisk(target);
HujiangTechnology/RestVolley
restvolley/src/main/java/com/hujiang/restvolley/image/RVImageRequest.java
// Path: restvolley/src/main/java/com/hujiang/restvolley/MD5Utils.java // public class MD5Utils { // // private static final int HEX_FF = 0xFF; // // /** // * // * @param key for disk. // * @return hash key. // */ // public static String hashKeyForDisk(String key) { // String cacheKey; // try { // final MessageDigest mDigest = MessageDigest.getInstance("MD5"); // mDigest.update(key.getBytes()); // cacheKey = bytesToHexString(mDigest.digest()); // } catch (NoSuchAlgorithmException e) { // cacheKey = String.valueOf(key.hashCode()); // } // return cacheKey; // } // // private static String bytesToHexString(byte[] bytes) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < bytes.length; i++) { // String hex = Integer.toHexString(HEX_FF & bytes[i]); // if (hex.length() == 1) { // sb.append('0'); // } // sb.append(hex); // } // return sb.toString(); // } // // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/compat/StreamBasedNetworkResponse.java // public class StreamBasedNetworkResponse extends NetworkResponse { // // /** Raw data inputStream from this response. */ // public final InputStream inputStream; // public final long contentLength; // // public StreamBasedNetworkResponse(int statusCode, InputStream inputStream, long contentLength, Map<String, String> headers, boolean notModified, long networkTimeMs) { // super(statusCode, null, headers, notModified, networkTimeMs); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(int statusCode, InputStream inputStream, long contentLength, Map<String, String> headers, boolean notModified) { // super(statusCode, null, headers, notModified); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(InputStream inputStream, long contentLength) { // super(null); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(InputStream inputStream, long contentLength, Map<String, String> headers) { // super(null, headers); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(int statusCode, byte[] data, Map<String, String> headers, boolean notModified, long networkTimeMs) { // super(statusCode, data, headers, notModified, networkTimeMs); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // // public StreamBasedNetworkResponse(int statusCode, byte[] data, Map<String, String> headers, boolean notModified) { // super(statusCode, data, headers, notModified); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // // public StreamBasedNetworkResponse(byte[] data) { // super(data); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // // public StreamBasedNetworkResponse(byte[] data, Map<String, String> headers) { // super(data, headers); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/image/ImageProcessor.java // public static final int BYTE_IN_PIX = 4;
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.ImageView; import com.android.volley.DefaultRetryPolicy; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyLog; import com.hujiang.restvolley.MD5Utils; import com.hujiang.restvolley.compat.StreamBasedNetworkResponse; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import static com.hujiang.restvolley.image.ImageProcessor.BYTE_IN_PIX;
if ((resized * ratio) < maxSecondary) { resized = (int) (maxSecondary / ratio); } return resized; } if ((resized * ratio) > maxSecondary) { resized = (int) (maxSecondary / ratio); } return resized; } @Override protected Response<Bitmap> parseNetworkResponse(NetworkResponse response) { // Serialize all decode on a global lock to reduce concurrent heap usage. synchronized (sDecodeLock) { try { return doParse(response); } catch (OutOfMemoryError e) { VolleyLog.e("Caught OOM for %d byte image, url=%s", response.data.length, getUrl()); return Response.error(new ParseError(e)); } } } /** * The real guts of parseNetworkResponse. Broken out for readability. */ private Response<Bitmap> doParse(NetworkResponse response) { Bitmap bitmap = null;
// Path: restvolley/src/main/java/com/hujiang/restvolley/MD5Utils.java // public class MD5Utils { // // private static final int HEX_FF = 0xFF; // // /** // * // * @param key for disk. // * @return hash key. // */ // public static String hashKeyForDisk(String key) { // String cacheKey; // try { // final MessageDigest mDigest = MessageDigest.getInstance("MD5"); // mDigest.update(key.getBytes()); // cacheKey = bytesToHexString(mDigest.digest()); // } catch (NoSuchAlgorithmException e) { // cacheKey = String.valueOf(key.hashCode()); // } // return cacheKey; // } // // private static String bytesToHexString(byte[] bytes) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < bytes.length; i++) { // String hex = Integer.toHexString(HEX_FF & bytes[i]); // if (hex.length() == 1) { // sb.append('0'); // } // sb.append(hex); // } // return sb.toString(); // } // // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/compat/StreamBasedNetworkResponse.java // public class StreamBasedNetworkResponse extends NetworkResponse { // // /** Raw data inputStream from this response. */ // public final InputStream inputStream; // public final long contentLength; // // public StreamBasedNetworkResponse(int statusCode, InputStream inputStream, long contentLength, Map<String, String> headers, boolean notModified, long networkTimeMs) { // super(statusCode, null, headers, notModified, networkTimeMs); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(int statusCode, InputStream inputStream, long contentLength, Map<String, String> headers, boolean notModified) { // super(statusCode, null, headers, notModified); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(InputStream inputStream, long contentLength) { // super(null); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(InputStream inputStream, long contentLength, Map<String, String> headers) { // super(null, headers); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(int statusCode, byte[] data, Map<String, String> headers, boolean notModified, long networkTimeMs) { // super(statusCode, data, headers, notModified, networkTimeMs); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // // public StreamBasedNetworkResponse(int statusCode, byte[] data, Map<String, String> headers, boolean notModified) { // super(statusCode, data, headers, notModified); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // // public StreamBasedNetworkResponse(byte[] data) { // super(data); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // // public StreamBasedNetworkResponse(byte[] data, Map<String, String> headers) { // super(data, headers); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/image/ImageProcessor.java // public static final int BYTE_IN_PIX = 4; // Path: restvolley/src/main/java/com/hujiang/restvolley/image/RVImageRequest.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.ImageView; import com.android.volley.DefaultRetryPolicy; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyLog; import com.hujiang.restvolley.MD5Utils; import com.hujiang.restvolley.compat.StreamBasedNetworkResponse; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import static com.hujiang.restvolley.image.ImageProcessor.BYTE_IN_PIX; if ((resized * ratio) < maxSecondary) { resized = (int) (maxSecondary / ratio); } return resized; } if ((resized * ratio) > maxSecondary) { resized = (int) (maxSecondary / ratio); } return resized; } @Override protected Response<Bitmap> parseNetworkResponse(NetworkResponse response) { // Serialize all decode on a global lock to reduce concurrent heap usage. synchronized (sDecodeLock) { try { return doParse(response); } catch (OutOfMemoryError e) { VolleyLog.e("Caught OOM for %d byte image, url=%s", response.data.length, getUrl()); return Response.error(new ParseError(e)); } } } /** * The real guts of parseNetworkResponse. Broken out for readability. */ private Response<Bitmap> doParse(NetworkResponse response) { Bitmap bitmap = null;
if (response instanceof StreamBasedNetworkResponse) {
HujiangTechnology/RestVolley
restvolley/src/main/java/com/hujiang/restvolley/image/RVImageRequest.java
// Path: restvolley/src/main/java/com/hujiang/restvolley/MD5Utils.java // public class MD5Utils { // // private static final int HEX_FF = 0xFF; // // /** // * // * @param key for disk. // * @return hash key. // */ // public static String hashKeyForDisk(String key) { // String cacheKey; // try { // final MessageDigest mDigest = MessageDigest.getInstance("MD5"); // mDigest.update(key.getBytes()); // cacheKey = bytesToHexString(mDigest.digest()); // } catch (NoSuchAlgorithmException e) { // cacheKey = String.valueOf(key.hashCode()); // } // return cacheKey; // } // // private static String bytesToHexString(byte[] bytes) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < bytes.length; i++) { // String hex = Integer.toHexString(HEX_FF & bytes[i]); // if (hex.length() == 1) { // sb.append('0'); // } // sb.append(hex); // } // return sb.toString(); // } // // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/compat/StreamBasedNetworkResponse.java // public class StreamBasedNetworkResponse extends NetworkResponse { // // /** Raw data inputStream from this response. */ // public final InputStream inputStream; // public final long contentLength; // // public StreamBasedNetworkResponse(int statusCode, InputStream inputStream, long contentLength, Map<String, String> headers, boolean notModified, long networkTimeMs) { // super(statusCode, null, headers, notModified, networkTimeMs); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(int statusCode, InputStream inputStream, long contentLength, Map<String, String> headers, boolean notModified) { // super(statusCode, null, headers, notModified); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(InputStream inputStream, long contentLength) { // super(null); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(InputStream inputStream, long contentLength, Map<String, String> headers) { // super(null, headers); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(int statusCode, byte[] data, Map<String, String> headers, boolean notModified, long networkTimeMs) { // super(statusCode, data, headers, notModified, networkTimeMs); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // // public StreamBasedNetworkResponse(int statusCode, byte[] data, Map<String, String> headers, boolean notModified) { // super(statusCode, data, headers, notModified); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // // public StreamBasedNetworkResponse(byte[] data) { // super(data); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // // public StreamBasedNetworkResponse(byte[] data, Map<String, String> headers) { // super(data, headers); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/image/ImageProcessor.java // public static final int BYTE_IN_PIX = 4;
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.ImageView; import com.android.volley.DefaultRetryPolicy; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyLog; import com.hujiang.restvolley.MD5Utils; import com.hujiang.restvolley.compat.StreamBasedNetworkResponse; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import static com.hujiang.restvolley.image.ImageProcessor.BYTE_IN_PIX;
decodeOptions.inSampleSize = findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight); bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, decodeOptions); } return bitmap; } private Bitmap doParseStreamSafe(InputStream bitmapStream, long contentLength) { if (bitmapStream == null) { return null; } Bitmap bitmap; BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); if (contentLength <= RestVolleyImageCache.MAX_BITMAP_CACHE_SIZE) { decodeOptions.inJustDecodeBounds = false; decodeOptions.inPreferredConfig = mDecodeConfig; bitmap = BitmapFactory.decodeStream(bitmapStream, null, decodeOptions); try { bitmapStream.close(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } String diskCachePath = RestVolleyImageLoader.instance(mContext).getDiskCachePath();
// Path: restvolley/src/main/java/com/hujiang/restvolley/MD5Utils.java // public class MD5Utils { // // private static final int HEX_FF = 0xFF; // // /** // * // * @param key for disk. // * @return hash key. // */ // public static String hashKeyForDisk(String key) { // String cacheKey; // try { // final MessageDigest mDigest = MessageDigest.getInstance("MD5"); // mDigest.update(key.getBytes()); // cacheKey = bytesToHexString(mDigest.digest()); // } catch (NoSuchAlgorithmException e) { // cacheKey = String.valueOf(key.hashCode()); // } // return cacheKey; // } // // private static String bytesToHexString(byte[] bytes) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < bytes.length; i++) { // String hex = Integer.toHexString(HEX_FF & bytes[i]); // if (hex.length() == 1) { // sb.append('0'); // } // sb.append(hex); // } // return sb.toString(); // } // // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/compat/StreamBasedNetworkResponse.java // public class StreamBasedNetworkResponse extends NetworkResponse { // // /** Raw data inputStream from this response. */ // public final InputStream inputStream; // public final long contentLength; // // public StreamBasedNetworkResponse(int statusCode, InputStream inputStream, long contentLength, Map<String, String> headers, boolean notModified, long networkTimeMs) { // super(statusCode, null, headers, notModified, networkTimeMs); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(int statusCode, InputStream inputStream, long contentLength, Map<String, String> headers, boolean notModified) { // super(statusCode, null, headers, notModified); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(InputStream inputStream, long contentLength) { // super(null); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(InputStream inputStream, long contentLength, Map<String, String> headers) { // super(null, headers); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(int statusCode, byte[] data, Map<String, String> headers, boolean notModified, long networkTimeMs) { // super(statusCode, data, headers, notModified, networkTimeMs); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // // public StreamBasedNetworkResponse(int statusCode, byte[] data, Map<String, String> headers, boolean notModified) { // super(statusCode, data, headers, notModified); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // // public StreamBasedNetworkResponse(byte[] data) { // super(data); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // // public StreamBasedNetworkResponse(byte[] data, Map<String, String> headers) { // super(data, headers); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/image/ImageProcessor.java // public static final int BYTE_IN_PIX = 4; // Path: restvolley/src/main/java/com/hujiang/restvolley/image/RVImageRequest.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.ImageView; import com.android.volley.DefaultRetryPolicy; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyLog; import com.hujiang.restvolley.MD5Utils; import com.hujiang.restvolley.compat.StreamBasedNetworkResponse; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import static com.hujiang.restvolley.image.ImageProcessor.BYTE_IN_PIX; decodeOptions.inSampleSize = findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight); bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, decodeOptions); } return bitmap; } private Bitmap doParseStreamSafe(InputStream bitmapStream, long contentLength) { if (bitmapStream == null) { return null; } Bitmap bitmap; BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); if (contentLength <= RestVolleyImageCache.MAX_BITMAP_CACHE_SIZE) { decodeOptions.inJustDecodeBounds = false; decodeOptions.inPreferredConfig = mDecodeConfig; bitmap = BitmapFactory.decodeStream(bitmapStream, null, decodeOptions); try { bitmapStream.close(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } String diskCachePath = RestVolleyImageLoader.instance(mContext).getDiskCachePath();
String bitmapCachePath = diskCachePath + File.separator + MD5Utils.hashKeyForDisk(getUrl());
HujiangTechnology/RestVolley
restvolley/src/main/java/com/hujiang/restvolley/image/RVImageRequest.java
// Path: restvolley/src/main/java/com/hujiang/restvolley/MD5Utils.java // public class MD5Utils { // // private static final int HEX_FF = 0xFF; // // /** // * // * @param key for disk. // * @return hash key. // */ // public static String hashKeyForDisk(String key) { // String cacheKey; // try { // final MessageDigest mDigest = MessageDigest.getInstance("MD5"); // mDigest.update(key.getBytes()); // cacheKey = bytesToHexString(mDigest.digest()); // } catch (NoSuchAlgorithmException e) { // cacheKey = String.valueOf(key.hashCode()); // } // return cacheKey; // } // // private static String bytesToHexString(byte[] bytes) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < bytes.length; i++) { // String hex = Integer.toHexString(HEX_FF & bytes[i]); // if (hex.length() == 1) { // sb.append('0'); // } // sb.append(hex); // } // return sb.toString(); // } // // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/compat/StreamBasedNetworkResponse.java // public class StreamBasedNetworkResponse extends NetworkResponse { // // /** Raw data inputStream from this response. */ // public final InputStream inputStream; // public final long contentLength; // // public StreamBasedNetworkResponse(int statusCode, InputStream inputStream, long contentLength, Map<String, String> headers, boolean notModified, long networkTimeMs) { // super(statusCode, null, headers, notModified, networkTimeMs); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(int statusCode, InputStream inputStream, long contentLength, Map<String, String> headers, boolean notModified) { // super(statusCode, null, headers, notModified); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(InputStream inputStream, long contentLength) { // super(null); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(InputStream inputStream, long contentLength, Map<String, String> headers) { // super(null, headers); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(int statusCode, byte[] data, Map<String, String> headers, boolean notModified, long networkTimeMs) { // super(statusCode, data, headers, notModified, networkTimeMs); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // // public StreamBasedNetworkResponse(int statusCode, byte[] data, Map<String, String> headers, boolean notModified) { // super(statusCode, data, headers, notModified); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // // public StreamBasedNetworkResponse(byte[] data) { // super(data); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // // public StreamBasedNetworkResponse(byte[] data, Map<String, String> headers) { // super(data, headers); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/image/ImageProcessor.java // public static final int BYTE_IN_PIX = 4;
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.ImageView; import com.android.volley.DefaultRetryPolicy; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyLog; import com.hujiang.restvolley.MD5Utils; import com.hujiang.restvolley.compat.StreamBasedNetworkResponse; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import static com.hujiang.restvolley.image.ImageProcessor.BYTE_IN_PIX;
BufferedOutputStream bitmapOutputStream = null; try { bitmapOutputStream = new BufferedOutputStream(new FileOutputStream(bitmapCache)); byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = bitmapStream.read(buffer)) != -1) { bitmapOutputStream.write(buffer, 0, len); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (bitmapStream != null) { bitmapStream.close(); } if (bitmapOutputStream != null) { bitmapOutputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } decodeOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(bitmapCachePath); int actualWidth = decodeOptions.outWidth; int actualHeight = decodeOptions.outHeight; if (mMaxWidth == 0 && mMaxHeight == 0) { int sampleSize = 1;
// Path: restvolley/src/main/java/com/hujiang/restvolley/MD5Utils.java // public class MD5Utils { // // private static final int HEX_FF = 0xFF; // // /** // * // * @param key for disk. // * @return hash key. // */ // public static String hashKeyForDisk(String key) { // String cacheKey; // try { // final MessageDigest mDigest = MessageDigest.getInstance("MD5"); // mDigest.update(key.getBytes()); // cacheKey = bytesToHexString(mDigest.digest()); // } catch (NoSuchAlgorithmException e) { // cacheKey = String.valueOf(key.hashCode()); // } // return cacheKey; // } // // private static String bytesToHexString(byte[] bytes) { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < bytes.length; i++) { // String hex = Integer.toHexString(HEX_FF & bytes[i]); // if (hex.length() == 1) { // sb.append('0'); // } // sb.append(hex); // } // return sb.toString(); // } // // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/compat/StreamBasedNetworkResponse.java // public class StreamBasedNetworkResponse extends NetworkResponse { // // /** Raw data inputStream from this response. */ // public final InputStream inputStream; // public final long contentLength; // // public StreamBasedNetworkResponse(int statusCode, InputStream inputStream, long contentLength, Map<String, String> headers, boolean notModified, long networkTimeMs) { // super(statusCode, null, headers, notModified, networkTimeMs); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(int statusCode, InputStream inputStream, long contentLength, Map<String, String> headers, boolean notModified) { // super(statusCode, null, headers, notModified); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(InputStream inputStream, long contentLength) { // super(null); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(InputStream inputStream, long contentLength, Map<String, String> headers) { // super(null, headers); // this.inputStream = inputStream; // this.contentLength = contentLength; // } // // public StreamBasedNetworkResponse(int statusCode, byte[] data, Map<String, String> headers, boolean notModified, long networkTimeMs) { // super(statusCode, data, headers, notModified, networkTimeMs); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // // public StreamBasedNetworkResponse(int statusCode, byte[] data, Map<String, String> headers, boolean notModified) { // super(statusCode, data, headers, notModified); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // // public StreamBasedNetworkResponse(byte[] data) { // super(data); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // // public StreamBasedNetworkResponse(byte[] data, Map<String, String> headers) { // super(data, headers); // this.inputStream = null; // this.contentLength = data != null ? data.length : 0; // } // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/image/ImageProcessor.java // public static final int BYTE_IN_PIX = 4; // Path: restvolley/src/main/java/com/hujiang/restvolley/image/RVImageRequest.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.ImageView; import com.android.volley.DefaultRetryPolicy; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyLog; import com.hujiang.restvolley.MD5Utils; import com.hujiang.restvolley.compat.StreamBasedNetworkResponse; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import static com.hujiang.restvolley.image.ImageProcessor.BYTE_IN_PIX; BufferedOutputStream bitmapOutputStream = null; try { bitmapOutputStream = new BufferedOutputStream(new FileOutputStream(bitmapCache)); byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = bitmapStream.read(buffer)) != -1) { bitmapOutputStream.write(buffer, 0, len); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (bitmapStream != null) { bitmapStream.close(); } if (bitmapOutputStream != null) { bitmapOutputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } decodeOptions.inJustDecodeBounds = true; BitmapFactory.decodeFile(bitmapCachePath); int actualWidth = decodeOptions.outWidth; int actualHeight = decodeOptions.outHeight; if (mMaxWidth == 0 && mMaxHeight == 0) { int sampleSize = 1;
long desired_size = actualWidth * actualHeight * BYTE_IN_PIX;
HujiangTechnology/RestVolley
app/src/main/java/com/hujiang/restvolley/demo/HTTPSActivity.java
// Path: restvolley/src/main/java/com/hujiang/restvolley/webapi/RestVolleyCallback.java // public abstract class RestVolleyCallback<T> { // // protected Exception mException; // // public void setException(Exception e) { // mException = e; // } // // public Exception getException() { // return mException; // } // // /** // * start request callback. // * @param request {@link RestVolleyRequest} // */ // public void onStart(RestVolleyRequest request) { // // } // // /** // * finish request callback. // * @param request {@link RestVolleyRequest} // */ // public void onFinished(RestVolleyRequest request) { // // } // // /** // * request success callback. // * @param statusCode http status code. // * @param data response data. // * @param headers response headers. // * @param notModified data not modified. // * @param networkTimeMs request times. // * @param message request message. // */ // public abstract void onSuccess(int statusCode, T data, Map<String, String> headers, boolean notModified, long networkTimeMs, String message); // // /** // * request fail callback. // * @param statusCode http status code. // * @param data response data. // * @param headers response headers. // * @param notModified data not modified. // * @param networkTimeMs request times. // * @param message request message. // */ // public abstract void onFail(int statusCode, T data, Map<String, String> headers, boolean notModified, long networkTimeMs, String message); // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/webapi/request/GetRequest.java // public class GetRequest extends RestVolleyRequestWithNoBody<GetRequest> { // /** // * constructor. // * @param context {@link Context} // */ // public GetRequest(Context context) { // super(context, Request.Method.GET); // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import com.hujiang.restvolley.webapi.RestVolleyCallback; import com.hujiang.restvolley.webapi.request.GetRequest; import java.util.Map;
package com.hujiang.restvolley.demo; public class HTTPSActivity extends AppCompatActivity { private TextView mRequestContentView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_https); mRequestContentView = (TextView)findViewById(R.id.txt_request_content); findViewById(R.id.btn_office_ca).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
// Path: restvolley/src/main/java/com/hujiang/restvolley/webapi/RestVolleyCallback.java // public abstract class RestVolleyCallback<T> { // // protected Exception mException; // // public void setException(Exception e) { // mException = e; // } // // public Exception getException() { // return mException; // } // // /** // * start request callback. // * @param request {@link RestVolleyRequest} // */ // public void onStart(RestVolleyRequest request) { // // } // // /** // * finish request callback. // * @param request {@link RestVolleyRequest} // */ // public void onFinished(RestVolleyRequest request) { // // } // // /** // * request success callback. // * @param statusCode http status code. // * @param data response data. // * @param headers response headers. // * @param notModified data not modified. // * @param networkTimeMs request times. // * @param message request message. // */ // public abstract void onSuccess(int statusCode, T data, Map<String, String> headers, boolean notModified, long networkTimeMs, String message); // // /** // * request fail callback. // * @param statusCode http status code. // * @param data response data. // * @param headers response headers. // * @param notModified data not modified. // * @param networkTimeMs request times. // * @param message request message. // */ // public abstract void onFail(int statusCode, T data, Map<String, String> headers, boolean notModified, long networkTimeMs, String message); // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/webapi/request/GetRequest.java // public class GetRequest extends RestVolleyRequestWithNoBody<GetRequest> { // /** // * constructor. // * @param context {@link Context} // */ // public GetRequest(Context context) { // super(context, Request.Method.GET); // } // } // Path: app/src/main/java/com/hujiang/restvolley/demo/HTTPSActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import com.hujiang.restvolley.webapi.RestVolleyCallback; import com.hujiang.restvolley.webapi.request.GetRequest; import java.util.Map; package com.hujiang.restvolley.demo; public class HTTPSActivity extends AppCompatActivity { private TextView mRequestContentView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_https); mRequestContentView = (TextView)findViewById(R.id.txt_request_content); findViewById(R.id.btn_office_ca).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
new GetRequest(HTTPSActivity.this).url("https://pass.hjapi.com/v1.1").execute(new RestVolleyCallback<String>() {
HujiangTechnology/RestVolley
app/src/main/java/com/hujiang/restvolley/demo/HTTPSActivity.java
// Path: restvolley/src/main/java/com/hujiang/restvolley/webapi/RestVolleyCallback.java // public abstract class RestVolleyCallback<T> { // // protected Exception mException; // // public void setException(Exception e) { // mException = e; // } // // public Exception getException() { // return mException; // } // // /** // * start request callback. // * @param request {@link RestVolleyRequest} // */ // public void onStart(RestVolleyRequest request) { // // } // // /** // * finish request callback. // * @param request {@link RestVolleyRequest} // */ // public void onFinished(RestVolleyRequest request) { // // } // // /** // * request success callback. // * @param statusCode http status code. // * @param data response data. // * @param headers response headers. // * @param notModified data not modified. // * @param networkTimeMs request times. // * @param message request message. // */ // public abstract void onSuccess(int statusCode, T data, Map<String, String> headers, boolean notModified, long networkTimeMs, String message); // // /** // * request fail callback. // * @param statusCode http status code. // * @param data response data. // * @param headers response headers. // * @param notModified data not modified. // * @param networkTimeMs request times. // * @param message request message. // */ // public abstract void onFail(int statusCode, T data, Map<String, String> headers, boolean notModified, long networkTimeMs, String message); // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/webapi/request/GetRequest.java // public class GetRequest extends RestVolleyRequestWithNoBody<GetRequest> { // /** // * constructor. // * @param context {@link Context} // */ // public GetRequest(Context context) { // super(context, Request.Method.GET); // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import com.hujiang.restvolley.webapi.RestVolleyCallback; import com.hujiang.restvolley.webapi.request.GetRequest; import java.util.Map;
package com.hujiang.restvolley.demo; public class HTTPSActivity extends AppCompatActivity { private TextView mRequestContentView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_https); mRequestContentView = (TextView)findViewById(R.id.txt_request_content); findViewById(R.id.btn_office_ca).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
// Path: restvolley/src/main/java/com/hujiang/restvolley/webapi/RestVolleyCallback.java // public abstract class RestVolleyCallback<T> { // // protected Exception mException; // // public void setException(Exception e) { // mException = e; // } // // public Exception getException() { // return mException; // } // // /** // * start request callback. // * @param request {@link RestVolleyRequest} // */ // public void onStart(RestVolleyRequest request) { // // } // // /** // * finish request callback. // * @param request {@link RestVolleyRequest} // */ // public void onFinished(RestVolleyRequest request) { // // } // // /** // * request success callback. // * @param statusCode http status code. // * @param data response data. // * @param headers response headers. // * @param notModified data not modified. // * @param networkTimeMs request times. // * @param message request message. // */ // public abstract void onSuccess(int statusCode, T data, Map<String, String> headers, boolean notModified, long networkTimeMs, String message); // // /** // * request fail callback. // * @param statusCode http status code. // * @param data response data. // * @param headers response headers. // * @param notModified data not modified. // * @param networkTimeMs request times. // * @param message request message. // */ // public abstract void onFail(int statusCode, T data, Map<String, String> headers, boolean notModified, long networkTimeMs, String message); // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/webapi/request/GetRequest.java // public class GetRequest extends RestVolleyRequestWithNoBody<GetRequest> { // /** // * constructor. // * @param context {@link Context} // */ // public GetRequest(Context context) { // super(context, Request.Method.GET); // } // } // Path: app/src/main/java/com/hujiang/restvolley/demo/HTTPSActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import com.hujiang.restvolley.webapi.RestVolleyCallback; import com.hujiang.restvolley.webapi.request.GetRequest; import java.util.Map; package com.hujiang.restvolley.demo; public class HTTPSActivity extends AppCompatActivity { private TextView mRequestContentView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_https); mRequestContentView = (TextView)findViewById(R.id.txt_request_content); findViewById(R.id.btn_office_ca).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
new GetRequest(HTTPSActivity.this).url("https://pass.hjapi.com/v1.1").execute(new RestVolleyCallback<String>() {
HujiangTechnology/RestVolley
app/src/main/java/com/hujiang/restvolley/demo/RestfulAPIActivity.java
// Path: restvolley/src/main/java/com/hujiang/restvolley/webapi/RestVolleyCallback.java // public abstract class RestVolleyCallback<T> { // // protected Exception mException; // // public void setException(Exception e) { // mException = e; // } // // public Exception getException() { // return mException; // } // // /** // * start request callback. // * @param request {@link RestVolleyRequest} // */ // public void onStart(RestVolleyRequest request) { // // } // // /** // * finish request callback. // * @param request {@link RestVolleyRequest} // */ // public void onFinished(RestVolleyRequest request) { // // } // // /** // * request success callback. // * @param statusCode http status code. // * @param data response data. // * @param headers response headers. // * @param notModified data not modified. // * @param networkTimeMs request times. // * @param message request message. // */ // public abstract void onSuccess(int statusCode, T data, Map<String, String> headers, boolean notModified, long networkTimeMs, String message); // // /** // * request fail callback. // * @param statusCode http status code. // * @param data response data. // * @param headers response headers. // * @param notModified data not modified. // * @param networkTimeMs request times. // * @param message request message. // */ // public abstract void onFail(int statusCode, T data, Map<String, String> headers, boolean notModified, long networkTimeMs, String message); // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/webapi/request/GetRequest.java // public class GetRequest extends RestVolleyRequestWithNoBody<GetRequest> { // /** // * constructor. // * @param context {@link Context} // */ // public GetRequest(Context context) { // super(context, Request.Method.GET); // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.android.volley.DefaultRetryPolicy; import com.hujiang.restvolley.webapi.RestVolleyCallback; import com.hujiang.restvolley.webapi.request.GetRequest; import java.util.Map;
package com.hujiang.restvolley.demo; public class RestfulAPIActivity extends AppCompatActivity { private static final String TAG = RestfulAPIActivity.class.getSimpleName(); private static final String[] CONCURRENCE_URLS = { "https://www.google.co.in/" , "http://www.baidu.com" , "http://stackoverflow.com/" , "http://www.hujiang.com" , "https://bintray.com/" , "http://www.infoq.com/cn/" }; private LinearLayout mRestGroup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_restful_api); mRestGroup = (LinearLayout) findViewById(R.id.rest_group); findViewById(R.id.btn_restful_api).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (final String s : CONCURRENCE_URLS) {
// Path: restvolley/src/main/java/com/hujiang/restvolley/webapi/RestVolleyCallback.java // public abstract class RestVolleyCallback<T> { // // protected Exception mException; // // public void setException(Exception e) { // mException = e; // } // // public Exception getException() { // return mException; // } // // /** // * start request callback. // * @param request {@link RestVolleyRequest} // */ // public void onStart(RestVolleyRequest request) { // // } // // /** // * finish request callback. // * @param request {@link RestVolleyRequest} // */ // public void onFinished(RestVolleyRequest request) { // // } // // /** // * request success callback. // * @param statusCode http status code. // * @param data response data. // * @param headers response headers. // * @param notModified data not modified. // * @param networkTimeMs request times. // * @param message request message. // */ // public abstract void onSuccess(int statusCode, T data, Map<String, String> headers, boolean notModified, long networkTimeMs, String message); // // /** // * request fail callback. // * @param statusCode http status code. // * @param data response data. // * @param headers response headers. // * @param notModified data not modified. // * @param networkTimeMs request times. // * @param message request message. // */ // public abstract void onFail(int statusCode, T data, Map<String, String> headers, boolean notModified, long networkTimeMs, String message); // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/webapi/request/GetRequest.java // public class GetRequest extends RestVolleyRequestWithNoBody<GetRequest> { // /** // * constructor. // * @param context {@link Context} // */ // public GetRequest(Context context) { // super(context, Request.Method.GET); // } // } // Path: app/src/main/java/com/hujiang/restvolley/demo/RestfulAPIActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.android.volley.DefaultRetryPolicy; import com.hujiang.restvolley.webapi.RestVolleyCallback; import com.hujiang.restvolley.webapi.request.GetRequest; import java.util.Map; package com.hujiang.restvolley.demo; public class RestfulAPIActivity extends AppCompatActivity { private static final String TAG = RestfulAPIActivity.class.getSimpleName(); private static final String[] CONCURRENCE_URLS = { "https://www.google.co.in/" , "http://www.baidu.com" , "http://stackoverflow.com/" , "http://www.hujiang.com" , "https://bintray.com/" , "http://www.infoq.com/cn/" }; private LinearLayout mRestGroup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_restful_api); mRestGroup = (LinearLayout) findViewById(R.id.rest_group); findViewById(R.id.btn_restful_api).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (final String s : CONCURRENCE_URLS) {
new GetRequest(RestfulAPIActivity.this)
HujiangTechnology/RestVolley
app/src/main/java/com/hujiang/restvolley/demo/RestfulAPIActivity.java
// Path: restvolley/src/main/java/com/hujiang/restvolley/webapi/RestVolleyCallback.java // public abstract class RestVolleyCallback<T> { // // protected Exception mException; // // public void setException(Exception e) { // mException = e; // } // // public Exception getException() { // return mException; // } // // /** // * start request callback. // * @param request {@link RestVolleyRequest} // */ // public void onStart(RestVolleyRequest request) { // // } // // /** // * finish request callback. // * @param request {@link RestVolleyRequest} // */ // public void onFinished(RestVolleyRequest request) { // // } // // /** // * request success callback. // * @param statusCode http status code. // * @param data response data. // * @param headers response headers. // * @param notModified data not modified. // * @param networkTimeMs request times. // * @param message request message. // */ // public abstract void onSuccess(int statusCode, T data, Map<String, String> headers, boolean notModified, long networkTimeMs, String message); // // /** // * request fail callback. // * @param statusCode http status code. // * @param data response data. // * @param headers response headers. // * @param notModified data not modified. // * @param networkTimeMs request times. // * @param message request message. // */ // public abstract void onFail(int statusCode, T data, Map<String, String> headers, boolean notModified, long networkTimeMs, String message); // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/webapi/request/GetRequest.java // public class GetRequest extends RestVolleyRequestWithNoBody<GetRequest> { // /** // * constructor. // * @param context {@link Context} // */ // public GetRequest(Context context) { // super(context, Request.Method.GET); // } // }
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.android.volley.DefaultRetryPolicy; import com.hujiang.restvolley.webapi.RestVolleyCallback; import com.hujiang.restvolley.webapi.request.GetRequest; import java.util.Map;
package com.hujiang.restvolley.demo; public class RestfulAPIActivity extends AppCompatActivity { private static final String TAG = RestfulAPIActivity.class.getSimpleName(); private static final String[] CONCURRENCE_URLS = { "https://www.google.co.in/" , "http://www.baidu.com" , "http://stackoverflow.com/" , "http://www.hujiang.com" , "https://bintray.com/" , "http://www.infoq.com/cn/" }; private LinearLayout mRestGroup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_restful_api); mRestGroup = (LinearLayout) findViewById(R.id.rest_group); findViewById(R.id.btn_restful_api).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (final String s : CONCURRENCE_URLS) { new GetRequest(RestfulAPIActivity.this) .url(s) .setTag(s) .setTimeout(5000) .setShouldCache(false) .setRetryPolicy(new DefaultRetryPolicy(2000, 3, 1.0f))
// Path: restvolley/src/main/java/com/hujiang/restvolley/webapi/RestVolleyCallback.java // public abstract class RestVolleyCallback<T> { // // protected Exception mException; // // public void setException(Exception e) { // mException = e; // } // // public Exception getException() { // return mException; // } // // /** // * start request callback. // * @param request {@link RestVolleyRequest} // */ // public void onStart(RestVolleyRequest request) { // // } // // /** // * finish request callback. // * @param request {@link RestVolleyRequest} // */ // public void onFinished(RestVolleyRequest request) { // // } // // /** // * request success callback. // * @param statusCode http status code. // * @param data response data. // * @param headers response headers. // * @param notModified data not modified. // * @param networkTimeMs request times. // * @param message request message. // */ // public abstract void onSuccess(int statusCode, T data, Map<String, String> headers, boolean notModified, long networkTimeMs, String message); // // /** // * request fail callback. // * @param statusCode http status code. // * @param data response data. // * @param headers response headers. // * @param notModified data not modified. // * @param networkTimeMs request times. // * @param message request message. // */ // public abstract void onFail(int statusCode, T data, Map<String, String> headers, boolean notModified, long networkTimeMs, String message); // } // // Path: restvolley/src/main/java/com/hujiang/restvolley/webapi/request/GetRequest.java // public class GetRequest extends RestVolleyRequestWithNoBody<GetRequest> { // /** // * constructor. // * @param context {@link Context} // */ // public GetRequest(Context context) { // super(context, Request.Method.GET); // } // } // Path: app/src/main/java/com/hujiang/restvolley/demo/RestfulAPIActivity.java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.android.volley.DefaultRetryPolicy; import com.hujiang.restvolley.webapi.RestVolleyCallback; import com.hujiang.restvolley.webapi.request.GetRequest; import java.util.Map; package com.hujiang.restvolley.demo; public class RestfulAPIActivity extends AppCompatActivity { private static final String TAG = RestfulAPIActivity.class.getSimpleName(); private static final String[] CONCURRENCE_URLS = { "https://www.google.co.in/" , "http://www.baidu.com" , "http://stackoverflow.com/" , "http://www.hujiang.com" , "https://bintray.com/" , "http://www.infoq.com/cn/" }; private LinearLayout mRestGroup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_restful_api); mRestGroup = (LinearLayout) findViewById(R.id.rest_group); findViewById(R.id.btn_restful_api).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (final String s : CONCURRENCE_URLS) { new GetRequest(RestfulAPIActivity.this) .url(s) .setTag(s) .setTimeout(5000) .setShouldCache(false) .setRetryPolicy(new DefaultRetryPolicy(2000, 3, 1.0f))
.execute(String.class, new RestVolleyCallback<String>() {
HujiangTechnology/RestVolley
restvolley/src/main/java/com/hujiang/restvolley/image/ImageLoaderGlobalConfig.java
// Path: restvolley/src/main/java/com/hujiang/restvolley/RequestEngine.java // public class RequestEngine { // /** // * {@link RequestQueue} of the {@link com.android.volley.toolbox.Volley}. // */ // public RequestQueue requestQueue; // /** // * {@link OkHttpClient}. // */ // public OkHttpClient okHttpClient; // // RequestEngine(RequestQueue requestQueue, OkHttpClient okHttpClient) { // this.requestQueue = requestQueue; // this.okHttpClient = okHttpClient; // } // // /** // * cancel all the request associated wht the tag from the {@link com.android.volley.toolbox.Volley} {@link RequestQueue}. // * @param tag request tag. // */ // public void cancelAll(Object tag) { // if (requestQueue != null) { // requestQueue.cancelAll(tag); // } // } // // /** // * cancel all the request in the {@link RequestQueue} of the {@link com.android.volley.toolbox.Volley}. // */ // public void cancelAll() { // if (requestQueue != null) { // requestQueue.cancelAll(new RequestQueue.RequestFilter() { // @Override // public boolean apply(Request<?> request) { // return true; // } // }); // } // } // // /** // * {@link RequestQueue} stop work. // */ // public void stop() { // if (requestQueue != null) { // requestQueue.stop(); // } // } // }
import android.content.Context; import com.hujiang.restvolley.RequestEngine;
/* * ImageLoaderConfig 2016-01-05 * Copyright (c) 2016 hujiang Co.Ltd. All right reserved(http://www.hujiang.com). * */ package com.hujiang.restvolley.image; /** * config that effects on all the image loading. * * @author simon * @version 1.0.0 * @since 2016-01-05 */ public class ImageLoaderGlobalConfig { long memCacheSize; long diskCacheSize; String diskCacheDir;
// Path: restvolley/src/main/java/com/hujiang/restvolley/RequestEngine.java // public class RequestEngine { // /** // * {@link RequestQueue} of the {@link com.android.volley.toolbox.Volley}. // */ // public RequestQueue requestQueue; // /** // * {@link OkHttpClient}. // */ // public OkHttpClient okHttpClient; // // RequestEngine(RequestQueue requestQueue, OkHttpClient okHttpClient) { // this.requestQueue = requestQueue; // this.okHttpClient = okHttpClient; // } // // /** // * cancel all the request associated wht the tag from the {@link com.android.volley.toolbox.Volley} {@link RequestQueue}. // * @param tag request tag. // */ // public void cancelAll(Object tag) { // if (requestQueue != null) { // requestQueue.cancelAll(tag); // } // } // // /** // * cancel all the request in the {@link RequestQueue} of the {@link com.android.volley.toolbox.Volley}. // */ // public void cancelAll() { // if (requestQueue != null) { // requestQueue.cancelAll(new RequestQueue.RequestFilter() { // @Override // public boolean apply(Request<?> request) { // return true; // } // }); // } // } // // /** // * {@link RequestQueue} stop work. // */ // public void stop() { // if (requestQueue != null) { // requestQueue.stop(); // } // } // } // Path: restvolley/src/main/java/com/hujiang/restvolley/image/ImageLoaderGlobalConfig.java import android.content.Context; import com.hujiang.restvolley.RequestEngine; /* * ImageLoaderConfig 2016-01-05 * Copyright (c) 2016 hujiang Co.Ltd. All right reserved(http://www.hujiang.com). * */ package com.hujiang.restvolley.image; /** * config that effects on all the image loading. * * @author simon * @version 1.0.0 * @since 2016-01-05 */ public class ImageLoaderGlobalConfig { long memCacheSize; long diskCacheSize; String diskCacheDir;
RequestEngine requestEngine;
kkung/kakao-android-sdk-standalone
sdk/src/com/kakao/internal/LinkObject.java
// Path: sdk/src/com/kakao/KakaoLinkParseException.java // public class KakaoLinkParseException extends Exception { // private static final long serialVersionUID = 4539740978213889048L; // private ERROR_CODE code = ERROR_CODE.UNKNOWN; // // /** // * ์นด์นด์˜ค๋งํฌ ํ”„๋กœํ† ์ฝœ์— ๋งž์ง€ ์•Š๋Š” ๊ฒฝ์šฐ ๋˜์ง€๋Š” ์—๋Ÿฌ ์ฝ”๋“œ // */ // public enum ERROR_CODE { // /** // * ์ •์˜๋˜์ง€ ์•Š์€ ์—๋Ÿฌ // */ // UNKNOWN, // /** // * ํ•„์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ€ ๋ˆ„๋ฝ๋œ ๊ฒฝ์šฐ // */ // CORE_PARAMETER_MISSING, // /** // * ์ตœ์†Œ ์ด๋ฏธ์ง€ ์‚ฌ์ด์ฆˆ๋ณด๋‹ค ์ž‘์€ ๊ฒฝ์šฐ // */ // MINIMUM_IMAGE_SIZE_REQUIRED, // /** // * ๊ฐ™์€ ํƒ€์ž…์˜ ๋ฉ”์‹œ์ง€๊ฐ€ ๋‘๊ฐœ ์ด์ƒ ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ // */ // DUPLICATE_OBJECTS_USED, // /** // * ์ง€์›ํ•˜์ง€ ์•Š๋Š” ์ธ์ฝ”๋”ฉ์ด ์„ ์–ธ๋œ ๊ฒฝ์šฐ // */ // UNSUPPORTED_ENCODING, // /** // * JSON ํŒŒ์‹ฑ ๋„์ค‘ ์—๋Ÿฌ // */ // JSON_PARSING_ERROR // } // // /** // * exception์„ ๋˜์ง€๋Š” ์ด์œ  code๊ฐ’ // * @return {@link KakaoLinkParseException.ERROR_CODE} ์ค‘ ํ•˜๋‚˜ // */ // public ERROR_CODE getCode() { // return code; // } // // /** // * exception์„ ๋˜์ง€๋Š” ์ด์œ  code ๊ฐ’๊ณผ ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ // * @return error_cod ":" error_message // */ // public String getMessage(){ // return code != null ? code + ":" + super.getMessage() : super.getMessage(); // } // // KakaoLinkParseException(final String message) { // super(message); // } // // public KakaoLinkParseException(final ERROR_CODE code, final String e) { // super(e); // this.code = code; // } // // KakaoLinkParseException(final ERROR_CODE code, final Exception e) { // super(e); // this.code = code; // } // // }
import org.json.JSONObject; import android.text.TextUtils; import com.kakao.KakaoLinkParseException; import org.json.JSONException;
/** * Copyright 2014 Kakao Corp. * * Redistribution and modification in source or binary forms are not permitted without specific prior written permission.ย  * * 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.kakao.internal; /** * @author MJ */ public final class LinkObject { public enum OBJTYPE { UNKNOWN("", false), TEXT("label", false), IMAGE("image", false), BUTTON("button", true), TEXT_LINK("link", true); private final String value; private final boolean actionable; OBJTYPE(final String value, final boolean actionable) { this.value = value; this.actionable = actionable; } } private final OBJTYPE objType; private final String text; private final String imageSrc; private final int imageWidth; private final int imageHeight; private final Action action; private LinkObject(final OBJTYPE objType, final String msg, final String imageSrc, final int imageWidth, final int imageHeight, final Action action) { this.objType = objType; this.text = msg; this.imageSrc = imageSrc; this.imageWidth = imageWidth; this.imageHeight = imageHeight; this.action = action; }
// Path: sdk/src/com/kakao/KakaoLinkParseException.java // public class KakaoLinkParseException extends Exception { // private static final long serialVersionUID = 4539740978213889048L; // private ERROR_CODE code = ERROR_CODE.UNKNOWN; // // /** // * ์นด์นด์˜ค๋งํฌ ํ”„๋กœํ† ์ฝœ์— ๋งž์ง€ ์•Š๋Š” ๊ฒฝ์šฐ ๋˜์ง€๋Š” ์—๋Ÿฌ ์ฝ”๋“œ // */ // public enum ERROR_CODE { // /** // * ์ •์˜๋˜์ง€ ์•Š์€ ์—๋Ÿฌ // */ // UNKNOWN, // /** // * ํ•„์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ€ ๋ˆ„๋ฝ๋œ ๊ฒฝ์šฐ // */ // CORE_PARAMETER_MISSING, // /** // * ์ตœ์†Œ ์ด๋ฏธ์ง€ ์‚ฌ์ด์ฆˆ๋ณด๋‹ค ์ž‘์€ ๊ฒฝ์šฐ // */ // MINIMUM_IMAGE_SIZE_REQUIRED, // /** // * ๊ฐ™์€ ํƒ€์ž…์˜ ๋ฉ”์‹œ์ง€๊ฐ€ ๋‘๊ฐœ ์ด์ƒ ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ // */ // DUPLICATE_OBJECTS_USED, // /** // * ์ง€์›ํ•˜์ง€ ์•Š๋Š” ์ธ์ฝ”๋”ฉ์ด ์„ ์–ธ๋œ ๊ฒฝ์šฐ // */ // UNSUPPORTED_ENCODING, // /** // * JSON ํŒŒ์‹ฑ ๋„์ค‘ ์—๋Ÿฌ // */ // JSON_PARSING_ERROR // } // // /** // * exception์„ ๋˜์ง€๋Š” ์ด์œ  code๊ฐ’ // * @return {@link KakaoLinkParseException.ERROR_CODE} ์ค‘ ํ•˜๋‚˜ // */ // public ERROR_CODE getCode() { // return code; // } // // /** // * exception์„ ๋˜์ง€๋Š” ์ด์œ  code ๊ฐ’๊ณผ ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ // * @return error_cod ":" error_message // */ // public String getMessage(){ // return code != null ? code + ":" + super.getMessage() : super.getMessage(); // } // // KakaoLinkParseException(final String message) { // super(message); // } // // public KakaoLinkParseException(final ERROR_CODE code, final String e) { // super(e); // this.code = code; // } // // KakaoLinkParseException(final ERROR_CODE code, final Exception e) { // super(e); // this.code = code; // } // // } // Path: sdk/src/com/kakao/internal/LinkObject.java import org.json.JSONObject; import android.text.TextUtils; import com.kakao.KakaoLinkParseException; import org.json.JSONException; /** * Copyright 2014 Kakao Corp. * * Redistribution and modification in source or binary forms are not permitted without specific prior written permission.ย  * * 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.kakao.internal; /** * @author MJ */ public final class LinkObject { public enum OBJTYPE { UNKNOWN("", false), TEXT("label", false), IMAGE("image", false), BUTTON("button", true), TEXT_LINK("link", true); private final String value; private final boolean actionable; OBJTYPE(final String value, final boolean actionable) { this.value = value; this.actionable = actionable; } } private final OBJTYPE objType; private final String text; private final String imageSrc; private final int imageWidth; private final int imageHeight; private final Action action; private LinkObject(final OBJTYPE objType, final String msg, final String imageSrc, final int imageWidth, final int imageHeight, final Action action) { this.objType = objType; this.text = msg; this.imageSrc = imageSrc; this.imageWidth = imageWidth; this.imageHeight = imageHeight; this.action = action; }
public static LinkObject newText(final String text) throws KakaoLinkParseException {
kkung/kakao-android-sdk-standalone
sdk/src/com/kakao/authorization/authcode/AuthorizationCodeRequest.java
// Path: sdk/src/com/kakao/LoginActivity.java // public class LoginActivity extends Activity { // public static final int AUTHORIZATION_CODE_REQUEST = 1; // public static final int ACCESS_TOKEN_REQUEST = 2; // public static final String CODE_REQUEST_KEY = "authCodeRequest"; // public static final String TOKEN_REQUEST_KEY = "tokenRequest"; // // private GetterAuthorizationCode getterAuthorizationCode; // private GetterAccessToken getterAccessToken; // private final Authorizer.BackgroundProcessingListener backgroundProcessingListener = new BackgroundProcessListener(); // private final Authorizer.OnAuthorizationListener authorizationListener = new AuthorizationCallback(); // // /** // * authorize_code ๋˜๋Š” access_token ์š”์ฒญ์ด ๋“ค์–ด์˜จ๋‹ค. // */ // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.kakao_internal_login_activity); // // AuthorizationCodeRequest authCodeRequest; // AccessTokenRequest accessTokenRequest; // if (savedInstanceState != null) { // authCodeRequest = (AuthorizationCodeRequest) savedInstanceState.getSerializable(CODE_REQUEST_KEY); // accessTokenRequest = (AccessTokenRequest) savedInstanceState.getSerializable(TOKEN_REQUEST_KEY); // } else { // authCodeRequest = (AuthorizationCodeRequest) getIntent().getSerializableExtra(CODE_REQUEST_KEY); // accessTokenRequest = (AccessTokenRequest) getIntent().getSerializableExtra(TOKEN_REQUEST_KEY); // } // if (authCodeRequest != null) { // getterAuthorizationCode = new GetterAuthorizationCode(authCodeRequest); // initializeAuthorizer(getterAuthorizationCode); // getterAuthorizationCode.tryNextHandler(); // } else if (accessTokenRequest != null) { // getterAccessToken = new GetterAccessToken(accessTokenRequest); // initializeAuthorizer(getterAccessToken); // getterAccessToken.requestAccessToken(); // } else { // Logger.getInstance().d("Error : login activity created without request"); // } // } // // /** // * {@link Authorizer.BackgroundProcessingListener}์—๊ฒŒ ํ”„๋กœ์„ธ์‹ฑ์ด ๋๋‚ฌ๋‹ค๊ณ  ์•Œ๋ ค์ค€๋‹ค. // */ // @Override // protected void onPause() { // super.onPause(); // backgroundProcessingListener.onBackgroundProcessingStopped(); // } // // /** // * authorize code ๋˜๋Š” access token ์š”์ฒญ ์ค‘์ด๋ผ๋ฉด request๋ฅผ ์ €์žฅํ•ด ๋‘”๋‹ค. // */ // @Override // protected void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // if(getterAuthorizationCode != null) // outState.putSerializable(CODE_REQUEST_KEY, getterAuthorizationCode.getRequest()); // if(getterAccessToken != null) // outState.putSerializable(TOKEN_REQUEST_KEY, getterAccessToken.getRequest()); // } // // private void initializeAuthorizer(final Authorizer authorizer) { // authorizer.setLoginActivity(this); // authorizer.setOnAuthorizationListener(authorizationListener); // authorizer.setBackgroundProcessingListener(backgroundProcessingListener); // } // // private class BackgroundProcessListener implements Authorizer.BackgroundProcessingListener { // @Override // public void onBackgroundProcessingStarted() { // findViewById(R.id.kakao_login_activity_progress_bar).setVisibility(View.VISIBLE); // } // // @Override // public void onBackgroundProcessingStopped() { // findViewById(R.id.kakao_login_activity_progress_bar).setVisibility(View.GONE); // } // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (requestCode == AUTHORIZATION_CODE_REQUEST) { // getterAuthorizationCode.onActivityResult(requestCode, resultCode, data); // } // } // // private class AuthorizationCallback implements Authorizer.OnAuthorizationListener { // @Override // public void onAuthorizationCompletion(final AuthorizationResult result) { // backgroundProcessingListener.onBackgroundProcessingStopped(); // // if (result.isAuthorizationCodeRequest()) { // getterAuthorizationCode = null; // Session.getCurrentSession().onAuthCodeCompleted(result); // } else if (result.isAccessTokenRequest()) { // getterAccessToken = null; // Session.getCurrentSession().onAccessTokenCompleted(result); // } // runOnUiThread(new Runnable() { // @Override // public void run() { // finish(); // } // }); // } // } // }
import com.kakao.LoginActivity; import java.io.Serializable;
/** * Copyright 2014 Minyoung Jeong <kkungkkung@gmail.com> * Copyright 2014 Kakao Corp. * * Redistribution and modification in source or binary forms are not permitted without specific prior written permission.ย  * * 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.kakao.authorization.authcode; /** * authorization code์™€ access token์„ ์–ป๋Š” base request * * @author MJ */ public class AuthorizationCodeRequest implements Serializable { private static final long serialVersionUID = 7078182213563726736L; private String appKey; private String redirectURI; public AuthorizationCodeRequest() { } public static AuthorizationCodeRequest createNewRequest(final String appKey, final String redirectURI) { return new AuthorizationCodeRequest(appKey, redirectURI); } private AuthorizationCodeRequest(final String appKey, final String redirectURI) { this.appKey = appKey; this.redirectURI = redirectURI; } public int getRequestCode() {
// Path: sdk/src/com/kakao/LoginActivity.java // public class LoginActivity extends Activity { // public static final int AUTHORIZATION_CODE_REQUEST = 1; // public static final int ACCESS_TOKEN_REQUEST = 2; // public static final String CODE_REQUEST_KEY = "authCodeRequest"; // public static final String TOKEN_REQUEST_KEY = "tokenRequest"; // // private GetterAuthorizationCode getterAuthorizationCode; // private GetterAccessToken getterAccessToken; // private final Authorizer.BackgroundProcessingListener backgroundProcessingListener = new BackgroundProcessListener(); // private final Authorizer.OnAuthorizationListener authorizationListener = new AuthorizationCallback(); // // /** // * authorize_code ๋˜๋Š” access_token ์š”์ฒญ์ด ๋“ค์–ด์˜จ๋‹ค. // */ // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.kakao_internal_login_activity); // // AuthorizationCodeRequest authCodeRequest; // AccessTokenRequest accessTokenRequest; // if (savedInstanceState != null) { // authCodeRequest = (AuthorizationCodeRequest) savedInstanceState.getSerializable(CODE_REQUEST_KEY); // accessTokenRequest = (AccessTokenRequest) savedInstanceState.getSerializable(TOKEN_REQUEST_KEY); // } else { // authCodeRequest = (AuthorizationCodeRequest) getIntent().getSerializableExtra(CODE_REQUEST_KEY); // accessTokenRequest = (AccessTokenRequest) getIntent().getSerializableExtra(TOKEN_REQUEST_KEY); // } // if (authCodeRequest != null) { // getterAuthorizationCode = new GetterAuthorizationCode(authCodeRequest); // initializeAuthorizer(getterAuthorizationCode); // getterAuthorizationCode.tryNextHandler(); // } else if (accessTokenRequest != null) { // getterAccessToken = new GetterAccessToken(accessTokenRequest); // initializeAuthorizer(getterAccessToken); // getterAccessToken.requestAccessToken(); // } else { // Logger.getInstance().d("Error : login activity created without request"); // } // } // // /** // * {@link Authorizer.BackgroundProcessingListener}์—๊ฒŒ ํ”„๋กœ์„ธ์‹ฑ์ด ๋๋‚ฌ๋‹ค๊ณ  ์•Œ๋ ค์ค€๋‹ค. // */ // @Override // protected void onPause() { // super.onPause(); // backgroundProcessingListener.onBackgroundProcessingStopped(); // } // // /** // * authorize code ๋˜๋Š” access token ์š”์ฒญ ์ค‘์ด๋ผ๋ฉด request๋ฅผ ์ €์žฅํ•ด ๋‘”๋‹ค. // */ // @Override // protected void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // if(getterAuthorizationCode != null) // outState.putSerializable(CODE_REQUEST_KEY, getterAuthorizationCode.getRequest()); // if(getterAccessToken != null) // outState.putSerializable(TOKEN_REQUEST_KEY, getterAccessToken.getRequest()); // } // // private void initializeAuthorizer(final Authorizer authorizer) { // authorizer.setLoginActivity(this); // authorizer.setOnAuthorizationListener(authorizationListener); // authorizer.setBackgroundProcessingListener(backgroundProcessingListener); // } // // private class BackgroundProcessListener implements Authorizer.BackgroundProcessingListener { // @Override // public void onBackgroundProcessingStarted() { // findViewById(R.id.kakao_login_activity_progress_bar).setVisibility(View.VISIBLE); // } // // @Override // public void onBackgroundProcessingStopped() { // findViewById(R.id.kakao_login_activity_progress_bar).setVisibility(View.GONE); // } // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if (requestCode == AUTHORIZATION_CODE_REQUEST) { // getterAuthorizationCode.onActivityResult(requestCode, resultCode, data); // } // } // // private class AuthorizationCallback implements Authorizer.OnAuthorizationListener { // @Override // public void onAuthorizationCompletion(final AuthorizationResult result) { // backgroundProcessingListener.onBackgroundProcessingStopped(); // // if (result.isAuthorizationCodeRequest()) { // getterAuthorizationCode = null; // Session.getCurrentSession().onAuthCodeCompleted(result); // } else if (result.isAccessTokenRequest()) { // getterAccessToken = null; // Session.getCurrentSession().onAccessTokenCompleted(result); // } // runOnUiThread(new Runnable() { // @Override // public void run() { // finish(); // } // }); // } // } // } // Path: sdk/src/com/kakao/authorization/authcode/AuthorizationCodeRequest.java import com.kakao.LoginActivity; import java.io.Serializable; /** * Copyright 2014 Minyoung Jeong <kkungkkung@gmail.com> * Copyright 2014 Kakao Corp. * * Redistribution and modification in source or binary forms are not permitted without specific prior written permission.ย  * * 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.kakao.authorization.authcode; /** * authorization code์™€ access token์„ ์–ป๋Š” base request * * @author MJ */ public class AuthorizationCodeRequest implements Serializable { private static final long serialVersionUID = 7078182213563726736L; private String appKey; private String redirectURI; public AuthorizationCodeRequest() { } public static AuthorizationCodeRequest createNewRequest(final String appKey, final String redirectURI) { return new AuthorizationCodeRequest(appKey, redirectURI); } private AuthorizationCodeRequest(final String appKey, final String redirectURI) { this.appKey = appKey; this.redirectURI = redirectURI; } public int getRequestCode() {
return LoginActivity.AUTHORIZATION_CODE_REQUEST;
kkung/kakao-android-sdk-standalone
sdk/src/com/kakao/authorization/accesstoken/AccessTokenRequest.java
// Path: sdk/src/com/kakao/helper/Utility.java // public final class Utility { // private static final String TAG = Utility.class.getCanonicalName(); // // public static boolean isNullOrEmpty(final String s) { // return (s == null) || (s.length() == 0); // } // // public static Uri buildUri(final String authority, final String path) { // Uri.Builder builder = new Uri.Builder(); // builder.scheme(ServerProtocol.URL_SCHEME); // builder.authority(authority); // builder.path(path); // return builder.build(); // } // // public static Uri buildUri(final String authority, final String path, final Bundle parameters) { // Uri.Builder builder = new Uri.Builder(); // builder.scheme(ServerProtocol.URL_SCHEME); // builder.authority(authority); // builder.path(path); // for (String key : parameters.keySet()) { // Object parameter = parameters.get(key); // if (parameter instanceof String) { // builder.appendQueryParameter(key, (String) parameter); // } // } // return builder.build(); // } // // public static void putObjectInBundle(final Bundle bundle, final String key, final Object value) { // if (value instanceof String) { // bundle.putString(key, (String) value); // } else if (value instanceof Parcelable) { // bundle.putParcelable(key, (Parcelable) value); // } else if (value instanceof byte[]) { // bundle.putByteArray(key, (byte[]) value); // } else { // throw new KakaoException("attempted to add unsupported type to Bundle"); // } // } // // public static void notNull(final Object arg, final String name) { // if (arg == null) { // throw new NullPointerException("Argument '" + name + "' cannot be null"); // } // } // // public static String getMetadata(final Context context, final String key) { // try { // ApplicationInfo ai = context.getPackageManager().getApplicationInfo( // context.getPackageName(), PackageManager.GET_META_DATA); // if(ai == null) // return null; // else if(ai.metaData == null) // return null; // else // return ai.metaData.getString(key); // } catch (PackageManager.NameNotFoundException e) { // return null; // } // } // // public static ResolveInfo resolveIntent(final Context context, final Intent intent) { // return context.getPackageManager().resolveActivity(intent, 0); // } // // public static PackageInfo getPackageInfo(final Context context) { // try { // return context.getPackageManager().getPackageInfo(context.getPackageName(), // PackageManager.GET_SIGNATURES); // } catch (PackageManager.NameNotFoundException e) { // Log.w(TAG, "Unable to get PackageInfo", e); // } // return null; // } // // public static String getKeyHash(final Context context) { // PackageInfo packageInfo = getPackageInfo(context); // if (packageInfo == null) // return null; // // for (Signature signature : packageInfo.signatures) { // try { // MessageDigest md = MessageDigest.getInstance("SHA"); // md.update(signature.toByteArray()); // return android.util.Base64.encodeToString(md.digest(), android.util.Base64.NO_WRAP); // } catch (NoSuchAlgorithmException e) { // Log.w(TAG, "Unable to get MessageDigest. signature=" + signature, e); // } // } // return null; // } // }
import java.io.Serializable; import android.content.Context; import com.kakao.helper.Utility;
/** * Copyright 2014 Minyoung Jeong <kkungkkung@gmail.com> * Copyright 2014 Kakao Corp. * * Redistribution and modification in source or binary forms are not permitted without specific prior written permission.ย  * * 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.kakao.authorization.accesstoken; /** * authorization cod ๋˜๋Š” refresh token์„ ์ด์šฉํ•˜์—ฌ access token์„ ์–ป์–ด์˜ค๋Š” ์š”์ฒญ * @author MJ */ public class AccessTokenRequest implements Serializable { private static final long serialVersionUID = -7167683110703808736L; private final String appKey; private final String redirectURI; private final String keyHash; private String authorizationCode; private String refreshToken; private AccessTokenRequest(final Context context, final String appKey, final String redirectURI) { this.appKey = appKey; this.redirectURI = redirectURI;
// Path: sdk/src/com/kakao/helper/Utility.java // public final class Utility { // private static final String TAG = Utility.class.getCanonicalName(); // // public static boolean isNullOrEmpty(final String s) { // return (s == null) || (s.length() == 0); // } // // public static Uri buildUri(final String authority, final String path) { // Uri.Builder builder = new Uri.Builder(); // builder.scheme(ServerProtocol.URL_SCHEME); // builder.authority(authority); // builder.path(path); // return builder.build(); // } // // public static Uri buildUri(final String authority, final String path, final Bundle parameters) { // Uri.Builder builder = new Uri.Builder(); // builder.scheme(ServerProtocol.URL_SCHEME); // builder.authority(authority); // builder.path(path); // for (String key : parameters.keySet()) { // Object parameter = parameters.get(key); // if (parameter instanceof String) { // builder.appendQueryParameter(key, (String) parameter); // } // } // return builder.build(); // } // // public static void putObjectInBundle(final Bundle bundle, final String key, final Object value) { // if (value instanceof String) { // bundle.putString(key, (String) value); // } else if (value instanceof Parcelable) { // bundle.putParcelable(key, (Parcelable) value); // } else if (value instanceof byte[]) { // bundle.putByteArray(key, (byte[]) value); // } else { // throw new KakaoException("attempted to add unsupported type to Bundle"); // } // } // // public static void notNull(final Object arg, final String name) { // if (arg == null) { // throw new NullPointerException("Argument '" + name + "' cannot be null"); // } // } // // public static String getMetadata(final Context context, final String key) { // try { // ApplicationInfo ai = context.getPackageManager().getApplicationInfo( // context.getPackageName(), PackageManager.GET_META_DATA); // if(ai == null) // return null; // else if(ai.metaData == null) // return null; // else // return ai.metaData.getString(key); // } catch (PackageManager.NameNotFoundException e) { // return null; // } // } // // public static ResolveInfo resolveIntent(final Context context, final Intent intent) { // return context.getPackageManager().resolveActivity(intent, 0); // } // // public static PackageInfo getPackageInfo(final Context context) { // try { // return context.getPackageManager().getPackageInfo(context.getPackageName(), // PackageManager.GET_SIGNATURES); // } catch (PackageManager.NameNotFoundException e) { // Log.w(TAG, "Unable to get PackageInfo", e); // } // return null; // } // // public static String getKeyHash(final Context context) { // PackageInfo packageInfo = getPackageInfo(context); // if (packageInfo == null) // return null; // // for (Signature signature : packageInfo.signatures) { // try { // MessageDigest md = MessageDigest.getInstance("SHA"); // md.update(signature.toByteArray()); // return android.util.Base64.encodeToString(md.digest(), android.util.Base64.NO_WRAP); // } catch (NoSuchAlgorithmException e) { // Log.w(TAG, "Unable to get MessageDigest. signature=" + signature, e); // } // } // return null; // } // } // Path: sdk/src/com/kakao/authorization/accesstoken/AccessTokenRequest.java import java.io.Serializable; import android.content.Context; import com.kakao.helper.Utility; /** * Copyright 2014 Minyoung Jeong <kkungkkung@gmail.com> * Copyright 2014 Kakao Corp. * * Redistribution and modification in source or binary forms are not permitted without specific prior written permission.ย  * * 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.kakao.authorization.accesstoken; /** * authorization cod ๋˜๋Š” refresh token์„ ์ด์šฉํ•˜์—ฌ access token์„ ์–ป์–ด์˜ค๋Š” ์š”์ฒญ * @author MJ */ public class AccessTokenRequest implements Serializable { private static final long serialVersionUID = -7167683110703808736L; private final String appKey; private final String redirectURI; private final String keyHash; private String authorizationCode; private String refreshToken; private AccessTokenRequest(final Context context, final String appKey, final String redirectURI) { this.appKey = appKey; this.redirectURI = redirectURI;
this.keyHash = Utility.getKeyHash(context);
kkung/kakao-android-sdk-standalone
sdk/src/com/kakao/http/HttpResponseHandler.java
// Path: sdk/src/com/kakao/APIErrorResult.java // public class APIErrorResult { // /** // * ์—๋Ÿฌ๋ฅผ ์ผ์œผํ‚จ ์š”์ฒญ URL // */ // private String requestURL; // // {@link com.kakao.helper.ServerProtocol.ERROR_CODE_KEY}์™€ ๊ฐ™์€ ๋ณ€์ˆ˜ ์ด๋ฆ„ ์œ ์ง€. for jackson parsing // /** // * ์ˆซ์ž๋กœ ๊ตฌ์„ฑ๋œ ์—๋Ÿฌ ์ฝ”๋“œ // */ // protected int errorCode; // // //{@link com.kakao.helper.ServerProtocol.ERROR_MSG_KEY}์™€ ๊ฐ™์€ ๋ณ€์ˆ˜ ์ด๋ฆ„ ์œ ์ง€. for jackson parsing // /** // * String์œผ๋กœ ๊ตฌ์„ฑ๋œ ์ƒ์„ธํ•œ ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ // */ // protected String errorMessage; // // // for jackson // public APIErrorResult(int errorCode, String errorMessage) { // this.errorCode = errorCode; // this.errorMessage = errorMessage; // } // // public APIErrorResult(final String requestURL, final String errorMessage) { // this.requestURL = requestURL; // this.errorCode = ErrorCode.CLIENT_ERROR_CODE.getErrorCode(); // this.errorMessage = errorMessage; // } // // /** // * ์—๋Ÿฌ๋ฅผ ์ผ์œผํ‚จ ์š”์ฒญ URL์„ ๋„˜๊ฒจ์ค€๋‹ค. // * @return ์š”์ฒญ URL // */ // public String getRequestURL() { // return requestURL; // } // // /** // * ์—๋Ÿฌ๋ฅผ ์ผ์œผํ‚จ ์š”์ฒญ URL์„ ์„ค์ • ํ•œ๋‹ค. // * @param requestURL ์š”์ฒญ URL // */ // public void setRequestURL(String requestURL) { // this.requestURL = requestURL; // } // // /** // * ์ˆซ์ž๋กœ ๊ตฌ์„ฑ๋œ ์—๋Ÿฌ ์ฝ”๋“œ // * @return ์—๋Ÿฌ ์ฝ”๋“œ // */ // public int getErrorCodeInt() { // return errorCode; // } // // /** // * Enum ์—๋Ÿฌ ์ฝ”๋“œ // * @return {@link ErrorCode} ์ค‘ ํ•˜๋‚˜ // */ // public ErrorCode getErrorCode() { // return ErrorCode.valueOf(errorCode); // } // // /** // * String์œผ๋กœ ๊ตฌ์„ฑ๋œ ์ƒ์„ธํ•œ ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ // * @return ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ // */ // public String getErrorMessage() { // return errorMessage; // } // // /** // * ๊ฒฐ๊ณผ ๊ฐ์ฒด๋ฅผ String์œผ๋กœ ํ‘œํ˜„ // * @return ์š”์ฒญ URL, ์—๋Ÿฌ ์ฝ”๋“œ, ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋ฅผ ํฌํ•จํ•œ string // */ // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("APIErrorResult{"); // sb.append("requestURL='").append(requestURL).append('\''); // sb.append(", errorCode=").append(errorCode); // sb.append(", errorMessage='").append(errorMessage).append('\''); // sb.append('}'); // return sb.toString(); // } // }
import android.os.Handler; import android.os.Message; import com.kakao.APIErrorResult;
/** * Copyright 2014 Minyoung Jeong <kkungkkung@gmail.com> * Copyright 2014 Kakao Corp. * * Redistribution and modification in source or binary forms are not permitted without specific prior written permission.ย  * * 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.kakao.http; /** * Http ์š”์ฒญ ๊ฒฐ๊ณผ๋ฅผ caller thread์—๊ฒŒ ๋Œ๋ ค์ฃผ๋Š” ์—ญํ• . * ์‚ฌ์šฉ์ž๊ฐ€ ๋“ฑ๋กํ•œ callback์„ callder thread์—์„œ ์ˆ˜ํ–‰ํ•˜๋„๋ก ํ•˜๊ธฐ ์œ„ํ•จ * @param <T> : http ์š”์ฒญ์ด ์„ฑ๊ณตํ•œ ๊ฒฝ์šฐ return ๊ฐ์ฒด type. {@link #onHttpSuccess(T)} * ์‹คํŒจํ•œ ๊ฒฝ์šฐ๋Š” APIErrorResult. {@link #onHttpFailure(APIErrorResult)} * @author MJ */ public abstract class HttpResponseHandler<T> extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case HttpRequestTask.SUCCESS: onHttpSuccess((T) msg.obj); break; case HttpRequestTask.ERROR:
// Path: sdk/src/com/kakao/APIErrorResult.java // public class APIErrorResult { // /** // * ์—๋Ÿฌ๋ฅผ ์ผ์œผํ‚จ ์š”์ฒญ URL // */ // private String requestURL; // // {@link com.kakao.helper.ServerProtocol.ERROR_CODE_KEY}์™€ ๊ฐ™์€ ๋ณ€์ˆ˜ ์ด๋ฆ„ ์œ ์ง€. for jackson parsing // /** // * ์ˆซ์ž๋กœ ๊ตฌ์„ฑ๋œ ์—๋Ÿฌ ์ฝ”๋“œ // */ // protected int errorCode; // // //{@link com.kakao.helper.ServerProtocol.ERROR_MSG_KEY}์™€ ๊ฐ™์€ ๋ณ€์ˆ˜ ์ด๋ฆ„ ์œ ์ง€. for jackson parsing // /** // * String์œผ๋กœ ๊ตฌ์„ฑ๋œ ์ƒ์„ธํ•œ ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ // */ // protected String errorMessage; // // // for jackson // public APIErrorResult(int errorCode, String errorMessage) { // this.errorCode = errorCode; // this.errorMessage = errorMessage; // } // // public APIErrorResult(final String requestURL, final String errorMessage) { // this.requestURL = requestURL; // this.errorCode = ErrorCode.CLIENT_ERROR_CODE.getErrorCode(); // this.errorMessage = errorMessage; // } // // /** // * ์—๋Ÿฌ๋ฅผ ์ผ์œผํ‚จ ์š”์ฒญ URL์„ ๋„˜๊ฒจ์ค€๋‹ค. // * @return ์š”์ฒญ URL // */ // public String getRequestURL() { // return requestURL; // } // // /** // * ์—๋Ÿฌ๋ฅผ ์ผ์œผํ‚จ ์š”์ฒญ URL์„ ์„ค์ • ํ•œ๋‹ค. // * @param requestURL ์š”์ฒญ URL // */ // public void setRequestURL(String requestURL) { // this.requestURL = requestURL; // } // // /** // * ์ˆซ์ž๋กœ ๊ตฌ์„ฑ๋œ ์—๋Ÿฌ ์ฝ”๋“œ // * @return ์—๋Ÿฌ ์ฝ”๋“œ // */ // public int getErrorCodeInt() { // return errorCode; // } // // /** // * Enum ์—๋Ÿฌ ์ฝ”๋“œ // * @return {@link ErrorCode} ์ค‘ ํ•˜๋‚˜ // */ // public ErrorCode getErrorCode() { // return ErrorCode.valueOf(errorCode); // } // // /** // * String์œผ๋กœ ๊ตฌ์„ฑ๋œ ์ƒ์„ธํ•œ ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ // * @return ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ // */ // public String getErrorMessage() { // return errorMessage; // } // // /** // * ๊ฒฐ๊ณผ ๊ฐ์ฒด๋ฅผ String์œผ๋กœ ํ‘œํ˜„ // * @return ์š”์ฒญ URL, ์—๋Ÿฌ ์ฝ”๋“œ, ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋ฅผ ํฌํ•จํ•œ string // */ // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("APIErrorResult{"); // sb.append("requestURL='").append(requestURL).append('\''); // sb.append(", errorCode=").append(errorCode); // sb.append(", errorMessage='").append(errorMessage).append('\''); // sb.append('}'); // return sb.toString(); // } // } // Path: sdk/src/com/kakao/http/HttpResponseHandler.java import android.os.Handler; import android.os.Message; import com.kakao.APIErrorResult; /** * Copyright 2014 Minyoung Jeong <kkungkkung@gmail.com> * Copyright 2014 Kakao Corp. * * Redistribution and modification in source or binary forms are not permitted without specific prior written permission.ย  * * 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.kakao.http; /** * Http ์š”์ฒญ ๊ฒฐ๊ณผ๋ฅผ caller thread์—๊ฒŒ ๋Œ๋ ค์ฃผ๋Š” ์—ญํ• . * ์‚ฌ์šฉ์ž๊ฐ€ ๋“ฑ๋กํ•œ callback์„ callder thread์—์„œ ์ˆ˜ํ–‰ํ•˜๋„๋ก ํ•˜๊ธฐ ์œ„ํ•จ * @param <T> : http ์š”์ฒญ์ด ์„ฑ๊ณตํ•œ ๊ฒฝ์šฐ return ๊ฐ์ฒด type. {@link #onHttpSuccess(T)} * ์‹คํŒจํ•œ ๊ฒฝ์šฐ๋Š” APIErrorResult. {@link #onHttpFailure(APIErrorResult)} * @author MJ */ public abstract class HttpResponseHandler<T> extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case HttpRequestTask.SUCCESS: onHttpSuccess((T) msg.obj); break; case HttpRequestTask.ERROR:
onHttpFailure((APIErrorResult) msg.obj);
kkung/kakao-android-sdk-standalone
sdk/src/com/kakao/helper/TalkProtocol.java
// Path: sdk/src/com/kakao/authorization/authcode/AuthorizationCodeRequest.java // public class AuthorizationCodeRequest implements Serializable { // private static final long serialVersionUID = 7078182213563726736L; // private String appKey; // private String redirectURI; // // public AuthorizationCodeRequest() { // } // // public static AuthorizationCodeRequest createNewRequest(final String appKey, final String redirectURI) { // return new AuthorizationCodeRequest(appKey, redirectURI); // } // // private AuthorizationCodeRequest(final String appKey, final String redirectURI) { // this.appKey = appKey; // this.redirectURI = redirectURI; // } // // public int getRequestCode() { // return LoginActivity.AUTHORIZATION_CODE_REQUEST; // } // // public String getAppKey() { // return appKey; // } // // public String getRedirectURI() { // return redirectURI; // } // }
import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.pm.Signature; import android.net.Uri; import com.kakao.authorization.authcode.AuthorizationCodeRequest;
public static final String ERROR_UNKNOWN_ERROR = "UnknownError"; public static final String ERROR_PROTOCOL_ERROR = "ProtocolError"; public static final String ERROR_APPLICATION_ERROR = "ApplicationError"; public static final String ERROR_NETWORK_ERROR = "NetworkError"; // kakolink public static final String KAKAO_TALK_LINK_URL = "kakaolink://send"; private static final String RELEASE_TAlk_SIGNATURE = "308201db30820144a00302010202044c707197300d06092a864886f70d010105050030" + "31310b3009060355040613026b6f310e300c060355040a13056b616b616f31123010060355040b13096b616b616f7465616d3020170d" + "3130303832323030333834375a180f32313130303732393030333834375a3031310b3009060355040613026b6f310e300c060355040a" + "13056b616b616f31123010060355040b13096b616b616f7465616d30819f300d06092a864886f70d010101050003818d003081890281" + "8100aef387bc86e022a87e66b8c42153284f18e0c468cf9c87a241b989729dfdad3dd9e1847546d01a2819ba77f3974a47b473c926ac" + "ae173fd90c7e635000721feeef6705da7ae949a35b82900a0f67d9464d73ed8a98c37f4ac70729494a17469bc40d4ee06d043b09147e" + "badc55fa1020968d7036c5fb9b8c148cba1d8e9d9fc10203010001300d06092a864886f70d0101050500038181005569be704c68cff6" + "221c1e04dd8a131110f9f5cd2138042286337fd6014a1b1d2d3eeb266ae1630afe56bf63c07dd0b5c8fad46dcb9f802f9a7802fb89eb" + "3b4777b9665bb1ed9feaf1dc7cac4f91abedfc81187ff6d2f471dbd12335d2c0ef0e2ee719df6e763f814b9ac91f8be37fd11d406867" + "00d66be6de22a1836f060f01"; private static final String DEBUG_TAlk_SIGNATURE = "308201e53082014ea00302010202044f4ae542300d06092a864886f70d01010505003037" + "310b30090603550406130255533110300e060355040a1307416e64726f6964311630140603550403130d416e64726f69642044656275" + "67301e170d3132303232373032303635385a170d3432303231393032303635385a3037310b30090603550406130255533110300e0603" + "55040a1307416e64726f6964311630140603550403130d416e64726f696420446562756730819f300d06092a864886f70d0101010500" + "03818d0030818902818100c0b41c25ef21a39a13ce89c82dc3a14bf9ef0c3094aa2ac1bf755c9699535e79119e8b980c0ecdcc51f259" + "eb0d8b2077d41de8fcfdeaac3f386c05e2a684ecb5504b660ad7d5a01cce35899f96bcbd099c9dcb274c6eb41fef861616a12fb45bc5" + "7a19683a8a97ab1a33d9c70128878b67dd1b3a388ad5121d1d66ff04c065ff0203010001300d06092a864886f70d0101050500038181" + "000418a7dacb6d13eb61c8270fe1fdd006eb66d0ff9f58f475defd8dc1fb11c41e34ce924531d1fd8ad26d9479d64f54851bf57b8dfe" + "3a5d6f0a01dcad5b8c36ac4ac48caeff37888c36483c26b09aaa9689dbb896938d5afe40135bf7d9f12643046301867165d28be0baa3" + "513a5084e182f7f9c044d5baa58bdce55fa1845241";
// Path: sdk/src/com/kakao/authorization/authcode/AuthorizationCodeRequest.java // public class AuthorizationCodeRequest implements Serializable { // private static final long serialVersionUID = 7078182213563726736L; // private String appKey; // private String redirectURI; // // public AuthorizationCodeRequest() { // } // // public static AuthorizationCodeRequest createNewRequest(final String appKey, final String redirectURI) { // return new AuthorizationCodeRequest(appKey, redirectURI); // } // // private AuthorizationCodeRequest(final String appKey, final String redirectURI) { // this.appKey = appKey; // this.redirectURI = redirectURI; // } // // public int getRequestCode() { // return LoginActivity.AUTHORIZATION_CODE_REQUEST; // } // // public String getAppKey() { // return appKey; // } // // public String getRedirectURI() { // return redirectURI; // } // } // Path: sdk/src/com/kakao/helper/TalkProtocol.java import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.pm.Signature; import android.net.Uri; import com.kakao.authorization.authcode.AuthorizationCodeRequest; public static final String ERROR_UNKNOWN_ERROR = "UnknownError"; public static final String ERROR_PROTOCOL_ERROR = "ProtocolError"; public static final String ERROR_APPLICATION_ERROR = "ApplicationError"; public static final String ERROR_NETWORK_ERROR = "NetworkError"; // kakolink public static final String KAKAO_TALK_LINK_URL = "kakaolink://send"; private static final String RELEASE_TAlk_SIGNATURE = "308201db30820144a00302010202044c707197300d06092a864886f70d010105050030" + "31310b3009060355040613026b6f310e300c060355040a13056b616b616f31123010060355040b13096b616b616f7465616d3020170d" + "3130303832323030333834375a180f32313130303732393030333834375a3031310b3009060355040613026b6f310e300c060355040a" + "13056b616b616f31123010060355040b13096b616b616f7465616d30819f300d06092a864886f70d010101050003818d003081890281" + "8100aef387bc86e022a87e66b8c42153284f18e0c468cf9c87a241b989729dfdad3dd9e1847546d01a2819ba77f3974a47b473c926ac" + "ae173fd90c7e635000721feeef6705da7ae949a35b82900a0f67d9464d73ed8a98c37f4ac70729494a17469bc40d4ee06d043b09147e" + "badc55fa1020968d7036c5fb9b8c148cba1d8e9d9fc10203010001300d06092a864886f70d0101050500038181005569be704c68cff6" + "221c1e04dd8a131110f9f5cd2138042286337fd6014a1b1d2d3eeb266ae1630afe56bf63c07dd0b5c8fad46dcb9f802f9a7802fb89eb" + "3b4777b9665bb1ed9feaf1dc7cac4f91abedfc81187ff6d2f471dbd12335d2c0ef0e2ee719df6e763f814b9ac91f8be37fd11d406867" + "00d66be6de22a1836f060f01"; private static final String DEBUG_TAlk_SIGNATURE = "308201e53082014ea00302010202044f4ae542300d06092a864886f70d01010505003037" + "310b30090603550406130255533110300e060355040a1307416e64726f6964311630140603550403130d416e64726f69642044656275" + "67301e170d3132303232373032303635385a170d3432303231393032303635385a3037310b30090603550406130255533110300e0603" + "55040a1307416e64726f6964311630140603550403130d416e64726f696420446562756730819f300d06092a864886f70d0101010500" + "03818d0030818902818100c0b41c25ef21a39a13ce89c82dc3a14bf9ef0c3094aa2ac1bf755c9699535e79119e8b980c0ecdcc51f259" + "eb0d8b2077d41de8fcfdeaac3f386c05e2a684ecb5504b660ad7d5a01cce35899f96bcbd099c9dcb274c6eb41fef861616a12fb45bc5" + "7a19683a8a97ab1a33d9c70128878b67dd1b3a388ad5121d1d66ff04c065ff0203010001300d06092a864886f70d0101050500038181" + "000418a7dacb6d13eb61c8270fe1fdd006eb66d0ff9f58f475defd8dc1fb11c41e34ce924531d1fd8ad26d9479d64f54851bf57b8dfe" + "3a5d6f0a01dcad5b8c36ac4ac48caeff37888c36483c26b09aaa9689dbb896938d5afe40135bf7d9f12643046301867165d28be0baa3" + "513a5084e182f7f9c044d5baa58bdce55fa1845241";
public static Intent createLoggedOutActivityIntent(final Context context, final AuthorizationCodeRequest request) {
kkung/kakao-android-sdk-standalone
sdk/src/com/kakao/internal/Action.java
// Path: sdk/src/com/kakao/KakaoLinkParseException.java // public class KakaoLinkParseException extends Exception { // private static final long serialVersionUID = 4539740978213889048L; // private ERROR_CODE code = ERROR_CODE.UNKNOWN; // // /** // * ์นด์นด์˜ค๋งํฌ ํ”„๋กœํ† ์ฝœ์— ๋งž์ง€ ์•Š๋Š” ๊ฒฝ์šฐ ๋˜์ง€๋Š” ์—๋Ÿฌ ์ฝ”๋“œ // */ // public enum ERROR_CODE { // /** // * ์ •์˜๋˜์ง€ ์•Š์€ ์—๋Ÿฌ // */ // UNKNOWN, // /** // * ํ•„์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ€ ๋ˆ„๋ฝ๋œ ๊ฒฝ์šฐ // */ // CORE_PARAMETER_MISSING, // /** // * ์ตœ์†Œ ์ด๋ฏธ์ง€ ์‚ฌ์ด์ฆˆ๋ณด๋‹ค ์ž‘์€ ๊ฒฝ์šฐ // */ // MINIMUM_IMAGE_SIZE_REQUIRED, // /** // * ๊ฐ™์€ ํƒ€์ž…์˜ ๋ฉ”์‹œ์ง€๊ฐ€ ๋‘๊ฐœ ์ด์ƒ ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ // */ // DUPLICATE_OBJECTS_USED, // /** // * ์ง€์›ํ•˜์ง€ ์•Š๋Š” ์ธ์ฝ”๋”ฉ์ด ์„ ์–ธ๋œ ๊ฒฝ์šฐ // */ // UNSUPPORTED_ENCODING, // /** // * JSON ํŒŒ์‹ฑ ๋„์ค‘ ์—๋Ÿฌ // */ // JSON_PARSING_ERROR // } // // /** // * exception์„ ๋˜์ง€๋Š” ์ด์œ  code๊ฐ’ // * @return {@link KakaoLinkParseException.ERROR_CODE} ์ค‘ ํ•˜๋‚˜ // */ // public ERROR_CODE getCode() { // return code; // } // // /** // * exception์„ ๋˜์ง€๋Š” ์ด์œ  code ๊ฐ’๊ณผ ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ // * @return error_cod ":" error_message // */ // public String getMessage(){ // return code != null ? code + ":" + super.getMessage() : super.getMessage(); // } // // KakaoLinkParseException(final String message) { // super(message); // } // // public KakaoLinkParseException(final ERROR_CODE code, final String e) { // super(e); // this.code = code; // } // // KakaoLinkParseException(final ERROR_CODE code, final Exception e) { // super(e); // this.code = code; // } // // }
import android.text.TextUtils; import com.kakao.KakaoLinkParseException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;
/** * Copyright 2014 Kakao Corp. * * Redistribution and modification in source or binary forms are not permitted without specific prior written permission.ย  * * 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.kakao.internal; /** * link, button, image type click์‹œ ์ทจํ•  action */ public class Action { public enum ACTION_TYPE { WEB("web"), APP("app"); private final String value; ACTION_TYPE(String value) { this.value = value; } } private ACTION_TYPE type; private ActionInfo[] actionInfos; private String url;
// Path: sdk/src/com/kakao/KakaoLinkParseException.java // public class KakaoLinkParseException extends Exception { // private static final long serialVersionUID = 4539740978213889048L; // private ERROR_CODE code = ERROR_CODE.UNKNOWN; // // /** // * ์นด์นด์˜ค๋งํฌ ํ”„๋กœํ† ์ฝœ์— ๋งž์ง€ ์•Š๋Š” ๊ฒฝ์šฐ ๋˜์ง€๋Š” ์—๋Ÿฌ ์ฝ”๋“œ // */ // public enum ERROR_CODE { // /** // * ์ •์˜๋˜์ง€ ์•Š์€ ์—๋Ÿฌ // */ // UNKNOWN, // /** // * ํ•„์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ€ ๋ˆ„๋ฝ๋œ ๊ฒฝ์šฐ // */ // CORE_PARAMETER_MISSING, // /** // * ์ตœ์†Œ ์ด๋ฏธ์ง€ ์‚ฌ์ด์ฆˆ๋ณด๋‹ค ์ž‘์€ ๊ฒฝ์šฐ // */ // MINIMUM_IMAGE_SIZE_REQUIRED, // /** // * ๊ฐ™์€ ํƒ€์ž…์˜ ๋ฉ”์‹œ์ง€๊ฐ€ ๋‘๊ฐœ ์ด์ƒ ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ // */ // DUPLICATE_OBJECTS_USED, // /** // * ์ง€์›ํ•˜์ง€ ์•Š๋Š” ์ธ์ฝ”๋”ฉ์ด ์„ ์–ธ๋œ ๊ฒฝ์šฐ // */ // UNSUPPORTED_ENCODING, // /** // * JSON ํŒŒ์‹ฑ ๋„์ค‘ ์—๋Ÿฌ // */ // JSON_PARSING_ERROR // } // // /** // * exception์„ ๋˜์ง€๋Š” ์ด์œ  code๊ฐ’ // * @return {@link KakaoLinkParseException.ERROR_CODE} ์ค‘ ํ•˜๋‚˜ // */ // public ERROR_CODE getCode() { // return code; // } // // /** // * exception์„ ๋˜์ง€๋Š” ์ด์œ  code ๊ฐ’๊ณผ ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ // * @return error_cod ":" error_message // */ // public String getMessage(){ // return code != null ? code + ":" + super.getMessage() : super.getMessage(); // } // // KakaoLinkParseException(final String message) { // super(message); // } // // public KakaoLinkParseException(final ERROR_CODE code, final String e) { // super(e); // this.code = code; // } // // KakaoLinkParseException(final ERROR_CODE code, final Exception e) { // super(e); // this.code = code; // } // // } // Path: sdk/src/com/kakao/internal/Action.java import android.text.TextUtils; import com.kakao.KakaoLinkParseException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * Copyright 2014 Kakao Corp. * * Redistribution and modification in source or binary forms are not permitted without specific prior written permission.ย  * * 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.kakao.internal; /** * link, button, image type click์‹œ ์ทจํ•  action */ public class Action { public enum ACTION_TYPE { WEB("web"), APP("app"); private final String value; ACTION_TYPE(String value) { this.value = value; } } private ACTION_TYPE type; private ActionInfo[] actionInfos; private String url;
private Action(final ACTION_TYPE type, final String url, final ActionInfo[] actionInfos) throws KakaoLinkParseException {
kkung/kakao-android-sdk-standalone
sdk/src/com/kakao/KakaoStoryProfile.java
// Path: sdk/src/com/kakao/helper/Logger.java // public class Logger { // public static enum LogLevel { // Verbose, Debug, Info, Warn, Error, Release // } // // // private static final String TAG = "kakao-android-sdk"; // private volatile static Logger instance; // // private LogLevel logLevel; // // private Logger() { // super(); // this.logLevel = LogLevel.Debug; // } // // public static Logger getInstance() { // if (instance == null) { // synchronized (Logger.class) { // if (instance == null) instance = new Logger(); // } // } // // return instance; // } // // public void setLogLevel(LogLevel logLevel) { // this.logLevel = logLevel; // } // // public boolean isLoggable(LogLevel logLevel){ // return this.logLevel.compareTo(logLevel) <= 0; // } // // public void v(String msg) { // v(TAG, msg); // } // // public void d(String msg) { // d(TAG, msg); // } // // public void i(String msg) { // i(TAG, msg); // } // // public void w(String msg) { // w(TAG, msg); // } // // public void e(String msg) { // e(TAG, msg); // } // // void v(String tag, String msg) { // switch (logLevel) { // case Verbose: // Log.v(tag, msg); // break; // } // } // // public void d(String tag, String msg) { // switch (logLevel) { // case Verbose: // case Debug: // Log.d(tag, msg); // break; // } // } // // void i(String tag, String msg) { // switch (logLevel) { // case Verbose: // case Debug: // case Info: // Log.i(tag, msg); // break; // } // } // // public void w(String tag, String msg) { // switch (logLevel) { // case Verbose: // case Debug: // case Info: // case Warn: // Log.w(tag, msg); // break; // } // } // // void e(String tag, String msg) { // switch (logLevel) { // case Verbose: // case Debug: // case Info: // case Warn: // case Error: // Log.e(tag, msg); // break; // } // } // // public void v(Throwable tr) { // v(TAG, tr); // } // // public void d(Throwable tr) { // d(TAG, tr); // } // // public void i(Throwable tr) { // i(TAG, tr); // } // // public void w(Throwable tr) { // w(TAG, tr); // } // // public void e(Throwable tr) { // e(TAG, tr); // } // // void v(String tag, Throwable tr) { // switch (logLevel) { // case Verbose: // Log.v(tag, tr.getLocalizedMessage(), tr); // break; // } // } // // void d(String tag, Throwable tr) { // switch (logLevel) { // case Verbose: // case Debug: // Log.d(tag, tr.getLocalizedMessage(), tr); // break; // } // } // // public void i(String tag, Throwable tr) { // switch (logLevel) { // case Verbose: // case Debug: // case Info: // Log.i(tag, tr.getLocalizedMessage(), tr); // break; // } // } // // public void w(String tag, Throwable tr) { // switch (logLevel) { // case Verbose: // case Debug: // case Info: // case Warn: // Log.w(tag, tr.getLocalizedMessage(), tr); // break; // } // } // // void e(String tag, Throwable tr) { // switch (logLevel) { // case Verbose: // case Debug: // case Info: // case Warn: // case Error: // Log.e(tag, tr.getLocalizedMessage(), tr); // break; // } // } // }
import android.graphics.Bitmap; import com.kakao.helper.Logger; import java.text.SimpleDateFormat; import java.util.Calendar;
} /** * ์นด์นด์˜ค์Šคํ† ๋ฆฌ ์ƒ์ผ์„ Calendar ํƒ€์ž… * @return ์นด์นด์˜ค์Šคํ† ๋ฆฌ ์ƒ์ผ์„ Calendar ํ˜•์‹์œผ๋กœ ๋ฐ˜ํ™˜ */ public Calendar getBirthdayCalendar() { return birthdayCalendar; } /** * ์นด์นด์˜ค์Šคํ† ๋ฆฌ ์ƒ์ผ ํƒ€์ž…. ์–‘๋ ฅ ๋˜๋Š” ์Œ๋ ฅ * @return ์นด์นด์˜ค์Šคํ† ๋ฆฌ ์ƒ์ผ ํƒ€์ž…. ์–‘๋ ฅ ๋˜๋Š” ์Œ๋ ฅ */ public BirthdayType getBirthdayType() { return birthdayType; } /** * jackson์—์„œ ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค. * @param birthday MMdd ํ˜•ํƒœ์˜ ์ƒ์ผ string ๊ฐ’ */ public void setBirthday(final String birthday) { if(birthday == null) return; final SimpleDateFormat form = new SimpleDateFormat("MMdd"); birthdayCalendar = Calendar.getInstance(); try { birthdayCalendar.setTime(form.parse(birthday)); } catch (java.text.ParseException e) {
// Path: sdk/src/com/kakao/helper/Logger.java // public class Logger { // public static enum LogLevel { // Verbose, Debug, Info, Warn, Error, Release // } // // // private static final String TAG = "kakao-android-sdk"; // private volatile static Logger instance; // // private LogLevel logLevel; // // private Logger() { // super(); // this.logLevel = LogLevel.Debug; // } // // public static Logger getInstance() { // if (instance == null) { // synchronized (Logger.class) { // if (instance == null) instance = new Logger(); // } // } // // return instance; // } // // public void setLogLevel(LogLevel logLevel) { // this.logLevel = logLevel; // } // // public boolean isLoggable(LogLevel logLevel){ // return this.logLevel.compareTo(logLevel) <= 0; // } // // public void v(String msg) { // v(TAG, msg); // } // // public void d(String msg) { // d(TAG, msg); // } // // public void i(String msg) { // i(TAG, msg); // } // // public void w(String msg) { // w(TAG, msg); // } // // public void e(String msg) { // e(TAG, msg); // } // // void v(String tag, String msg) { // switch (logLevel) { // case Verbose: // Log.v(tag, msg); // break; // } // } // // public void d(String tag, String msg) { // switch (logLevel) { // case Verbose: // case Debug: // Log.d(tag, msg); // break; // } // } // // void i(String tag, String msg) { // switch (logLevel) { // case Verbose: // case Debug: // case Info: // Log.i(tag, msg); // break; // } // } // // public void w(String tag, String msg) { // switch (logLevel) { // case Verbose: // case Debug: // case Info: // case Warn: // Log.w(tag, msg); // break; // } // } // // void e(String tag, String msg) { // switch (logLevel) { // case Verbose: // case Debug: // case Info: // case Warn: // case Error: // Log.e(tag, msg); // break; // } // } // // public void v(Throwable tr) { // v(TAG, tr); // } // // public void d(Throwable tr) { // d(TAG, tr); // } // // public void i(Throwable tr) { // i(TAG, tr); // } // // public void w(Throwable tr) { // w(TAG, tr); // } // // public void e(Throwable tr) { // e(TAG, tr); // } // // void v(String tag, Throwable tr) { // switch (logLevel) { // case Verbose: // Log.v(tag, tr.getLocalizedMessage(), tr); // break; // } // } // // void d(String tag, Throwable tr) { // switch (logLevel) { // case Verbose: // case Debug: // Log.d(tag, tr.getLocalizedMessage(), tr); // break; // } // } // // public void i(String tag, Throwable tr) { // switch (logLevel) { // case Verbose: // case Debug: // case Info: // Log.i(tag, tr.getLocalizedMessage(), tr); // break; // } // } // // public void w(String tag, Throwable tr) { // switch (logLevel) { // case Verbose: // case Debug: // case Info: // case Warn: // Log.w(tag, tr.getLocalizedMessage(), tr); // break; // } // } // // void e(String tag, Throwable tr) { // switch (logLevel) { // case Verbose: // case Debug: // case Info: // case Warn: // case Error: // Log.e(tag, tr.getLocalizedMessage(), tr); // break; // } // } // } // Path: sdk/src/com/kakao/KakaoStoryProfile.java import android.graphics.Bitmap; import com.kakao.helper.Logger; import java.text.SimpleDateFormat; import java.util.Calendar; } /** * ์นด์นด์˜ค์Šคํ† ๋ฆฌ ์ƒ์ผ์„ Calendar ํƒ€์ž… * @return ์นด์นด์˜ค์Šคํ† ๋ฆฌ ์ƒ์ผ์„ Calendar ํ˜•์‹์œผ๋กœ ๋ฐ˜ํ™˜ */ public Calendar getBirthdayCalendar() { return birthdayCalendar; } /** * ์นด์นด์˜ค์Šคํ† ๋ฆฌ ์ƒ์ผ ํƒ€์ž…. ์–‘๋ ฅ ๋˜๋Š” ์Œ๋ ฅ * @return ์นด์นด์˜ค์Šคํ† ๋ฆฌ ์ƒ์ผ ํƒ€์ž…. ์–‘๋ ฅ ๋˜๋Š” ์Œ๋ ฅ */ public BirthdayType getBirthdayType() { return birthdayType; } /** * jackson์—์„œ ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ค ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค. * @param birthday MMdd ํ˜•ํƒœ์˜ ์ƒ์ผ string ๊ฐ’ */ public void setBirthday(final String birthday) { if(birthday == null) return; final SimpleDateFormat form = new SimpleDateFormat("MMdd"); birthdayCalendar = Calendar.getInstance(); try { birthdayCalendar.setTime(form.parse(birthday)); } catch (java.text.ParseException e) {
Logger.getInstance().d(e);
kkung/kakao-android-sdk-standalone
sdk/src/com/kakao/AppActionBuilder.java
// Path: sdk/src/com/kakao/internal/Action.java // public class Action { // public enum ACTION_TYPE { // WEB("web"), // APP("app"); // private final String value; // // ACTION_TYPE(String value) { // this.value = value; // } // } // // private ACTION_TYPE type; // private ActionInfo[] actionInfos; // private String url; // // // private Action(final ACTION_TYPE type, final String url, final ActionInfo[] actionInfos) throws KakaoLinkParseException { // if (type == null) { // throw new KakaoLinkParseException(KakaoLinkParseException.ERROR_CODE.CORE_PARAMETER_MISSING, "action needs type."); // } // this.type = type; // // if ((type == ACTION_TYPE.WEB) && !TextUtils.isEmpty(url)) { // this.url = url; // } // // if (type == ACTION_TYPE.APP && !(actionInfos == null || actionInfos.length == 0)) { // this.actionInfos = actionInfos; // } // } // // public static Action newActionApp(final ActionInfo[] actionInfos) throws KakaoLinkParseException { // return new Action(ACTION_TYPE.APP, null, actionInfos); // } // // public static Action newActionWeb(final String url) throws KakaoLinkParseException { // return new Action(ACTION_TYPE.WEB, url, null); // } // // public JSONObject createJSONObject() throws JSONException { // JSONObject json = new JSONObject(); // json.put(KakaoTalkLinkProtocol.ACTION_TYPE, type.value); // if (url != null) { // json.put(KakaoTalkLinkProtocol.ACTION_URL, url); // } // if (actionInfos != null) { // JSONArray jsonObjs = new JSONArray(); // for (ActionInfo obj : actionInfos) { // jsonObjs.put(obj.createJSONObject()); // } // json.put(KakaoTalkLinkProtocol.ACTION_ACTIONINFO, jsonObjs); // } // return json; // } // } // // Path: sdk/src/com/kakao/internal/ActionInfo.java // public class ActionInfo { // enum ACTION_INFO_OS { // ANDROID("android"), // IOS("ios"); // // private final String value; // // ACTION_INFO_OS(String value) { // this.value = value; // } // } // // private final ACTION_INFO_OS os; // private final DEVICE_TYPE deviceType; // private final String executeParam; // // private ActionInfo(final ACTION_INFO_OS os, final String executeParam, final DEVICE_TYPE deviceType) { // this.os = os; // this.executeParam = executeParam; // this.deviceType = deviceType; // } // // public static ActionInfo createAndroidActionInfo(final String executeParam, final DEVICE_TYPE deviceType){ // return new ActionInfo(ACTION_INFO_OS.ANDROID, executeParam, deviceType); // } // // public static ActionInfo createIOSActionInfo(final String executeParam, final DEVICE_TYPE deviceType){ // return new ActionInfo(ACTION_INFO_OS.IOS, executeParam, deviceType); // } // // JSONObject createJSONObject() throws JSONException { // JSONObject json = new JSONObject(); // json.put(KakaoTalkLinkProtocol.ACTIONINFO_OS, os.value); // // if (!TextUtils.isEmpty(executeParam)) { // json.put(KakaoTalkLinkProtocol.ACTIONINFO_EXEC_PARAM, executeParam); // } // // if (deviceType != null) { // json.put(KakaoTalkLinkProtocol.ACTIONINFO_DEVICETYPE, deviceType.getValue()); // } // return json; // } // }
import java.util.Set; import com.kakao.internal.Action; import com.kakao.internal.ActionInfo; import java.util.HashSet;
/** * Copyright 2014 Minyoung Jeong <kkungkkung@gmail.com> * Copyright 2014 Kakao Corp. * * Redistribution and modification in source or binary forms are not permitted without specific prior written permission.ย  * * 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.kakao; /** * ์นด์นด์˜ค๋งํฌ ํ†ก๋ฉ”์‹œ์ง€ ์ค‘ ์•ฑ์œผ๋กœ ์—ฐ๊ฒฐํ•  url์„ ์„ค์ •ํ•˜๋Š” Builder * OS๋ณ„, ๋””๋ฐ”์ด์Šค๋ณ„ ์„ค์ •์ด ๊ฐ€๋Šฅํ•˜๋‹ค. * @author MJ */ public class AppActionBuilder { /** * ์•ฑ์œผ๋กœ ์—ฐ๊ฒฐํ•  url์„ ๋””๋ฐ”์ด์Šค๋ณ„๋กœ ๊ตฌ๋ถ„ํ•  ๋•Œ ์‚ฌ์šฉ๋œ๋‹ค. */ public enum DEVICE_TYPE { /** * ํ•ธ๋“œํฐ */ PHONE("phone"), /** * ํŒจ๋“œ */ PAD("pad"); private final String value; DEVICE_TYPE(String value) { this.value = value; } /** * ๋””๋ฐ”์ด์Šค ์ข…๋ฅ˜์˜ string ๊ฐ’ * ๋ฉ”์‹œ์ง€๋ฅผ json์œผ๋กœ ๋งŒ๋“ค๋•Œ ์‚ฌ์šฉ๋œ๋‹ค. * @return ๋””๋ฐ”์ด์Šค ์ข…๋ฅ˜์˜ string ๊ฐ’. ๋ฉ”์‹œ์ง€๋ฅผ json์œผ๋กœ ๋งŒ๋“ค๋•Œ ์‚ฌ์šฉ๋œ๋‹ค. */ public String getValue() { return value; } }
// Path: sdk/src/com/kakao/internal/Action.java // public class Action { // public enum ACTION_TYPE { // WEB("web"), // APP("app"); // private final String value; // // ACTION_TYPE(String value) { // this.value = value; // } // } // // private ACTION_TYPE type; // private ActionInfo[] actionInfos; // private String url; // // // private Action(final ACTION_TYPE type, final String url, final ActionInfo[] actionInfos) throws KakaoLinkParseException { // if (type == null) { // throw new KakaoLinkParseException(KakaoLinkParseException.ERROR_CODE.CORE_PARAMETER_MISSING, "action needs type."); // } // this.type = type; // // if ((type == ACTION_TYPE.WEB) && !TextUtils.isEmpty(url)) { // this.url = url; // } // // if (type == ACTION_TYPE.APP && !(actionInfos == null || actionInfos.length == 0)) { // this.actionInfos = actionInfos; // } // } // // public static Action newActionApp(final ActionInfo[] actionInfos) throws KakaoLinkParseException { // return new Action(ACTION_TYPE.APP, null, actionInfos); // } // // public static Action newActionWeb(final String url) throws KakaoLinkParseException { // return new Action(ACTION_TYPE.WEB, url, null); // } // // public JSONObject createJSONObject() throws JSONException { // JSONObject json = new JSONObject(); // json.put(KakaoTalkLinkProtocol.ACTION_TYPE, type.value); // if (url != null) { // json.put(KakaoTalkLinkProtocol.ACTION_URL, url); // } // if (actionInfos != null) { // JSONArray jsonObjs = new JSONArray(); // for (ActionInfo obj : actionInfos) { // jsonObjs.put(obj.createJSONObject()); // } // json.put(KakaoTalkLinkProtocol.ACTION_ACTIONINFO, jsonObjs); // } // return json; // } // } // // Path: sdk/src/com/kakao/internal/ActionInfo.java // public class ActionInfo { // enum ACTION_INFO_OS { // ANDROID("android"), // IOS("ios"); // // private final String value; // // ACTION_INFO_OS(String value) { // this.value = value; // } // } // // private final ACTION_INFO_OS os; // private final DEVICE_TYPE deviceType; // private final String executeParam; // // private ActionInfo(final ACTION_INFO_OS os, final String executeParam, final DEVICE_TYPE deviceType) { // this.os = os; // this.executeParam = executeParam; // this.deviceType = deviceType; // } // // public static ActionInfo createAndroidActionInfo(final String executeParam, final DEVICE_TYPE deviceType){ // return new ActionInfo(ACTION_INFO_OS.ANDROID, executeParam, deviceType); // } // // public static ActionInfo createIOSActionInfo(final String executeParam, final DEVICE_TYPE deviceType){ // return new ActionInfo(ACTION_INFO_OS.IOS, executeParam, deviceType); // } // // JSONObject createJSONObject() throws JSONException { // JSONObject json = new JSONObject(); // json.put(KakaoTalkLinkProtocol.ACTIONINFO_OS, os.value); // // if (!TextUtils.isEmpty(executeParam)) { // json.put(KakaoTalkLinkProtocol.ACTIONINFO_EXEC_PARAM, executeParam); // } // // if (deviceType != null) { // json.put(KakaoTalkLinkProtocol.ACTIONINFO_DEVICETYPE, deviceType.getValue()); // } // return json; // } // } // Path: sdk/src/com/kakao/AppActionBuilder.java import java.util.Set; import com.kakao.internal.Action; import com.kakao.internal.ActionInfo; import java.util.HashSet; /** * Copyright 2014 Minyoung Jeong <kkungkkung@gmail.com> * Copyright 2014 Kakao Corp. * * Redistribution and modification in source or binary forms are not permitted without specific prior written permission.ย  * * 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.kakao; /** * ์นด์นด์˜ค๋งํฌ ํ†ก๋ฉ”์‹œ์ง€ ์ค‘ ์•ฑ์œผ๋กœ ์—ฐ๊ฒฐํ•  url์„ ์„ค์ •ํ•˜๋Š” Builder * OS๋ณ„, ๋””๋ฐ”์ด์Šค๋ณ„ ์„ค์ •์ด ๊ฐ€๋Šฅํ•˜๋‹ค. * @author MJ */ public class AppActionBuilder { /** * ์•ฑ์œผ๋กœ ์—ฐ๊ฒฐํ•  url์„ ๋””๋ฐ”์ด์Šค๋ณ„๋กœ ๊ตฌ๋ถ„ํ•  ๋•Œ ์‚ฌ์šฉ๋œ๋‹ค. */ public enum DEVICE_TYPE { /** * ํ•ธ๋“œํฐ */ PHONE("phone"), /** * ํŒจ๋“œ */ PAD("pad"); private final String value; DEVICE_TYPE(String value) { this.value = value; } /** * ๋””๋ฐ”์ด์Šค ์ข…๋ฅ˜์˜ string ๊ฐ’ * ๋ฉ”์‹œ์ง€๋ฅผ json์œผ๋กœ ๋งŒ๋“ค๋•Œ ์‚ฌ์šฉ๋œ๋‹ค. * @return ๋””๋ฐ”์ด์Šค ์ข…๋ฅ˜์˜ string ๊ฐ’. ๋ฉ”์‹œ์ง€๋ฅผ json์œผ๋กœ ๋งŒ๋“ค๋•Œ ์‚ฌ์šฉ๋œ๋‹ค. */ public String getValue() { return value; } }
private final Set<ActionInfo> actionInfos;