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
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/api/device/DeviceCompleteRequestHandlerSpiImpl.java
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response ok(String entity) // { // return builderForTextPlain(Status.OK, entity).build(); // }
import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import static com.authlete.jaxrs.server.util.ResponseUtil.ok; import java.util.Date; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import com.authlete.common.dto.DeviceCompleteRequest.Result; import com.authlete.common.types.User; import com.authlete.jaxrs.spi.DeviceCompleteRequestHandlerSpiAdapter;
} // Return the first element of the requested ACRs. Again, // this implementation is not suitable for commercial use. return acr; } @Override public Object getUserClaim(String claimName) { return mUser.getClaim(claimName, null); } @Override public Response onSuccess() { // The user has authorized or denied the client. // Return a response of "200 OK". return ok("OK. The user authorization process has been done."); } @Override public Response onInvalidRequest() { // The API call to Authlete was invalid. There should be some bugs in the // implementation of this authorization sever. // Return a response of "500 Internal Server Error".
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response ok(String entity) // { // return builderForTextPlain(Status.OK, entity).build(); // } // Path: src/main/java/com/authlete/jaxrs/server/api/device/DeviceCompleteRequestHandlerSpiImpl.java import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import static com.authlete.jaxrs.server.util.ResponseUtil.ok; import java.util.Date; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import com.authlete.common.dto.DeviceCompleteRequest.Result; import com.authlete.common.types.User; import com.authlete.jaxrs.spi.DeviceCompleteRequestHandlerSpiAdapter; } // Return the first element of the requested ACRs. Again, // this implementation is not suitable for commercial use. return acr; } @Override public Object getUserClaim(String claimName) { return mUser.getClaim(claimName, null); } @Override public Response onSuccess() { // The user has authorized or denied the client. // Return a response of "200 OK". return ok("OK. The user authorization process has been done."); } @Override public Response onInvalidRequest() { // The API call to Authlete was invalid. There should be some bugs in the // implementation of this authorization sever. // Return a response of "500 Internal Server Error".
return internalServerError("Server Error. Please re-initiate the flow again.");
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/api/device/DeviceCompleteRequestHandlerSpiImpl.java
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response ok(String entity) // { // return builderForTextPlain(Status.OK, entity).build(); // }
import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import static com.authlete.jaxrs.server.util.ResponseUtil.ok; import java.util.Date; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import com.authlete.common.dto.DeviceCompleteRequest.Result; import com.authlete.common.types.User; import com.authlete.jaxrs.spi.DeviceCompleteRequestHandlerSpiAdapter;
public Object getUserClaim(String claimName) { return mUser.getClaim(claimName, null); } @Override public Response onSuccess() { // The user has authorized or denied the client. // Return a response of "200 OK". return ok("OK. The user authorization process has been done."); } @Override public Response onInvalidRequest() { // The API call to Authlete was invalid. There should be some bugs in the // implementation of this authorization sever. // Return a response of "500 Internal Server Error". return internalServerError("Server Error. Please re-initiate the flow again."); } @Override public Response onUserCodeExpired() { // The user code has already expired. // Return a response of "400 Bad Request".
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response ok(String entity) // { // return builderForTextPlain(Status.OK, entity).build(); // } // Path: src/main/java/com/authlete/jaxrs/server/api/device/DeviceCompleteRequestHandlerSpiImpl.java import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import static com.authlete.jaxrs.server.util.ResponseUtil.ok; import java.util.Date; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import com.authlete.common.dto.DeviceCompleteRequest.Result; import com.authlete.common.types.User; import com.authlete.jaxrs.spi.DeviceCompleteRequestHandlerSpiAdapter; public Object getUserClaim(String claimName) { return mUser.getClaim(claimName, null); } @Override public Response onSuccess() { // The user has authorized or denied the client. // Return a response of "200 OK". return ok("OK. The user authorization process has been done."); } @Override public Response onInvalidRequest() { // The API call to Authlete was invalid. There should be some bugs in the // implementation of this authorization sever. // Return a response of "500 Internal Server Error". return internalServerError("Server Error. Please re-initiate the flow again."); } @Override public Response onUserCodeExpired() { // The user code has already expired. // Return a response of "400 Bad Request".
return badRequest("The user code has expired. Please re-initiate the flow again.");
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/federation/ClientConfig.java
// Path: src/main/java/com/authlete/jaxrs/server/federation/ConfigValidationHelper.java // public static void ensureNotEmpty(String key, Object value) throws IllegalStateException // { // if (value == null) // { // throw lack(key); // } // } // // Path: src/main/java/com/authlete/jaxrs/server/federation/ConfigValidationHelper.java // public static void ensureUri(String key, String value) throws IllegalStateException // { // try // { // new URI(value); // } // catch (URISyntaxException e) // { // throw illegalState("The value of ''{0}'' in the ID federation configuration is malformed: {1}", key, value); // } // }
import static com.authlete.jaxrs.server.federation.ConfigValidationHelper.ensureNotEmpty; import static com.authlete.jaxrs.server.federation.ConfigValidationHelper.ensureUri; import java.io.Serializable;
public String getRedirectUri() { return redirectUri; } public ClientConfig setRedirectUri(String redirectUri) { this.redirectUri = redirectUri; return this; } public String getIdTokenSignedResponseAlg() { return idTokenSignedResponseAlg; } public ClientConfig setIdTokenSignedResponseAlg(String idTokenSignedResponseAlg) { this.idTokenSignedResponseAlg = idTokenSignedResponseAlg; return this; } public void validate() throws IllegalStateException {
// Path: src/main/java/com/authlete/jaxrs/server/federation/ConfigValidationHelper.java // public static void ensureNotEmpty(String key, Object value) throws IllegalStateException // { // if (value == null) // { // throw lack(key); // } // } // // Path: src/main/java/com/authlete/jaxrs/server/federation/ConfigValidationHelper.java // public static void ensureUri(String key, String value) throws IllegalStateException // { // try // { // new URI(value); // } // catch (URISyntaxException e) // { // throw illegalState("The value of ''{0}'' in the ID federation configuration is malformed: {1}", key, value); // } // } // Path: src/main/java/com/authlete/jaxrs/server/federation/ClientConfig.java import static com.authlete.jaxrs.server.federation.ConfigValidationHelper.ensureNotEmpty; import static com.authlete.jaxrs.server.federation.ConfigValidationHelper.ensureUri; import java.io.Serializable; public String getRedirectUri() { return redirectUri; } public ClientConfig setRedirectUri(String redirectUri) { this.redirectUri = redirectUri; return this; } public String getIdTokenSignedResponseAlg() { return idTokenSignedResponseAlg; } public ClientConfig setIdTokenSignedResponseAlg(String idTokenSignedResponseAlg) { this.idTokenSignedResponseAlg = idTokenSignedResponseAlg; return this; } public void validate() throws IllegalStateException {
ensureNotEmpty("client/clientId", clientId);
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/federation/ClientConfig.java
// Path: src/main/java/com/authlete/jaxrs/server/federation/ConfigValidationHelper.java // public static void ensureNotEmpty(String key, Object value) throws IllegalStateException // { // if (value == null) // { // throw lack(key); // } // } // // Path: src/main/java/com/authlete/jaxrs/server/federation/ConfigValidationHelper.java // public static void ensureUri(String key, String value) throws IllegalStateException // { // try // { // new URI(value); // } // catch (URISyntaxException e) // { // throw illegalState("The value of ''{0}'' in the ID federation configuration is malformed: {1}", key, value); // } // }
import static com.authlete.jaxrs.server.federation.ConfigValidationHelper.ensureNotEmpty; import static com.authlete.jaxrs.server.federation.ConfigValidationHelper.ensureUri; import java.io.Serializable;
return redirectUri; } public ClientConfig setRedirectUri(String redirectUri) { this.redirectUri = redirectUri; return this; } public String getIdTokenSignedResponseAlg() { return idTokenSignedResponseAlg; } public ClientConfig setIdTokenSignedResponseAlg(String idTokenSignedResponseAlg) { this.idTokenSignedResponseAlg = idTokenSignedResponseAlg; return this; } public void validate() throws IllegalStateException { ensureNotEmpty("client/clientId", clientId); ensureNotEmpty("client/redirectUri", redirectUri);
// Path: src/main/java/com/authlete/jaxrs/server/federation/ConfigValidationHelper.java // public static void ensureNotEmpty(String key, Object value) throws IllegalStateException // { // if (value == null) // { // throw lack(key); // } // } // // Path: src/main/java/com/authlete/jaxrs/server/federation/ConfigValidationHelper.java // public static void ensureUri(String key, String value) throws IllegalStateException // { // try // { // new URI(value); // } // catch (URISyntaxException e) // { // throw illegalState("The value of ''{0}'' in the ID federation configuration is malformed: {1}", key, value); // } // } // Path: src/main/java/com/authlete/jaxrs/server/federation/ClientConfig.java import static com.authlete.jaxrs.server.federation.ConfigValidationHelper.ensureNotEmpty; import static com.authlete.jaxrs.server.federation.ConfigValidationHelper.ensureUri; import java.io.Serializable; return redirectUri; } public ClientConfig setRedirectUri(String redirectUri) { this.redirectUri = redirectUri; return this; } public String getIdTokenSignedResponseAlg() { return idTokenSignedResponseAlg; } public ClientConfig setIdTokenSignedResponseAlg(String idTokenSignedResponseAlg) { this.idTokenSignedResponseAlg = idTokenSignedResponseAlg; return this; } public void validate() throws IllegalStateException { ensureNotEmpty("client/clientId", clientId); ensureNotEmpty("client/redirectUri", redirectUri);
ensureUri("client/redirectUri", redirectUri);
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/ad/dto/SyncAuthenticationResponse.java
// Path: src/main/java/com/authlete/jaxrs/server/ad/type/Result.java // public enum Result // { // /** // * The result showing that an end-user authorized a client application's request. // */ // allow, // // // /** // * The result showing that an end-user denied a client application's request. // */ // deny, // // // /** // * The result showing that timeout occurred during end-user authentication and // * authorization process. // */ // timeout // ; // }
import java.io.Serializable; import com.authlete.jaxrs.server.ad.type.Result;
/* * Copyright (C) 2019 Authlete, Inc. * * 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.authlete.jaxrs.server.ad.dto; /** * A class representing a response from <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim/1.0.0#/default/post_api_authenticate_sync"> * /api/authenticate/sync API</a> of <a href="https://cibasim.authlete.com"> * Authlete CIBA authentication device simulator</a>. * * @see <a href="https://cibasim.authlete.com">Authlete CIBA authentication * device simulator</a> * * @see <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim/1.0.0#/default/post_api_authenticate_sync"> * /api/authenticate/sync API</a> * * @author Hideki Ikeda */ public class SyncAuthenticationResponse implements Serializable { private static final long serialVersionUID = 1L;
// Path: src/main/java/com/authlete/jaxrs/server/ad/type/Result.java // public enum Result // { // /** // * The result showing that an end-user authorized a client application's request. // */ // allow, // // // /** // * The result showing that an end-user denied a client application's request. // */ // deny, // // // /** // * The result showing that timeout occurred during end-user authentication and // * authorization process. // */ // timeout // ; // } // Path: src/main/java/com/authlete/jaxrs/server/ad/dto/SyncAuthenticationResponse.java import java.io.Serializable; import com.authlete.jaxrs.server.ad.type.Result; /* * Copyright (C) 2019 Authlete, Inc. * * 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.authlete.jaxrs.server.ad.dto; /** * A class representing a response from <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim/1.0.0#/default/post_api_authenticate_sync"> * /api/authenticate/sync API</a> of <a href="https://cibasim.authlete.com"> * Authlete CIBA authentication device simulator</a>. * * @see <a href="https://cibasim.authlete.com">Authlete CIBA authentication * device simulator</a> * * @see <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim/1.0.0#/default/post_api_authenticate_sync"> * /api/authenticate/sync API</a> * * @author Hideki Ikeda */ public class SyncAuthenticationResponse implements Serializable { private static final long serialVersionUID = 1L;
private Result result;
DataDog/java-dogstatsd-client
src/main/java/com/timgroup/statsd/Telemetry.java
// Path: src/main/java/com/timgroup/statsd/Message.java // public abstract class Message { // final String aspect; // final Message.Type type; // final String[] tags; // protected boolean done; // protected Integer hash; // // // borrowed from Array.hashCode implementation: // // https://github.com/openjdk/jdk11/blob/master/src/java.base/share/classes/java/util/Arrays.java#L4454-L4465 // protected final int HASH_MULTIPLIER = 31; // // public enum Type { // GAUGE("g"), // COUNT("c"), // TIME("ms"), // SET("s"), // HISTOGRAM("h"), // DISTRIBUTION("d"), // EVENT("_e"), // SERVICE_CHECK("_sc"); // // private final String type; // // Type(String type) { // this.type = type; // } // // public String toString() { // return this.type; // } // } // // protected Message(Message.Type type) { // this.aspect = ""; // this.type = type; // this.done = false; // this.tags = null; // } // // protected Message(String aspect, Message.Type type, String[] tags) { // this.aspect = aspect; // this.type = type; // this.done = false; // this.tags = tags; // } // // /** // * Write this message to the provided {@link StringBuilder}. Will // * be called from the sender threads. // * // * @param builder // * StringBuilder the text representation will be written to. // */ // abstract void writeTo(StringBuilder builder); // // /** // * Aggregate message. // * // * @param message // * Message to aggregate. // */ // public abstract void aggregate(Message message); // // // /** // * Return the message aspect. // * // * @return returns the string representing the Message aspect // */ // public final String getAspect() { // return this.aspect; // } // // /** // * Return the message type. // * // * @return returns the dogstatsd type for the Message // */ // public final Type getType() { // return this.type; // } // // /** // * Return the array of tags for the message. // * // * @return returns the string array of tags for the Message // */ // public String[] getTags() { // return this.tags; // } // // /** // * Return whether a message can be aggregated. // * Not sure if this makes sense. // * // * @return boolean on whether or not this message type may be aggregated. // */ // public boolean canAggregate() { // // return (this.type == m.type); // return false; // } // // public void setDone(boolean done) { // this.done = done; // } // // public boolean getDone() { // return this.done; // } // // /** // * Messages must implement hashCode. // */ // @Override // public int hashCode() { // // cache it // if (this.hash == null) { // this.hash = new Integer(Objects.hash(this.aspect)) * HASH_MULTIPLIER; // this.hash += Objects.hash(this.tags); // } // // return this.hash; // } // // /** // * Messages must implement hashCode. // */ // @Override // public boolean equals(Object object) { // if (object == null) { // return false; // } // if (object instanceof Message) { // final Message msg = (Message)object; // // boolean equals = (this.getAspect() == msg.getAspect()) // && (this.getType() == msg.getType()) // && (this.done == msg.getDone()) // && Arrays.equals(this.tags, (msg.getTags())); // // return equals; // } // // return false; // } // }
import com.timgroup.statsd.Message; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicInteger;
protected final String bytesDroppedMetric = "datadog.dogstatsd.client.bytes_dropped"; protected final String packetsSentMetric = "datadog.dogstatsd.client.packets_sent"; protected final String packetsDroppedMetric = "datadog.dogstatsd.client.packets_dropped"; protected final String packetsDroppedQueueMetric = "datadog.dogstatsd.client.packets_dropped_queue"; protected final String aggregatedContextsMetric = "datadog.dogstatsd.client.aggregated_context"; protected final String aggregatedContextsByTypeMetric = "datadog.dogstatsd.client.aggregated_context_by_type"; protected String tags; protected StringBuilder tagBuilder = new StringBuilder(); public StatsDProcessor processor; protected Timer timer; protected class TelemetryTask extends TimerTask { private Telemetry telemetry; TelemetryTask(final Telemetry telemetry) { super(); this.telemetry = telemetry; } public void run() { this.telemetry.flush(); } } class TelemetryMessage extends NumericMessage<Integer> { private final String tagsString; // pre-baked comma separeated tags string protected TelemetryMessage(String metric, Integer value, String tags) {
// Path: src/main/java/com/timgroup/statsd/Message.java // public abstract class Message { // final String aspect; // final Message.Type type; // final String[] tags; // protected boolean done; // protected Integer hash; // // // borrowed from Array.hashCode implementation: // // https://github.com/openjdk/jdk11/blob/master/src/java.base/share/classes/java/util/Arrays.java#L4454-L4465 // protected final int HASH_MULTIPLIER = 31; // // public enum Type { // GAUGE("g"), // COUNT("c"), // TIME("ms"), // SET("s"), // HISTOGRAM("h"), // DISTRIBUTION("d"), // EVENT("_e"), // SERVICE_CHECK("_sc"); // // private final String type; // // Type(String type) { // this.type = type; // } // // public String toString() { // return this.type; // } // } // // protected Message(Message.Type type) { // this.aspect = ""; // this.type = type; // this.done = false; // this.tags = null; // } // // protected Message(String aspect, Message.Type type, String[] tags) { // this.aspect = aspect; // this.type = type; // this.done = false; // this.tags = tags; // } // // /** // * Write this message to the provided {@link StringBuilder}. Will // * be called from the sender threads. // * // * @param builder // * StringBuilder the text representation will be written to. // */ // abstract void writeTo(StringBuilder builder); // // /** // * Aggregate message. // * // * @param message // * Message to aggregate. // */ // public abstract void aggregate(Message message); // // // /** // * Return the message aspect. // * // * @return returns the string representing the Message aspect // */ // public final String getAspect() { // return this.aspect; // } // // /** // * Return the message type. // * // * @return returns the dogstatsd type for the Message // */ // public final Type getType() { // return this.type; // } // // /** // * Return the array of tags for the message. // * // * @return returns the string array of tags for the Message // */ // public String[] getTags() { // return this.tags; // } // // /** // * Return whether a message can be aggregated. // * Not sure if this makes sense. // * // * @return boolean on whether or not this message type may be aggregated. // */ // public boolean canAggregate() { // // return (this.type == m.type); // return false; // } // // public void setDone(boolean done) { // this.done = done; // } // // public boolean getDone() { // return this.done; // } // // /** // * Messages must implement hashCode. // */ // @Override // public int hashCode() { // // cache it // if (this.hash == null) { // this.hash = new Integer(Objects.hash(this.aspect)) * HASH_MULTIPLIER; // this.hash += Objects.hash(this.tags); // } // // return this.hash; // } // // /** // * Messages must implement hashCode. // */ // @Override // public boolean equals(Object object) { // if (object == null) { // return false; // } // if (object instanceof Message) { // final Message msg = (Message)object; // // boolean equals = (this.getAspect() == msg.getAspect()) // && (this.getType() == msg.getType()) // && (this.done == msg.getDone()) // && Arrays.equals(this.tags, (msg.getTags())); // // return equals; // } // // return false; // } // } // Path: src/main/java/com/timgroup/statsd/Telemetry.java import com.timgroup.statsd.Message; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicInteger; protected final String bytesDroppedMetric = "datadog.dogstatsd.client.bytes_dropped"; protected final String packetsSentMetric = "datadog.dogstatsd.client.packets_sent"; protected final String packetsDroppedMetric = "datadog.dogstatsd.client.packets_dropped"; protected final String packetsDroppedQueueMetric = "datadog.dogstatsd.client.packets_dropped_queue"; protected final String aggregatedContextsMetric = "datadog.dogstatsd.client.aggregated_context"; protected final String aggregatedContextsByTypeMetric = "datadog.dogstatsd.client.aggregated_context_by_type"; protected String tags; protected StringBuilder tagBuilder = new StringBuilder(); public StatsDProcessor processor; protected Timer timer; protected class TelemetryTask extends TimerTask { private Telemetry telemetry; TelemetryTask(final Telemetry telemetry) { super(); this.telemetry = telemetry; } public void run() { this.telemetry.flush(); } } class TelemetryMessage extends NumericMessage<Integer> { private final String tagsString; // pre-baked comma separeated tags string protected TelemetryMessage(String metric, Integer value, String tags) {
super(metric, Message.Type.COUNT, value, null);
DataDog/java-dogstatsd-client
src/main/java/com/timgroup/statsd/StatsDAggregator.java
// Path: src/main/java/com/timgroup/statsd/Message.java // public abstract class Message { // final String aspect; // final Message.Type type; // final String[] tags; // protected boolean done; // protected Integer hash; // // // borrowed from Array.hashCode implementation: // // https://github.com/openjdk/jdk11/blob/master/src/java.base/share/classes/java/util/Arrays.java#L4454-L4465 // protected final int HASH_MULTIPLIER = 31; // // public enum Type { // GAUGE("g"), // COUNT("c"), // TIME("ms"), // SET("s"), // HISTOGRAM("h"), // DISTRIBUTION("d"), // EVENT("_e"), // SERVICE_CHECK("_sc"); // // private final String type; // // Type(String type) { // this.type = type; // } // // public String toString() { // return this.type; // } // } // // protected Message(Message.Type type) { // this.aspect = ""; // this.type = type; // this.done = false; // this.tags = null; // } // // protected Message(String aspect, Message.Type type, String[] tags) { // this.aspect = aspect; // this.type = type; // this.done = false; // this.tags = tags; // } // // /** // * Write this message to the provided {@link StringBuilder}. Will // * be called from the sender threads. // * // * @param builder // * StringBuilder the text representation will be written to. // */ // abstract void writeTo(StringBuilder builder); // // /** // * Aggregate message. // * // * @param message // * Message to aggregate. // */ // public abstract void aggregate(Message message); // // // /** // * Return the message aspect. // * // * @return returns the string representing the Message aspect // */ // public final String getAspect() { // return this.aspect; // } // // /** // * Return the message type. // * // * @return returns the dogstatsd type for the Message // */ // public final Type getType() { // return this.type; // } // // /** // * Return the array of tags for the message. // * // * @return returns the string array of tags for the Message // */ // public String[] getTags() { // return this.tags; // } // // /** // * Return whether a message can be aggregated. // * Not sure if this makes sense. // * // * @return boolean on whether or not this message type may be aggregated. // */ // public boolean canAggregate() { // // return (this.type == m.type); // return false; // } // // public void setDone(boolean done) { // this.done = done; // } // // public boolean getDone() { // return this.done; // } // // /** // * Messages must implement hashCode. // */ // @Override // public int hashCode() { // // cache it // if (this.hash == null) { // this.hash = new Integer(Objects.hash(this.aspect)) * HASH_MULTIPLIER; // this.hash += Objects.hash(this.tags); // } // // return this.hash; // } // // /** // * Messages must implement hashCode. // */ // @Override // public boolean equals(Object object) { // if (object == null) { // return false; // } // if (object instanceof Message) { // final Message msg = (Message)object; // // boolean equals = (this.getAspect() == msg.getAspect()) // && (this.getType() == msg.getType()) // && (this.done == msg.getDone()) // && Arrays.equals(this.tags, (msg.getTags())); // // return equals; // } // // return false; // } // }
import com.timgroup.statsd.Message; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.Timer; import java.util.TimerTask;
package com.timgroup.statsd; public class StatsDAggregator { public static int DEFAULT_FLUSH_INTERVAL = 2000; // 2s public static int DEFAULT_SHARDS = 4; // 4 partitions to reduce contention. protected final String AGGREGATOR_THREAD_NAME = "statsd-aggregator-thread";
// Path: src/main/java/com/timgroup/statsd/Message.java // public abstract class Message { // final String aspect; // final Message.Type type; // final String[] tags; // protected boolean done; // protected Integer hash; // // // borrowed from Array.hashCode implementation: // // https://github.com/openjdk/jdk11/blob/master/src/java.base/share/classes/java/util/Arrays.java#L4454-L4465 // protected final int HASH_MULTIPLIER = 31; // // public enum Type { // GAUGE("g"), // COUNT("c"), // TIME("ms"), // SET("s"), // HISTOGRAM("h"), // DISTRIBUTION("d"), // EVENT("_e"), // SERVICE_CHECK("_sc"); // // private final String type; // // Type(String type) { // this.type = type; // } // // public String toString() { // return this.type; // } // } // // protected Message(Message.Type type) { // this.aspect = ""; // this.type = type; // this.done = false; // this.tags = null; // } // // protected Message(String aspect, Message.Type type, String[] tags) { // this.aspect = aspect; // this.type = type; // this.done = false; // this.tags = tags; // } // // /** // * Write this message to the provided {@link StringBuilder}. Will // * be called from the sender threads. // * // * @param builder // * StringBuilder the text representation will be written to. // */ // abstract void writeTo(StringBuilder builder); // // /** // * Aggregate message. // * // * @param message // * Message to aggregate. // */ // public abstract void aggregate(Message message); // // // /** // * Return the message aspect. // * // * @return returns the string representing the Message aspect // */ // public final String getAspect() { // return this.aspect; // } // // /** // * Return the message type. // * // * @return returns the dogstatsd type for the Message // */ // public final Type getType() { // return this.type; // } // // /** // * Return the array of tags for the message. // * // * @return returns the string array of tags for the Message // */ // public String[] getTags() { // return this.tags; // } // // /** // * Return whether a message can be aggregated. // * Not sure if this makes sense. // * // * @return boolean on whether or not this message type may be aggregated. // */ // public boolean canAggregate() { // // return (this.type == m.type); // return false; // } // // public void setDone(boolean done) { // this.done = done; // } // // public boolean getDone() { // return this.done; // } // // /** // * Messages must implement hashCode. // */ // @Override // public int hashCode() { // // cache it // if (this.hash == null) { // this.hash = new Integer(Objects.hash(this.aspect)) * HASH_MULTIPLIER; // this.hash += Objects.hash(this.tags); // } // // return this.hash; // } // // /** // * Messages must implement hashCode. // */ // @Override // public boolean equals(Object object) { // if (object == null) { // return false; // } // if (object instanceof Message) { // final Message msg = (Message)object; // // boolean equals = (this.getAspect() == msg.getAspect()) // && (this.getType() == msg.getType()) // && (this.done == msg.getDone()) // && Arrays.equals(this.tags, (msg.getTags())); // // return equals; // } // // return false; // } // } // Path: src/main/java/com/timgroup/statsd/StatsDAggregator.java import com.timgroup.statsd.Message; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.Timer; import java.util.TimerTask; package com.timgroup.statsd; public class StatsDAggregator { public static int DEFAULT_FLUSH_INTERVAL = 2000; // 2s public static int DEFAULT_SHARDS = 4; // 4 partitions to reduce contention. protected final String AGGREGATOR_THREAD_NAME = "statsd-aggregator-thread";
protected final Set<Message.Type> aggregateSet = new HashSet<>(
DataDog/java-dogstatsd-client
src/main/java/com/timgroup/statsd/StatsDProcessor.java
// Path: src/main/java/com/timgroup/statsd/Message.java // public abstract class Message { // final String aspect; // final Message.Type type; // final String[] tags; // protected boolean done; // protected Integer hash; // // // borrowed from Array.hashCode implementation: // // https://github.com/openjdk/jdk11/blob/master/src/java.base/share/classes/java/util/Arrays.java#L4454-L4465 // protected final int HASH_MULTIPLIER = 31; // // public enum Type { // GAUGE("g"), // COUNT("c"), // TIME("ms"), // SET("s"), // HISTOGRAM("h"), // DISTRIBUTION("d"), // EVENT("_e"), // SERVICE_CHECK("_sc"); // // private final String type; // // Type(String type) { // this.type = type; // } // // public String toString() { // return this.type; // } // } // // protected Message(Message.Type type) { // this.aspect = ""; // this.type = type; // this.done = false; // this.tags = null; // } // // protected Message(String aspect, Message.Type type, String[] tags) { // this.aspect = aspect; // this.type = type; // this.done = false; // this.tags = tags; // } // // /** // * Write this message to the provided {@link StringBuilder}. Will // * be called from the sender threads. // * // * @param builder // * StringBuilder the text representation will be written to. // */ // abstract void writeTo(StringBuilder builder); // // /** // * Aggregate message. // * // * @param message // * Message to aggregate. // */ // public abstract void aggregate(Message message); // // // /** // * Return the message aspect. // * // * @return returns the string representing the Message aspect // */ // public final String getAspect() { // return this.aspect; // } // // /** // * Return the message type. // * // * @return returns the dogstatsd type for the Message // */ // public final Type getType() { // return this.type; // } // // /** // * Return the array of tags for the message. // * // * @return returns the string array of tags for the Message // */ // public String[] getTags() { // return this.tags; // } // // /** // * Return whether a message can be aggregated. // * Not sure if this makes sense. // * // * @return boolean on whether or not this message type may be aggregated. // */ // public boolean canAggregate() { // // return (this.type == m.type); // return false; // } // // public void setDone(boolean done) { // this.done = done; // } // // public boolean getDone() { // return this.done; // } // // /** // * Messages must implement hashCode. // */ // @Override // public int hashCode() { // // cache it // if (this.hash == null) { // this.hash = new Integer(Objects.hash(this.aspect)) * HASH_MULTIPLIER; // this.hash += Objects.hash(this.tags); // } // // return this.hash; // } // // /** // * Messages must implement hashCode. // */ // @Override // public boolean equals(Object object) { // if (object == null) { // return false; // } // if (object instanceof Message) { // final Message msg = (Message)object; // // boolean equals = (this.getAspect() == msg.getAspect()) // && (this.getType() == msg.getType()) // && (this.done == msg.getDone()) // && Arrays.equals(this.tags, (msg.getTags())); // // return equals; // } // // return false; // } // }
import com.timgroup.statsd.Message; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger;
package com.timgroup.statsd; public abstract class StatsDProcessor { protected static final Charset MESSAGE_CHARSET = Charset.forName("UTF-8"); protected static final String MESSAGE_TOO_LONG = "Message longer than size of sendBuffer"; protected static final int WAIT_SLEEP_MS = 10; // 10 ms would be a 100HZ slice protected final StatsDClientErrorHandler handler; protected final BufferPool bufferPool;
// Path: src/main/java/com/timgroup/statsd/Message.java // public abstract class Message { // final String aspect; // final Message.Type type; // final String[] tags; // protected boolean done; // protected Integer hash; // // // borrowed from Array.hashCode implementation: // // https://github.com/openjdk/jdk11/blob/master/src/java.base/share/classes/java/util/Arrays.java#L4454-L4465 // protected final int HASH_MULTIPLIER = 31; // // public enum Type { // GAUGE("g"), // COUNT("c"), // TIME("ms"), // SET("s"), // HISTOGRAM("h"), // DISTRIBUTION("d"), // EVENT("_e"), // SERVICE_CHECK("_sc"); // // private final String type; // // Type(String type) { // this.type = type; // } // // public String toString() { // return this.type; // } // } // // protected Message(Message.Type type) { // this.aspect = ""; // this.type = type; // this.done = false; // this.tags = null; // } // // protected Message(String aspect, Message.Type type, String[] tags) { // this.aspect = aspect; // this.type = type; // this.done = false; // this.tags = tags; // } // // /** // * Write this message to the provided {@link StringBuilder}. Will // * be called from the sender threads. // * // * @param builder // * StringBuilder the text representation will be written to. // */ // abstract void writeTo(StringBuilder builder); // // /** // * Aggregate message. // * // * @param message // * Message to aggregate. // */ // public abstract void aggregate(Message message); // // // /** // * Return the message aspect. // * // * @return returns the string representing the Message aspect // */ // public final String getAspect() { // return this.aspect; // } // // /** // * Return the message type. // * // * @return returns the dogstatsd type for the Message // */ // public final Type getType() { // return this.type; // } // // /** // * Return the array of tags for the message. // * // * @return returns the string array of tags for the Message // */ // public String[] getTags() { // return this.tags; // } // // /** // * Return whether a message can be aggregated. // * Not sure if this makes sense. // * // * @return boolean on whether or not this message type may be aggregated. // */ // public boolean canAggregate() { // // return (this.type == m.type); // return false; // } // // public void setDone(boolean done) { // this.done = done; // } // // public boolean getDone() { // return this.done; // } // // /** // * Messages must implement hashCode. // */ // @Override // public int hashCode() { // // cache it // if (this.hash == null) { // this.hash = new Integer(Objects.hash(this.aspect)) * HASH_MULTIPLIER; // this.hash += Objects.hash(this.tags); // } // // return this.hash; // } // // /** // * Messages must implement hashCode. // */ // @Override // public boolean equals(Object object) { // if (object == null) { // return false; // } // if (object instanceof Message) { // final Message msg = (Message)object; // // boolean equals = (this.getAspect() == msg.getAspect()) // && (this.getType() == msg.getType()) // && (this.done == msg.getDone()) // && Arrays.equals(this.tags, (msg.getTags())); // // return equals; // } // // return false; // } // } // Path: src/main/java/com/timgroup/statsd/StatsDProcessor.java import com.timgroup.statsd.Message; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; package com.timgroup.statsd; public abstract class StatsDProcessor { protected static final Charset MESSAGE_CHARSET = Charset.forName("UTF-8"); protected static final String MESSAGE_TOO_LONG = "Message longer than size of sendBuffer"; protected static final int WAIT_SLEEP_MS = 10; // 10 ms would be a 100HZ slice protected final StatsDClientErrorHandler handler; protected final BufferPool bufferPool;
protected final Queue<Message> highPrioMessages; // FIFO queue for high priority messages
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/ui/widget/PickerScrollView.java
// Path: app/src/main/java/com/sola/v2ex_android/model/Pickers.java // public class Pickers implements Serializable { // // public String title; // public String id; // // public Pickers(String title ,String id ){ // this.title = title; // this.id = id; // } // // } // // Path: app/src/main/java/com/sola/v2ex_android/util/LogUtil.java // public class LogUtil { // // public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化 // private static final String TAG = "zuqiukong"; // // public LogUtil() { // } // // // 下面四个是默认tag的函数 // public static void i(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(TAG, msg); // } // // public static void d(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(TAG, msg); // } // // public static void e(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(TAG, msg); // } // public static void dClass(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // { // String clazzName = new Throwable().getStackTrace()[1].getClassName(); // String[] clazzNames = clazzName.split("\\."); // Log.d(clazzNames[clazzNames.length - 1], msg); // } // } // // public static void v(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.v(TAG, msg); // } // // // 下面是传入自定义tag的函数 // public static void i(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(tag, msg); // } // // public static void d(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(tag, msg); // } // // public static void e(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(tag, msg); // } // // public static void v(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.v(tag, msg); // } // // public static void w(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.w(tag, msg); // } // // public static void wtf(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.wtf(tag, msg); // } // // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import com.sola.v2ex_android.model.Pickers; import com.sola.v2ex_android.util.LogUtil; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask;
package com.sola.v2ex_android.ui.widget; /** * Created by wei on 2016/12/2. */ public class PickerScrollView extends View { /** * text之间间距和minTextSize之比 */ public static final float MARGIN_ALPHA = 2.0f; /** * 自动回滚到中间的速度 */ public static final float SPEED = 2;
// Path: app/src/main/java/com/sola/v2ex_android/model/Pickers.java // public class Pickers implements Serializable { // // public String title; // public String id; // // public Pickers(String title ,String id ){ // this.title = title; // this.id = id; // } // // } // // Path: app/src/main/java/com/sola/v2ex_android/util/LogUtil.java // public class LogUtil { // // public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化 // private static final String TAG = "zuqiukong"; // // public LogUtil() { // } // // // 下面四个是默认tag的函数 // public static void i(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(TAG, msg); // } // // public static void d(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(TAG, msg); // } // // public static void e(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(TAG, msg); // } // public static void dClass(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // { // String clazzName = new Throwable().getStackTrace()[1].getClassName(); // String[] clazzNames = clazzName.split("\\."); // Log.d(clazzNames[clazzNames.length - 1], msg); // } // } // // public static void v(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.v(TAG, msg); // } // // // 下面是传入自定义tag的函数 // public static void i(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(tag, msg); // } // // public static void d(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(tag, msg); // } // // public static void e(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(tag, msg); // } // // public static void v(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.v(tag, msg); // } // // public static void w(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.w(tag, msg); // } // // public static void wtf(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.wtf(tag, msg); // } // // } // Path: app/src/main/java/com/sola/v2ex_android/ui/widget/PickerScrollView.java import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import com.sola.v2ex_android.model.Pickers; import com.sola.v2ex_android.util.LogUtil; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; package com.sola.v2ex_android.ui.widget; /** * Created by wei on 2016/12/2. */ public class PickerScrollView extends View { /** * text之间间距和minTextSize之比 */ public static final float MARGIN_ALPHA = 2.0f; /** * 自动回滚到中间的速度 */ public static final float SPEED = 2;
private List<Pickers> mDataList;
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/ui/widget/PickerScrollView.java
// Path: app/src/main/java/com/sola/v2ex_android/model/Pickers.java // public class Pickers implements Serializable { // // public String title; // public String id; // // public Pickers(String title ,String id ){ // this.title = title; // this.id = id; // } // // } // // Path: app/src/main/java/com/sola/v2ex_android/util/LogUtil.java // public class LogUtil { // // public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化 // private static final String TAG = "zuqiukong"; // // public LogUtil() { // } // // // 下面四个是默认tag的函数 // public static void i(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(TAG, msg); // } // // public static void d(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(TAG, msg); // } // // public static void e(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(TAG, msg); // } // public static void dClass(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // { // String clazzName = new Throwable().getStackTrace()[1].getClassName(); // String[] clazzNames = clazzName.split("\\."); // Log.d(clazzNames[clazzNames.length - 1], msg); // } // } // // public static void v(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.v(TAG, msg); // } // // // 下面是传入自定义tag的函数 // public static void i(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(tag, msg); // } // // public static void d(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(tag, msg); // } // // public static void e(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(tag, msg); // } // // public static void v(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.v(tag, msg); // } // // public static void w(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.w(tag, msg); // } // // public static void wtf(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.wtf(tag, msg); // } // // }
import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import com.sola.v2ex_android.model.Pickers; import com.sola.v2ex_android.util.LogUtil; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask;
float baseline = (float) (y - (fmi.bottom / 2.0 + fmi.top / 2.0)); int indexs = mCurrentSelected; String textData = mDataList.get(indexs).title; canvas.drawLine(0 , y - size / 2 ,mViewWidth , y - size / 2 - 6 ,mPaint); canvas.drawText(textData, x, baseline , mPaint); canvas.drawLine(0 , y + size /2 ,mViewWidth , y + size / 2 + 6 ,mPaint); // 绘制上方data for (int i = 1; (mCurrentSelected - i) >= 0; i++) { drawOtherText(canvas, i, -1); } // 绘制下方data for (int i = 1; (mCurrentSelected + i) < mDataList.size(); i++) { drawOtherText(canvas, i, 1); } } /** * @param canvas * @param position * 距离mCurrentSelected的差值 * @param type * 1表示向下绘制,-1表示向上绘制 */ private void drawOtherText(Canvas canvas, int position, int type) { float d = (float) (MARGIN_ALPHA * mMinTextSize * position + type * mMoveLen); float scale = parabola(mViewHeight / 4.0f, d);
// Path: app/src/main/java/com/sola/v2ex_android/model/Pickers.java // public class Pickers implements Serializable { // // public String title; // public String id; // // public Pickers(String title ,String id ){ // this.title = title; // this.id = id; // } // // } // // Path: app/src/main/java/com/sola/v2ex_android/util/LogUtil.java // public class LogUtil { // // public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化 // private static final String TAG = "zuqiukong"; // // public LogUtil() { // } // // // 下面四个是默认tag的函数 // public static void i(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(TAG, msg); // } // // public static void d(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(TAG, msg); // } // // public static void e(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(TAG, msg); // } // public static void dClass(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // { // String clazzName = new Throwable().getStackTrace()[1].getClassName(); // String[] clazzNames = clazzName.split("\\."); // Log.d(clazzNames[clazzNames.length - 1], msg); // } // } // // public static void v(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.v(TAG, msg); // } // // // 下面是传入自定义tag的函数 // public static void i(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(tag, msg); // } // // public static void d(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(tag, msg); // } // // public static void e(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(tag, msg); // } // // public static void v(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.v(tag, msg); // } // // public static void w(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.w(tag, msg); // } // // public static void wtf(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.wtf(tag, msg); // } // // } // Path: app/src/main/java/com/sola/v2ex_android/ui/widget/PickerScrollView.java import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import com.sola.v2ex_android.model.Pickers; import com.sola.v2ex_android.util.LogUtil; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; float baseline = (float) (y - (fmi.bottom / 2.0 + fmi.top / 2.0)); int indexs = mCurrentSelected; String textData = mDataList.get(indexs).title; canvas.drawLine(0 , y - size / 2 ,mViewWidth , y - size / 2 - 6 ,mPaint); canvas.drawText(textData, x, baseline , mPaint); canvas.drawLine(0 , y + size /2 ,mViewWidth , y + size / 2 + 6 ,mPaint); // 绘制上方data for (int i = 1; (mCurrentSelected - i) >= 0; i++) { drawOtherText(canvas, i, -1); } // 绘制下方data for (int i = 1; (mCurrentSelected + i) < mDataList.size(); i++) { drawOtherText(canvas, i, 1); } } /** * @param canvas * @param position * 距离mCurrentSelected的差值 * @param type * 1表示向下绘制,-1表示向上绘制 */ private void drawOtherText(Canvas canvas, int position, int type) { float d = (float) (MARGIN_ALPHA * mMinTextSize * position + type * mMoveLen); float scale = parabola(mViewHeight / 4.0f, d);
LogUtil.d("PickerScrollView","scale" + scale);
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/util/JsoupUtil.java
// Path: app/src/main/java/com/sola/v2ex_android/model/LoginResult.java // public class LoginResult { // // public LoginResult() { // // } // // public LoginResult(String userId, String userAvatar) { // this.userId = userId; // this.userAvatar = userAvatar; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // // public String getUserAvatar() { // return userAvatar; // } // // public void setUserAvatar(String userAvatar) { // this.userAvatar = userAvatar; // } // // public String userId; // public String userAvatar; // public String message; // // @Override // public String toString() { // return "LoginResult{" + // "userId='" + userId + '\'' + // ", userAvatar='" + userAvatar + '\'' + // ", message='" + message + '\'' + // '}'; // } // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyFollowing.java // public class MyFollowing { // // public String userName; // public String title; // public String userIconUrl; // public String nodeName; // public String commentCount; // public String topicId; // // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyFollowingTopicDetial.java // public class MyFollowingTopicDetial { // // public String avatar; // public String userName; // public String title; // public String content; // public String publishTime; // public int replies_count; // // public List<Replies> replies; // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyNode.java // public class MyNode { // // public String imgSrc; // public String nodeName; // public String followCount; // // @Override // public String toString() { // return "MyNode{" + // "imgSrc='" + imgSrc + '\'' + // ", nodeName='" + nodeName + '\'' + // ", collectNumber='" + followCount + '\'' + // '}'; // } // } // // Path: app/src/main/java/com/sola/v2ex_android/model/Replies.java // public class Replies { // // public int id; // public int thanks; // public String content; // public String content_rendered; // public String publishTime; // public MemberEntity member; // public long created; // public int last_modified; // // @Override // public String toString() { // return "Replies{" + // "id=" + id + // ", thanks=" + thanks + // ", content='" + content + '\'' + // ", content_rendered='" + content_rendered + '\'' + // ", member=" + member + // ", created=" + created + // ", last_modified=" + last_modified + // '}'; // } // // public static class MemberEntity { // public int id; // public String username; // public String tagline; // public String avatar_mini; // public String avatar_normal; // public String avatar_large; // // @Override // public String toString() { // return "MemberEntity{" + // "id=" + id + // ", username='" + username + '\'' + // ", tagline='" + tagline + '\'' + // ", avatar_mini='" + avatar_mini + '\'' + // ", avatar_normal='" + avatar_normal + '\'' + // ", avatar_large='" + avatar_large + '\'' + // '}'; // } // } // }
import com.sola.v2ex_android.model.LoginResult; import com.sola.v2ex_android.model.MyFollowing; import com.sola.v2ex_android.model.MyFollowingTopicDetial; import com.sola.v2ex_android.model.MyNode; import com.sola.v2ex_android.model.Replies; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
loginResult = new LoginResult(userId, src); return loginResult; } public static HashMap parseUserNameAndPwd(String stringResponse, String username, String password) { Element body = Jsoup.parse(stringResponse); Elements boxes = body.getElementsByClass("box"); HashMap params = new HashMap(); for (Element el : boxes) { Elements cell = el.getElementsByClass("cell"); for (Element c : cell) { String nameVal = c.getElementsByAttributeValue("type", "text").attr("name"); String passwordVal = c.getElementsByAttributeValue("type", "password").attr("name"); String once = c.getElementsByAttributeValue("name", "once").attr("value"); if (nameVal.isEmpty() || passwordVal.isEmpty()) continue; params.put(nameVal, username); params.put("once", once); params.put(passwordVal, password); break; } } params.put("next", "/"); return params; } /** * 解析我关注的节点 * @param response * @return */
// Path: app/src/main/java/com/sola/v2ex_android/model/LoginResult.java // public class LoginResult { // // public LoginResult() { // // } // // public LoginResult(String userId, String userAvatar) { // this.userId = userId; // this.userAvatar = userAvatar; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // // public String getUserAvatar() { // return userAvatar; // } // // public void setUserAvatar(String userAvatar) { // this.userAvatar = userAvatar; // } // // public String userId; // public String userAvatar; // public String message; // // @Override // public String toString() { // return "LoginResult{" + // "userId='" + userId + '\'' + // ", userAvatar='" + userAvatar + '\'' + // ", message='" + message + '\'' + // '}'; // } // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyFollowing.java // public class MyFollowing { // // public String userName; // public String title; // public String userIconUrl; // public String nodeName; // public String commentCount; // public String topicId; // // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyFollowingTopicDetial.java // public class MyFollowingTopicDetial { // // public String avatar; // public String userName; // public String title; // public String content; // public String publishTime; // public int replies_count; // // public List<Replies> replies; // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyNode.java // public class MyNode { // // public String imgSrc; // public String nodeName; // public String followCount; // // @Override // public String toString() { // return "MyNode{" + // "imgSrc='" + imgSrc + '\'' + // ", nodeName='" + nodeName + '\'' + // ", collectNumber='" + followCount + '\'' + // '}'; // } // } // // Path: app/src/main/java/com/sola/v2ex_android/model/Replies.java // public class Replies { // // public int id; // public int thanks; // public String content; // public String content_rendered; // public String publishTime; // public MemberEntity member; // public long created; // public int last_modified; // // @Override // public String toString() { // return "Replies{" + // "id=" + id + // ", thanks=" + thanks + // ", content='" + content + '\'' + // ", content_rendered='" + content_rendered + '\'' + // ", member=" + member + // ", created=" + created + // ", last_modified=" + last_modified + // '}'; // } // // public static class MemberEntity { // public int id; // public String username; // public String tagline; // public String avatar_mini; // public String avatar_normal; // public String avatar_large; // // @Override // public String toString() { // return "MemberEntity{" + // "id=" + id + // ", username='" + username + '\'' + // ", tagline='" + tagline + '\'' + // ", avatar_mini='" + avatar_mini + '\'' + // ", avatar_normal='" + avatar_normal + '\'' + // ", avatar_large='" + avatar_large + '\'' + // '}'; // } // } // } // Path: app/src/main/java/com/sola/v2ex_android/util/JsoupUtil.java import com.sola.v2ex_android.model.LoginResult; import com.sola.v2ex_android.model.MyFollowing; import com.sola.v2ex_android.model.MyFollowingTopicDetial; import com.sola.v2ex_android.model.MyNode; import com.sola.v2ex_android.model.Replies; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.HashMap; import java.util.List; loginResult = new LoginResult(userId, src); return loginResult; } public static HashMap parseUserNameAndPwd(String stringResponse, String username, String password) { Element body = Jsoup.parse(stringResponse); Elements boxes = body.getElementsByClass("box"); HashMap params = new HashMap(); for (Element el : boxes) { Elements cell = el.getElementsByClass("cell"); for (Element c : cell) { String nameVal = c.getElementsByAttributeValue("type", "text").attr("name"); String passwordVal = c.getElementsByAttributeValue("type", "password").attr("name"); String once = c.getElementsByAttributeValue("name", "once").attr("value"); if (nameVal.isEmpty() || passwordVal.isEmpty()) continue; params.put(nameVal, username); params.put("once", once); params.put(passwordVal, password); break; } } params.put("next", "/"); return params; } /** * 解析我关注的节点 * @param response * @return */
public static List<MyNode> parseMyNodeInfo(String response){
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/util/JsoupUtil.java
// Path: app/src/main/java/com/sola/v2ex_android/model/LoginResult.java // public class LoginResult { // // public LoginResult() { // // } // // public LoginResult(String userId, String userAvatar) { // this.userId = userId; // this.userAvatar = userAvatar; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // // public String getUserAvatar() { // return userAvatar; // } // // public void setUserAvatar(String userAvatar) { // this.userAvatar = userAvatar; // } // // public String userId; // public String userAvatar; // public String message; // // @Override // public String toString() { // return "LoginResult{" + // "userId='" + userId + '\'' + // ", userAvatar='" + userAvatar + '\'' + // ", message='" + message + '\'' + // '}'; // } // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyFollowing.java // public class MyFollowing { // // public String userName; // public String title; // public String userIconUrl; // public String nodeName; // public String commentCount; // public String topicId; // // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyFollowingTopicDetial.java // public class MyFollowingTopicDetial { // // public String avatar; // public String userName; // public String title; // public String content; // public String publishTime; // public int replies_count; // // public List<Replies> replies; // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyNode.java // public class MyNode { // // public String imgSrc; // public String nodeName; // public String followCount; // // @Override // public String toString() { // return "MyNode{" + // "imgSrc='" + imgSrc + '\'' + // ", nodeName='" + nodeName + '\'' + // ", collectNumber='" + followCount + '\'' + // '}'; // } // } // // Path: app/src/main/java/com/sola/v2ex_android/model/Replies.java // public class Replies { // // public int id; // public int thanks; // public String content; // public String content_rendered; // public String publishTime; // public MemberEntity member; // public long created; // public int last_modified; // // @Override // public String toString() { // return "Replies{" + // "id=" + id + // ", thanks=" + thanks + // ", content='" + content + '\'' + // ", content_rendered='" + content_rendered + '\'' + // ", member=" + member + // ", created=" + created + // ", last_modified=" + last_modified + // '}'; // } // // public static class MemberEntity { // public int id; // public String username; // public String tagline; // public String avatar_mini; // public String avatar_normal; // public String avatar_large; // // @Override // public String toString() { // return "MemberEntity{" + // "id=" + id + // ", username='" + username + '\'' + // ", tagline='" + tagline + '\'' + // ", avatar_mini='" + avatar_mini + '\'' + // ", avatar_normal='" + avatar_normal + '\'' + // ", avatar_large='" + avatar_large + '\'' + // '}'; // } // } // }
import com.sola.v2ex_android.model.LoginResult; import com.sola.v2ex_android.model.MyFollowing; import com.sola.v2ex_android.model.MyFollowingTopicDetial; import com.sola.v2ex_android.model.MyNode; import com.sola.v2ex_android.model.Replies; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
* @param response * @return */ public static List<MyNode> parseMyNodeInfo(String response){ List<MyNode> myNodeList = new ArrayList<>(); Document doc = Jsoup.parse(response); Element body = doc.body(); Elements elements = body.getElementsByAttributeValue("id", "MyNodes"); for (Element el : elements) { Elements aNodes = el.getElementsByTag("a"); for (Element tdNode : aNodes) { MyNode mynode = new MyNode(); String hrefStr = tdNode.attr("href"); Elements avatarNode = tdNode.getElementsByTag("img"); if (avatarNode != null) { String avatarString = avatarNode.attr("src"); if (avatarString.startsWith("//")) { mynode.imgSrc = "http:" + avatarString; } } Elements attentionNode = tdNode.getElementsByClass("fade f12"); mynode.followCount = attentionNode.text(); mynode.nodeName = hrefStr.substring(4); myNodeList.add(mynode); } } return myNodeList; }
// Path: app/src/main/java/com/sola/v2ex_android/model/LoginResult.java // public class LoginResult { // // public LoginResult() { // // } // // public LoginResult(String userId, String userAvatar) { // this.userId = userId; // this.userAvatar = userAvatar; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // // public String getUserAvatar() { // return userAvatar; // } // // public void setUserAvatar(String userAvatar) { // this.userAvatar = userAvatar; // } // // public String userId; // public String userAvatar; // public String message; // // @Override // public String toString() { // return "LoginResult{" + // "userId='" + userId + '\'' + // ", userAvatar='" + userAvatar + '\'' + // ", message='" + message + '\'' + // '}'; // } // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyFollowing.java // public class MyFollowing { // // public String userName; // public String title; // public String userIconUrl; // public String nodeName; // public String commentCount; // public String topicId; // // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyFollowingTopicDetial.java // public class MyFollowingTopicDetial { // // public String avatar; // public String userName; // public String title; // public String content; // public String publishTime; // public int replies_count; // // public List<Replies> replies; // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyNode.java // public class MyNode { // // public String imgSrc; // public String nodeName; // public String followCount; // // @Override // public String toString() { // return "MyNode{" + // "imgSrc='" + imgSrc + '\'' + // ", nodeName='" + nodeName + '\'' + // ", collectNumber='" + followCount + '\'' + // '}'; // } // } // // Path: app/src/main/java/com/sola/v2ex_android/model/Replies.java // public class Replies { // // public int id; // public int thanks; // public String content; // public String content_rendered; // public String publishTime; // public MemberEntity member; // public long created; // public int last_modified; // // @Override // public String toString() { // return "Replies{" + // "id=" + id + // ", thanks=" + thanks + // ", content='" + content + '\'' + // ", content_rendered='" + content_rendered + '\'' + // ", member=" + member + // ", created=" + created + // ", last_modified=" + last_modified + // '}'; // } // // public static class MemberEntity { // public int id; // public String username; // public String tagline; // public String avatar_mini; // public String avatar_normal; // public String avatar_large; // // @Override // public String toString() { // return "MemberEntity{" + // "id=" + id + // ", username='" + username + '\'' + // ", tagline='" + tagline + '\'' + // ", avatar_mini='" + avatar_mini + '\'' + // ", avatar_normal='" + avatar_normal + '\'' + // ", avatar_large='" + avatar_large + '\'' + // '}'; // } // } // } // Path: app/src/main/java/com/sola/v2ex_android/util/JsoupUtil.java import com.sola.v2ex_android.model.LoginResult; import com.sola.v2ex_android.model.MyFollowing; import com.sola.v2ex_android.model.MyFollowingTopicDetial; import com.sola.v2ex_android.model.MyNode; import com.sola.v2ex_android.model.Replies; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.HashMap; import java.util.List; * @param response * @return */ public static List<MyNode> parseMyNodeInfo(String response){ List<MyNode> myNodeList = new ArrayList<>(); Document doc = Jsoup.parse(response); Element body = doc.body(); Elements elements = body.getElementsByAttributeValue("id", "MyNodes"); for (Element el : elements) { Elements aNodes = el.getElementsByTag("a"); for (Element tdNode : aNodes) { MyNode mynode = new MyNode(); String hrefStr = tdNode.attr("href"); Elements avatarNode = tdNode.getElementsByTag("img"); if (avatarNode != null) { String avatarString = avatarNode.attr("src"); if (avatarString.startsWith("//")) { mynode.imgSrc = "http:" + avatarString; } } Elements attentionNode = tdNode.getElementsByClass("fade f12"); mynode.followCount = attentionNode.text(); mynode.nodeName = hrefStr.substring(4); myNodeList.add(mynode); } } return myNodeList; }
public static List<MyFollowing> parseMyfollowing(String response){
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/util/JsoupUtil.java
// Path: app/src/main/java/com/sola/v2ex_android/model/LoginResult.java // public class LoginResult { // // public LoginResult() { // // } // // public LoginResult(String userId, String userAvatar) { // this.userId = userId; // this.userAvatar = userAvatar; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // // public String getUserAvatar() { // return userAvatar; // } // // public void setUserAvatar(String userAvatar) { // this.userAvatar = userAvatar; // } // // public String userId; // public String userAvatar; // public String message; // // @Override // public String toString() { // return "LoginResult{" + // "userId='" + userId + '\'' + // ", userAvatar='" + userAvatar + '\'' + // ", message='" + message + '\'' + // '}'; // } // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyFollowing.java // public class MyFollowing { // // public String userName; // public String title; // public String userIconUrl; // public String nodeName; // public String commentCount; // public String topicId; // // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyFollowingTopicDetial.java // public class MyFollowingTopicDetial { // // public String avatar; // public String userName; // public String title; // public String content; // public String publishTime; // public int replies_count; // // public List<Replies> replies; // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyNode.java // public class MyNode { // // public String imgSrc; // public String nodeName; // public String followCount; // // @Override // public String toString() { // return "MyNode{" + // "imgSrc='" + imgSrc + '\'' + // ", nodeName='" + nodeName + '\'' + // ", collectNumber='" + followCount + '\'' + // '}'; // } // } // // Path: app/src/main/java/com/sola/v2ex_android/model/Replies.java // public class Replies { // // public int id; // public int thanks; // public String content; // public String content_rendered; // public String publishTime; // public MemberEntity member; // public long created; // public int last_modified; // // @Override // public String toString() { // return "Replies{" + // "id=" + id + // ", thanks=" + thanks + // ", content='" + content + '\'' + // ", content_rendered='" + content_rendered + '\'' + // ", member=" + member + // ", created=" + created + // ", last_modified=" + last_modified + // '}'; // } // // public static class MemberEntity { // public int id; // public String username; // public String tagline; // public String avatar_mini; // public String avatar_normal; // public String avatar_large; // // @Override // public String toString() { // return "MemberEntity{" + // "id=" + id + // ", username='" + username + '\'' + // ", tagline='" + tagline + '\'' + // ", avatar_mini='" + avatar_mini + '\'' + // ", avatar_normal='" + avatar_normal + '\'' + // ", avatar_large='" + avatar_large + '\'' + // '}'; // } // } // }
import com.sola.v2ex_android.model.LoginResult; import com.sola.v2ex_android.model.MyFollowing; import com.sola.v2ex_android.model.MyFollowingTopicDetial; import com.sola.v2ex_android.model.MyNode; import com.sola.v2ex_android.model.Replies; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
public static List<MyFollowing> parseMyfollowing(String response){ List<MyFollowing> myfollowingList = new ArrayList<>(); Document doc = Jsoup.parse(response); Element body = doc.body(); Element mainElement = body.getElementById("Main"); Elements itemElements = mainElement.getElementsByClass("cell item"); for (Element itemElement : itemElements) { MyFollowing myfollow = new MyFollowing(); Elements titleElements = itemElement.getElementsByClass("item_title"); Elements nodeElements = itemElement.getElementsByClass("node"); Elements hrefElements = itemElement.getElementsByAttribute("href"); String href = titleElements.select("a").attr("href"); myfollow.topicId = href.substring(3 , href.indexOf("#")); myfollow.title = titleElements.text(); myfollow.nodeName = nodeElements.text(); myfollow.userName = hrefElements.first().attr("href").substring(8); myfollow.commentCount = itemElement.getElementsByClass("count_livid").text(); Elements avatarNode = itemElement.getElementsByTag("img"); if (avatarNode != null) { String avatarString = avatarNode.attr("src"); if (avatarString.startsWith("//")) { myfollow.userIconUrl = "http:" + avatarString; } } myfollowingList.add(myfollow); } return myfollowingList; }
// Path: app/src/main/java/com/sola/v2ex_android/model/LoginResult.java // public class LoginResult { // // public LoginResult() { // // } // // public LoginResult(String userId, String userAvatar) { // this.userId = userId; // this.userAvatar = userAvatar; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // // public String getUserAvatar() { // return userAvatar; // } // // public void setUserAvatar(String userAvatar) { // this.userAvatar = userAvatar; // } // // public String userId; // public String userAvatar; // public String message; // // @Override // public String toString() { // return "LoginResult{" + // "userId='" + userId + '\'' + // ", userAvatar='" + userAvatar + '\'' + // ", message='" + message + '\'' + // '}'; // } // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyFollowing.java // public class MyFollowing { // // public String userName; // public String title; // public String userIconUrl; // public String nodeName; // public String commentCount; // public String topicId; // // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyFollowingTopicDetial.java // public class MyFollowingTopicDetial { // // public String avatar; // public String userName; // public String title; // public String content; // public String publishTime; // public int replies_count; // // public List<Replies> replies; // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyNode.java // public class MyNode { // // public String imgSrc; // public String nodeName; // public String followCount; // // @Override // public String toString() { // return "MyNode{" + // "imgSrc='" + imgSrc + '\'' + // ", nodeName='" + nodeName + '\'' + // ", collectNumber='" + followCount + '\'' + // '}'; // } // } // // Path: app/src/main/java/com/sola/v2ex_android/model/Replies.java // public class Replies { // // public int id; // public int thanks; // public String content; // public String content_rendered; // public String publishTime; // public MemberEntity member; // public long created; // public int last_modified; // // @Override // public String toString() { // return "Replies{" + // "id=" + id + // ", thanks=" + thanks + // ", content='" + content + '\'' + // ", content_rendered='" + content_rendered + '\'' + // ", member=" + member + // ", created=" + created + // ", last_modified=" + last_modified + // '}'; // } // // public static class MemberEntity { // public int id; // public String username; // public String tagline; // public String avatar_mini; // public String avatar_normal; // public String avatar_large; // // @Override // public String toString() { // return "MemberEntity{" + // "id=" + id + // ", username='" + username + '\'' + // ", tagline='" + tagline + '\'' + // ", avatar_mini='" + avatar_mini + '\'' + // ", avatar_normal='" + avatar_normal + '\'' + // ", avatar_large='" + avatar_large + '\'' + // '}'; // } // } // } // Path: app/src/main/java/com/sola/v2ex_android/util/JsoupUtil.java import com.sola.v2ex_android.model.LoginResult; import com.sola.v2ex_android.model.MyFollowing; import com.sola.v2ex_android.model.MyFollowingTopicDetial; import com.sola.v2ex_android.model.MyNode; import com.sola.v2ex_android.model.Replies; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public static List<MyFollowing> parseMyfollowing(String response){ List<MyFollowing> myfollowingList = new ArrayList<>(); Document doc = Jsoup.parse(response); Element body = doc.body(); Element mainElement = body.getElementById("Main"); Elements itemElements = mainElement.getElementsByClass("cell item"); for (Element itemElement : itemElements) { MyFollowing myfollow = new MyFollowing(); Elements titleElements = itemElement.getElementsByClass("item_title"); Elements nodeElements = itemElement.getElementsByClass("node"); Elements hrefElements = itemElement.getElementsByAttribute("href"); String href = titleElements.select("a").attr("href"); myfollow.topicId = href.substring(3 , href.indexOf("#")); myfollow.title = titleElements.text(); myfollow.nodeName = nodeElements.text(); myfollow.userName = hrefElements.first().attr("href").substring(8); myfollow.commentCount = itemElement.getElementsByClass("count_livid").text(); Elements avatarNode = itemElement.getElementsByTag("img"); if (avatarNode != null) { String avatarString = avatarNode.attr("src"); if (avatarString.startsWith("//")) { myfollow.userIconUrl = "http:" + avatarString; } } myfollowingList.add(myfollow); } return myfollowingList; }
public static MyFollowingTopicDetial parseMyfollowingTopicDetial(String response){
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/util/JsoupUtil.java
// Path: app/src/main/java/com/sola/v2ex_android/model/LoginResult.java // public class LoginResult { // // public LoginResult() { // // } // // public LoginResult(String userId, String userAvatar) { // this.userId = userId; // this.userAvatar = userAvatar; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // // public String getUserAvatar() { // return userAvatar; // } // // public void setUserAvatar(String userAvatar) { // this.userAvatar = userAvatar; // } // // public String userId; // public String userAvatar; // public String message; // // @Override // public String toString() { // return "LoginResult{" + // "userId='" + userId + '\'' + // ", userAvatar='" + userAvatar + '\'' + // ", message='" + message + '\'' + // '}'; // } // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyFollowing.java // public class MyFollowing { // // public String userName; // public String title; // public String userIconUrl; // public String nodeName; // public String commentCount; // public String topicId; // // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyFollowingTopicDetial.java // public class MyFollowingTopicDetial { // // public String avatar; // public String userName; // public String title; // public String content; // public String publishTime; // public int replies_count; // // public List<Replies> replies; // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyNode.java // public class MyNode { // // public String imgSrc; // public String nodeName; // public String followCount; // // @Override // public String toString() { // return "MyNode{" + // "imgSrc='" + imgSrc + '\'' + // ", nodeName='" + nodeName + '\'' + // ", collectNumber='" + followCount + '\'' + // '}'; // } // } // // Path: app/src/main/java/com/sola/v2ex_android/model/Replies.java // public class Replies { // // public int id; // public int thanks; // public String content; // public String content_rendered; // public String publishTime; // public MemberEntity member; // public long created; // public int last_modified; // // @Override // public String toString() { // return "Replies{" + // "id=" + id + // ", thanks=" + thanks + // ", content='" + content + '\'' + // ", content_rendered='" + content_rendered + '\'' + // ", member=" + member + // ", created=" + created + // ", last_modified=" + last_modified + // '}'; // } // // public static class MemberEntity { // public int id; // public String username; // public String tagline; // public String avatar_mini; // public String avatar_normal; // public String avatar_large; // // @Override // public String toString() { // return "MemberEntity{" + // "id=" + id + // ", username='" + username + '\'' + // ", tagline='" + tagline + '\'' + // ", avatar_mini='" + avatar_mini + '\'' + // ", avatar_normal='" + avatar_normal + '\'' + // ", avatar_large='" + avatar_large + '\'' + // '}'; // } // } // }
import com.sola.v2ex_android.model.LoginResult; import com.sola.v2ex_android.model.MyFollowing; import com.sola.v2ex_android.model.MyFollowingTopicDetial; import com.sola.v2ex_android.model.MyNode; import com.sola.v2ex_android.model.Replies; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
} return myfollowingList; } public static MyFollowingTopicDetial parseMyfollowingTopicDetial(String response){ MyFollowingTopicDetial topicDetial = new MyFollowingTopicDetial(); Document doc = Jsoup.parse(response); Element body = doc.body(); Element mainElement = body.getElementById("Main"); Elements itemElements = mainElement.getElementsByClass("cell"); Elements headerElements = mainElement.getElementsByClass("header"); Elements commentElements = mainElement.getElementsByClass("box"); for (Element headerElement : headerElements) { //头部用户信息 Elements avatarNode = headerElement.getElementsByTag("img"); Elements aNode = headerElement.getElementsByTag("a"); if (avatarNode != null) { String avatarString = avatarNode.attr("src"); if (avatarString.startsWith("//")) { topicDetial.avatar = "http:" + avatarString; topicDetial.userName = aNode.first().attr("href").substring(8); } } String[] s1 = headerElements.select(".gray").text().split(" · "); topicDetial.publishTime = s1[1]; topicDetial.title = headerElement.getElementsByTag("h1").text(); } topicDetial.content = mainElement.select(".markdown_body").html();
// Path: app/src/main/java/com/sola/v2ex_android/model/LoginResult.java // public class LoginResult { // // public LoginResult() { // // } // // public LoginResult(String userId, String userAvatar) { // this.userId = userId; // this.userAvatar = userAvatar; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // // public String getUserAvatar() { // return userAvatar; // } // // public void setUserAvatar(String userAvatar) { // this.userAvatar = userAvatar; // } // // public String userId; // public String userAvatar; // public String message; // // @Override // public String toString() { // return "LoginResult{" + // "userId='" + userId + '\'' + // ", userAvatar='" + userAvatar + '\'' + // ", message='" + message + '\'' + // '}'; // } // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyFollowing.java // public class MyFollowing { // // public String userName; // public String title; // public String userIconUrl; // public String nodeName; // public String commentCount; // public String topicId; // // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyFollowingTopicDetial.java // public class MyFollowingTopicDetial { // // public String avatar; // public String userName; // public String title; // public String content; // public String publishTime; // public int replies_count; // // public List<Replies> replies; // } // // Path: app/src/main/java/com/sola/v2ex_android/model/MyNode.java // public class MyNode { // // public String imgSrc; // public String nodeName; // public String followCount; // // @Override // public String toString() { // return "MyNode{" + // "imgSrc='" + imgSrc + '\'' + // ", nodeName='" + nodeName + '\'' + // ", collectNumber='" + followCount + '\'' + // '}'; // } // } // // Path: app/src/main/java/com/sola/v2ex_android/model/Replies.java // public class Replies { // // public int id; // public int thanks; // public String content; // public String content_rendered; // public String publishTime; // public MemberEntity member; // public long created; // public int last_modified; // // @Override // public String toString() { // return "Replies{" + // "id=" + id + // ", thanks=" + thanks + // ", content='" + content + '\'' + // ", content_rendered='" + content_rendered + '\'' + // ", member=" + member + // ", created=" + created + // ", last_modified=" + last_modified + // '}'; // } // // public static class MemberEntity { // public int id; // public String username; // public String tagline; // public String avatar_mini; // public String avatar_normal; // public String avatar_large; // // @Override // public String toString() { // return "MemberEntity{" + // "id=" + id + // ", username='" + username + '\'' + // ", tagline='" + tagline + '\'' + // ", avatar_mini='" + avatar_mini + '\'' + // ", avatar_normal='" + avatar_normal + '\'' + // ", avatar_large='" + avatar_large + '\'' + // '}'; // } // } // } // Path: app/src/main/java/com/sola/v2ex_android/util/JsoupUtil.java import com.sola.v2ex_android.model.LoginResult; import com.sola.v2ex_android.model.MyFollowing; import com.sola.v2ex_android.model.MyFollowingTopicDetial; import com.sola.v2ex_android.model.MyNode; import com.sola.v2ex_android.model.Replies; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.HashMap; import java.util.List; } return myfollowingList; } public static MyFollowingTopicDetial parseMyfollowingTopicDetial(String response){ MyFollowingTopicDetial topicDetial = new MyFollowingTopicDetial(); Document doc = Jsoup.parse(response); Element body = doc.body(); Element mainElement = body.getElementById("Main"); Elements itemElements = mainElement.getElementsByClass("cell"); Elements headerElements = mainElement.getElementsByClass("header"); Elements commentElements = mainElement.getElementsByClass("box"); for (Element headerElement : headerElements) { //头部用户信息 Elements avatarNode = headerElement.getElementsByTag("img"); Elements aNode = headerElement.getElementsByTag("a"); if (avatarNode != null) { String avatarString = avatarNode.attr("src"); if (avatarString.startsWith("//")) { topicDetial.avatar = "http:" + avatarString; topicDetial.userName = aNode.first().attr("href").substring(8); } } String[] s1 = headerElements.select(".gray").text().split(" · "); topicDetial.publishTime = s1[1]; topicDetial.title = headerElement.getElementsByTag("h1").text(); } topicDetial.content = mainElement.select(".markdown_body").html();
List<Replies> reploeList = new ArrayList<>();
sooola/V2EX-Android
app/src/androidTest/java/com/sola/v2ex_android/ExampleInstrumentedTest.java
// Path: app/src/main/java/com/sola/v2ex_android/util/LogUtil.java // public class LogUtil { // // public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化 // private static final String TAG = "zuqiukong"; // // public LogUtil() { // } // // // 下面四个是默认tag的函数 // public static void i(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(TAG, msg); // } // // public static void d(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(TAG, msg); // } // // public static void e(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(TAG, msg); // } // public static void dClass(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // { // String clazzName = new Throwable().getStackTrace()[1].getClassName(); // String[] clazzNames = clazzName.split("\\."); // Log.d(clazzNames[clazzNames.length - 1], msg); // } // } // // public static void v(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.v(TAG, msg); // } // // // 下面是传入自定义tag的函数 // public static void i(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(tag, msg); // } // // public static void d(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(tag, msg); // } // // public static void e(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(tag, msg); // } // // public static void v(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.v(tag, msg); // } // // public static void w(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.w(tag, msg); // } // // public static void wtf(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.wtf(tag, msg); // } // // }
import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import com.sola.v2ex_android.util.LogUtil; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals;
package com.sola.v2ex_android; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.sola.v2ex_android", appContext.getPackageName()); String url = "http://www.douban.com/accounts/login"; Connection.Response res = Jsoup.connect(url) .data("form_email","xxx@163.com","form_password","xxx") .method(Connection.Method.POST) .execute();
// Path: app/src/main/java/com/sola/v2ex_android/util/LogUtil.java // public class LogUtil { // // public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化 // private static final String TAG = "zuqiukong"; // // public LogUtil() { // } // // // 下面四个是默认tag的函数 // public static void i(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(TAG, msg); // } // // public static void d(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(TAG, msg); // } // // public static void e(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(TAG, msg); // } // public static void dClass(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // { // String clazzName = new Throwable().getStackTrace()[1].getClassName(); // String[] clazzNames = clazzName.split("\\."); // Log.d(clazzNames[clazzNames.length - 1], msg); // } // } // // public static void v(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.v(TAG, msg); // } // // // 下面是传入自定义tag的函数 // public static void i(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(tag, msg); // } // // public static void d(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(tag, msg); // } // // public static void e(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(tag, msg); // } // // public static void v(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.v(tag, msg); // } // // public static void w(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.w(tag, msg); // } // // public static void wtf(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.wtf(tag, msg); // } // // } // Path: app/src/androidTest/java/com/sola/v2ex_android/ExampleInstrumentedTest.java import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import com.sola.v2ex_android.util.LogUtil; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; package com.sola.v2ex_android; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.sola.v2ex_android", appContext.getPackageName()); String url = "http://www.douban.com/accounts/login"; Connection.Response res = Jsoup.connect(url) .data("form_email","xxx@163.com","form_password","xxx") .method(Connection.Method.POST) .execute();
LogUtil.d("ExampleInstrumentedTest",res.body());
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/util/TDevice.java
// Path: app/src/main/java/com/sola/v2ex_android/ui/base/application/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // // @Override // public void onCreate() { // super.onCreate(); // //获取Context // context = getApplicationContext(); // ToastUtil.init(this); // SharedPreferencesUtils.init(this); // V2exUser.init(); // } // // //返回 // public static Context getContextObject() { // return context; // } // // // // }
import android.annotation.TargetApi; import android.app.Activity; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.ClipboardManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.graphics.Point; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.PowerManager; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.DisplayMetrics; import android.view.Display; import android.view.View; import android.view.ViewConfiguration; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import com.sola.v2ex_android.ui.base.application.MyApplication; import java.io.File; import java.lang.reflect.Field; import java.text.NumberFormat; import java.util.List;
package com.sola.v2ex_android.util; @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public class TDevice { // 手机网络类型 public static final int NETTYPE_WIFI = 0x01; public static final int NETTYPE_CMWAP = 0x02; public static final int NETTYPE_CMNET = 0x03; public static boolean GTE_HC; public static boolean GTE_ICS; public static boolean PRE_HC; private static Boolean _hasBigScreen = null; private static Boolean _hasCamera = null; private static Boolean _isTablet = null; private static Integer _loadFactor = null; private static int _pageSize = -1; public static float displayDensity = 0.0F; static { GTE_ICS = Build.VERSION.SDK_INT >= 14; GTE_HC = Build.VERSION.SDK_INT >= 11; PRE_HC = Build.VERSION.SDK_INT < 11; } public TDevice() { } public static float dpToPixel(float dp) { return dp * (getDisplayMetrics().densityDpi / 160F); } public static int getDefaultLoadFactor() { if (_loadFactor == null) {
// Path: app/src/main/java/com/sola/v2ex_android/ui/base/application/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // // @Override // public void onCreate() { // super.onCreate(); // //获取Context // context = getApplicationContext(); // ToastUtil.init(this); // SharedPreferencesUtils.init(this); // V2exUser.init(); // } // // //返回 // public static Context getContextObject() { // return context; // } // // // // } // Path: app/src/main/java/com/sola/v2ex_android/util/TDevice.java import android.annotation.TargetApi; import android.app.Activity; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.ClipboardManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.graphics.Point; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.PowerManager; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.DisplayMetrics; import android.view.Display; import android.view.View; import android.view.ViewConfiguration; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import com.sola.v2ex_android.ui.base.application.MyApplication; import java.io.File; import java.lang.reflect.Field; import java.text.NumberFormat; import java.util.List; package com.sola.v2ex_android.util; @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public class TDevice { // 手机网络类型 public static final int NETTYPE_WIFI = 0x01; public static final int NETTYPE_CMWAP = 0x02; public static final int NETTYPE_CMNET = 0x03; public static boolean GTE_HC; public static boolean GTE_ICS; public static boolean PRE_HC; private static Boolean _hasBigScreen = null; private static Boolean _hasCamera = null; private static Boolean _isTablet = null; private static Integer _loadFactor = null; private static int _pageSize = -1; public static float displayDensity = 0.0F; static { GTE_ICS = Build.VERSION.SDK_INT >= 14; GTE_HC = Build.VERSION.SDK_INT >= 11; PRE_HC = Build.VERSION.SDK_INT < 11; } public TDevice() { } public static float dpToPixel(float dp) { return dp * (getDisplayMetrics().densityDpi / 160F); } public static int getDefaultLoadFactor() { if (_loadFactor == null) {
Integer integer = Integer.valueOf(0xf & MyApplication.getContextObject()
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/ui/base/view/BaseSpacesItemDecoration.java
// Path: app/src/main/java/com/sola/v2ex_android/ui/base/application/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // // @Override // public void onCreate() { // super.onCreate(); // //获取Context // context = getApplicationContext(); // ToastUtil.init(this); // SharedPreferencesUtils.init(this); // V2exUser.init(); // } // // //返回 // public static Context getContextObject() { // return context; // } // // // // } // // Path: app/src/main/java/com/sola/v2ex_android/util/DisplayUtil.java // public class DisplayUtil // { // /** // * 将px值转换为dip或dp值,保证尺寸大小不变 // * // * @param pxValue // * (DisplayMetrics类中属性density) // * @return // */ // public static int px2dip(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // /** // * 将dip或dp值转换为px值,保证尺寸大小不变 // * // * @param dipValue // * (DisplayMetrics类中属性density) // * @return // */ // public static int dip2px(Context context, float dipValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (dipValue * scale + 0.5f); // } // // /** // * 将px值转换为sp值,保证文字大小不变 // * // * @param pxValue // * (DisplayMetrics类中属性scaledDensity) // * @return // */ // public static int px2sp(Context context, float pxValue) { // final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; // return (int) (pxValue / fontScale + 0.5f); // } // // /** // * 将sp值转换为px值,保证文字大小不变 // * // * @param spValue // * (DisplayMetrics类中属性scaledDensity) // * @return // */ // public static int sp2px(Context context, float spValue) { // final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; // return (int) (spValue * fontScale + 0.5f); // } // }
import android.graphics.Rect; import android.os.Build; import android.view.View; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import com.sola.v2ex_android.ui.base.application.MyApplication; import com.sola.v2ex_android.util.DisplayUtil;
package com.sola.v2ex_android.ui.base.view; public class BaseSpacesItemDecoration extends RecyclerView.ItemDecoration { private int mSpace; public BaseSpacesItemDecoration() {
// Path: app/src/main/java/com/sola/v2ex_android/ui/base/application/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // // @Override // public void onCreate() { // super.onCreate(); // //获取Context // context = getApplicationContext(); // ToastUtil.init(this); // SharedPreferencesUtils.init(this); // V2exUser.init(); // } // // //返回 // public static Context getContextObject() { // return context; // } // // // // } // // Path: app/src/main/java/com/sola/v2ex_android/util/DisplayUtil.java // public class DisplayUtil // { // /** // * 将px值转换为dip或dp值,保证尺寸大小不变 // * // * @param pxValue // * (DisplayMetrics类中属性density) // * @return // */ // public static int px2dip(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // /** // * 将dip或dp值转换为px值,保证尺寸大小不变 // * // * @param dipValue // * (DisplayMetrics类中属性density) // * @return // */ // public static int dip2px(Context context, float dipValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (dipValue * scale + 0.5f); // } // // /** // * 将px值转换为sp值,保证文字大小不变 // * // * @param pxValue // * (DisplayMetrics类中属性scaledDensity) // * @return // */ // public static int px2sp(Context context, float pxValue) { // final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; // return (int) (pxValue / fontScale + 0.5f); // } // // /** // * 将sp值转换为px值,保证文字大小不变 // * // * @param spValue // * (DisplayMetrics类中属性scaledDensity) // * @return // */ // public static int sp2px(Context context, float spValue) { // final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; // return (int) (spValue * fontScale + 0.5f); // } // } // Path: app/src/main/java/com/sola/v2ex_android/ui/base/view/BaseSpacesItemDecoration.java import android.graphics.Rect; import android.os.Build; import android.view.View; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import com.sola.v2ex_android.ui.base.application.MyApplication; import com.sola.v2ex_android.util.DisplayUtil; package com.sola.v2ex_android.ui.base.view; public class BaseSpacesItemDecoration extends RecyclerView.ItemDecoration { private int mSpace; public BaseSpacesItemDecoration() {
this.mSpace = DisplayUtil.dip2px(MyApplication.getContextObject(),
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/ui/base/view/BaseSpacesItemDecoration.java
// Path: app/src/main/java/com/sola/v2ex_android/ui/base/application/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // // @Override // public void onCreate() { // super.onCreate(); // //获取Context // context = getApplicationContext(); // ToastUtil.init(this); // SharedPreferencesUtils.init(this); // V2exUser.init(); // } // // //返回 // public static Context getContextObject() { // return context; // } // // // // } // // Path: app/src/main/java/com/sola/v2ex_android/util/DisplayUtil.java // public class DisplayUtil // { // /** // * 将px值转换为dip或dp值,保证尺寸大小不变 // * // * @param pxValue // * (DisplayMetrics类中属性density) // * @return // */ // public static int px2dip(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // /** // * 将dip或dp值转换为px值,保证尺寸大小不变 // * // * @param dipValue // * (DisplayMetrics类中属性density) // * @return // */ // public static int dip2px(Context context, float dipValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (dipValue * scale + 0.5f); // } // // /** // * 将px值转换为sp值,保证文字大小不变 // * // * @param pxValue // * (DisplayMetrics类中属性scaledDensity) // * @return // */ // public static int px2sp(Context context, float pxValue) { // final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; // return (int) (pxValue / fontScale + 0.5f); // } // // /** // * 将sp值转换为px值,保证文字大小不变 // * // * @param spValue // * (DisplayMetrics类中属性scaledDensity) // * @return // */ // public static int sp2px(Context context, float spValue) { // final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; // return (int) (spValue * fontScale + 0.5f); // } // }
import android.graphics.Rect; import android.os.Build; import android.view.View; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import com.sola.v2ex_android.ui.base.application.MyApplication; import com.sola.v2ex_android.util.DisplayUtil;
package com.sola.v2ex_android.ui.base.view; public class BaseSpacesItemDecoration extends RecyclerView.ItemDecoration { private int mSpace; public BaseSpacesItemDecoration() {
// Path: app/src/main/java/com/sola/v2ex_android/ui/base/application/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // // @Override // public void onCreate() { // super.onCreate(); // //获取Context // context = getApplicationContext(); // ToastUtil.init(this); // SharedPreferencesUtils.init(this); // V2exUser.init(); // } // // //返回 // public static Context getContextObject() { // return context; // } // // // // } // // Path: app/src/main/java/com/sola/v2ex_android/util/DisplayUtil.java // public class DisplayUtil // { // /** // * 将px值转换为dip或dp值,保证尺寸大小不变 // * // * @param pxValue // * (DisplayMetrics类中属性density) // * @return // */ // public static int px2dip(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // /** // * 将dip或dp值转换为px值,保证尺寸大小不变 // * // * @param dipValue // * (DisplayMetrics类中属性density) // * @return // */ // public static int dip2px(Context context, float dipValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (dipValue * scale + 0.5f); // } // // /** // * 将px值转换为sp值,保证文字大小不变 // * // * @param pxValue // * (DisplayMetrics类中属性scaledDensity) // * @return // */ // public static int px2sp(Context context, float pxValue) { // final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; // return (int) (pxValue / fontScale + 0.5f); // } // // /** // * 将sp值转换为px值,保证文字大小不变 // * // * @param spValue // * (DisplayMetrics类中属性scaledDensity) // * @return // */ // public static int sp2px(Context context, float spValue) { // final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; // return (int) (spValue * fontScale + 0.5f); // } // } // Path: app/src/main/java/com/sola/v2ex_android/ui/base/view/BaseSpacesItemDecoration.java import android.graphics.Rect; import android.os.Build; import android.view.View; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import com.sola.v2ex_android.ui.base.application.MyApplication; import com.sola.v2ex_android.util.DisplayUtil; package com.sola.v2ex_android.ui.base.view; public class BaseSpacesItemDecoration extends RecyclerView.ItemDecoration { private int mSpace; public BaseSpacesItemDecoration() {
this.mSpace = DisplayUtil.dip2px(MyApplication.getContextObject(),
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/util/SharedPreferencesUtils.java
// Path: app/src/main/java/com/sola/v2ex_android/ui/base/application/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // // @Override // public void onCreate() { // super.onCreate(); // //获取Context // context = getApplicationContext(); // ToastUtil.init(this); // SharedPreferencesUtils.init(this); // V2exUser.init(); // } // // //返回 // public static Context getContextObject() { // return context; // } // // // // }
import android.content.Context; import android.content.SharedPreferences; import com.sola.v2ex_android.ui.base.application.MyApplication;
package com.sola.v2ex_android.util; /** * SharedPreferences的一个工具类,调用setParam就能保存String, Integer, Boolean, Float, Long类型的参数 * 同样调用getParam就能获取到保存在手机里面的数据 * @author * */ public class SharedPreferencesUtils { private static Context mContext; /** * 在MyApplication里初始化,避免再重复传Context * @param context */ public static void init(Context context) { mContext = context; } /** * 获取偏好文件 * @param spName */ public static SharedPreferences getSharedPreferences(String spName) { return mContext.getSharedPreferences(spName,Context.MODE_PRIVATE); } /** * 保存在手机里面的文件名 */ public static final String FILE_NAME = "data"; public static void setParam(String key, Object object) {
// Path: app/src/main/java/com/sola/v2ex_android/ui/base/application/MyApplication.java // public class MyApplication extends Application { // // private static Context context; // // @Override // public void onCreate() { // super.onCreate(); // //获取Context // context = getApplicationContext(); // ToastUtil.init(this); // SharedPreferencesUtils.init(this); // V2exUser.init(); // } // // //返回 // public static Context getContextObject() { // return context; // } // // // // } // Path: app/src/main/java/com/sola/v2ex_android/util/SharedPreferencesUtils.java import android.content.Context; import android.content.SharedPreferences; import com.sola.v2ex_android.ui.base.application.MyApplication; package com.sola.v2ex_android.util; /** * SharedPreferences的一个工具类,调用setParam就能保存String, Integer, Boolean, Float, Long类型的参数 * 同样调用getParam就能获取到保存在手机里面的数据 * @author * */ public class SharedPreferencesUtils { private static Context mContext; /** * 在MyApplication里初始化,避免再重复传Context * @param context */ public static void init(Context context) { mContext = context; } /** * 获取偏好文件 * @param spName */ public static SharedPreferences getSharedPreferences(String spName) { return mContext.getSharedPreferences(spName,Context.MODE_PRIVATE); } /** * 保存在手机里面的文件名 */ public static final String FILE_NAME = "data"; public static void setParam(String key, Object object) {
setParam(MyApplication.getContextObject(), key, object);
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/ui/widget/PickerView.java
// Path: app/src/main/java/com/sola/v2ex_android/util/LogUtil.java // public class LogUtil { // // public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化 // private static final String TAG = "zuqiukong"; // // public LogUtil() { // } // // // 下面四个是默认tag的函数 // public static void i(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(TAG, msg); // } // // public static void d(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(TAG, msg); // } // // public static void e(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(TAG, msg); // } // public static void dClass(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // { // String clazzName = new Throwable().getStackTrace()[1].getClassName(); // String[] clazzNames = clazzName.split("\\."); // Log.d(clazzNames[clazzNames.length - 1], msg); // } // } // // public static void v(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.v(TAG, msg); // } // // // 下面是传入自定义tag的函数 // public static void i(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(tag, msg); // } // // public static void d(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(tag, msg); // } // // public static void e(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(tag, msg); // } // // public static void v(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.v(tag, msg); // } // // public static void w(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.w(tag, msg); // } // // public static void wtf(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.wtf(tag, msg); // } // // } // // Path: app/src/main/java/com/sola/v2ex_android/util/ValidateUtil.java // public class ValidateUtil { // /** // * 是否为空 // * // * @return // */ // public static boolean isEmpty(Object o) { // if (null == o) // return true; // // if (o instanceof String) // return "".equals(o) ? true : false; // // if (o instanceof List) // return ((List) o).size() == 0 ? true : false; // // if (o instanceof Map) // return ((Map) o).size() == 0 ? true : false; // if (o instanceof String[]) // return ((String[]) o).length == 0 ? true : false; // if (o instanceof int[]) // return ((int[]) o).length == 0 ? true : false; // if (o instanceof Set) // return ((Set) o).size() == 0 ? true : false; // // return false; // } // // /** // * 是否不为空 // * // * @return // */ // public static boolean isNotEmpty(Object o) { // return !isEmpty(o); // } // // // // }
import android.content.Context; import android.graphics.Color; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.sola.v2ex_android.R; import com.sola.v2ex_android.util.LogUtil; import com.sola.v2ex_android.util.ValidateUtil; import java.util.List;
package com.sola.v2ex_android.ui.widget; /** * Created by wei on 2016/12/1. * */ public class PickerView extends RecyclerView { private PickerAdapter mAdapter; private int mHight; private int mItemHight; public PickerView(Context context) { super(context); initView(); } public PickerView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); initView(); } public PickerView(Context context, @Nullable AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initView(); } private void initView() { LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext()); this.setLayoutManager(layoutManager); mAdapter = new PickerAdapter(this.getContext()); this.setAdapter(mAdapter); this.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (newState == RecyclerView.SCROLL_STATE_IDLE) { // mAdapter.highlightItem(); //将位置移动到中间位置
// Path: app/src/main/java/com/sola/v2ex_android/util/LogUtil.java // public class LogUtil { // // public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化 // private static final String TAG = "zuqiukong"; // // public LogUtil() { // } // // // 下面四个是默认tag的函数 // public static void i(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(TAG, msg); // } // // public static void d(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(TAG, msg); // } // // public static void e(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(TAG, msg); // } // public static void dClass(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // { // String clazzName = new Throwable().getStackTrace()[1].getClassName(); // String[] clazzNames = clazzName.split("\\."); // Log.d(clazzNames[clazzNames.length - 1], msg); // } // } // // public static void v(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.v(TAG, msg); // } // // // 下面是传入自定义tag的函数 // public static void i(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(tag, msg); // } // // public static void d(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(tag, msg); // } // // public static void e(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(tag, msg); // } // // public static void v(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.v(tag, msg); // } // // public static void w(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.w(tag, msg); // } // // public static void wtf(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.wtf(tag, msg); // } // // } // // Path: app/src/main/java/com/sola/v2ex_android/util/ValidateUtil.java // public class ValidateUtil { // /** // * 是否为空 // * // * @return // */ // public static boolean isEmpty(Object o) { // if (null == o) // return true; // // if (o instanceof String) // return "".equals(o) ? true : false; // // if (o instanceof List) // return ((List) o).size() == 0 ? true : false; // // if (o instanceof Map) // return ((Map) o).size() == 0 ? true : false; // if (o instanceof String[]) // return ((String[]) o).length == 0 ? true : false; // if (o instanceof int[]) // return ((int[]) o).length == 0 ? true : false; // if (o instanceof Set) // return ((Set) o).size() == 0 ? true : false; // // return false; // } // // /** // * 是否不为空 // * // * @return // */ // public static boolean isNotEmpty(Object o) { // return !isEmpty(o); // } // // // // } // Path: app/src/main/java/com/sola/v2ex_android/ui/widget/PickerView.java import android.content.Context; import android.graphics.Color; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.sola.v2ex_android.R; import com.sola.v2ex_android.util.LogUtil; import com.sola.v2ex_android.util.ValidateUtil; import java.util.List; package com.sola.v2ex_android.ui.widget; /** * Created by wei on 2016/12/1. * */ public class PickerView extends RecyclerView { private PickerAdapter mAdapter; private int mHight; private int mItemHight; public PickerView(Context context) { super(context); initView(); } public PickerView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); initView(); } public PickerView(Context context, @Nullable AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initView(); } private void initView() { LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext()); this.setLayoutManager(layoutManager); mAdapter = new PickerAdapter(this.getContext()); this.setAdapter(mAdapter); this.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (newState == RecyclerView.SCROLL_STATE_IDLE) { // mAdapter.highlightItem(); //将位置移动到中间位置
LogUtil.d("PickerView", " getScollYDistance() " + getScollYDistance() );
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/ui/widget/PickerView.java
// Path: app/src/main/java/com/sola/v2ex_android/util/LogUtil.java // public class LogUtil { // // public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化 // private static final String TAG = "zuqiukong"; // // public LogUtil() { // } // // // 下面四个是默认tag的函数 // public static void i(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(TAG, msg); // } // // public static void d(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(TAG, msg); // } // // public static void e(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(TAG, msg); // } // public static void dClass(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // { // String clazzName = new Throwable().getStackTrace()[1].getClassName(); // String[] clazzNames = clazzName.split("\\."); // Log.d(clazzNames[clazzNames.length - 1], msg); // } // } // // public static void v(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.v(TAG, msg); // } // // // 下面是传入自定义tag的函数 // public static void i(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(tag, msg); // } // // public static void d(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(tag, msg); // } // // public static void e(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(tag, msg); // } // // public static void v(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.v(tag, msg); // } // // public static void w(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.w(tag, msg); // } // // public static void wtf(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.wtf(tag, msg); // } // // } // // Path: app/src/main/java/com/sola/v2ex_android/util/ValidateUtil.java // public class ValidateUtil { // /** // * 是否为空 // * // * @return // */ // public static boolean isEmpty(Object o) { // if (null == o) // return true; // // if (o instanceof String) // return "".equals(o) ? true : false; // // if (o instanceof List) // return ((List) o).size() == 0 ? true : false; // // if (o instanceof Map) // return ((Map) o).size() == 0 ? true : false; // if (o instanceof String[]) // return ((String[]) o).length == 0 ? true : false; // if (o instanceof int[]) // return ((int[]) o).length == 0 ? true : false; // if (o instanceof Set) // return ((Set) o).size() == 0 ? true : false; // // return false; // } // // /** // * 是否不为空 // * // * @return // */ // public static boolean isNotEmpty(Object o) { // return !isEmpty(o); // } // // // // }
import android.content.Context; import android.graphics.Color; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.sola.v2ex_android.R; import com.sola.v2ex_android.util.LogUtil; import com.sola.v2ex_android.util.ValidateUtil; import java.util.List;
holder.mTextView.setBackground(null); } } @Override public int getItemCount() { // return mData.size(); return Integer.MAX_VALUE; } public float getItemWidth() { return mViewHeight / ITEM_NUM; } // 判断是否是高亮 public boolean isSelected(int position) { return mHighlight == position; } // 高亮中心, 更新前后位置 public void highlightItem(int position) { mHighlight = position; // int offset = ITEM_NUM / 2; // for (int i = position - offset; i <= position + offset; ++i) // notifyItemChanged(i); notifyDataSetChanged(); } public void appendItems(List<String> items) {
// Path: app/src/main/java/com/sola/v2ex_android/util/LogUtil.java // public class LogUtil { // // public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化 // private static final String TAG = "zuqiukong"; // // public LogUtil() { // } // // // 下面四个是默认tag的函数 // public static void i(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(TAG, msg); // } // // public static void d(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(TAG, msg); // } // // public static void e(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(TAG, msg); // } // public static void dClass(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // { // String clazzName = new Throwable().getStackTrace()[1].getClassName(); // String[] clazzNames = clazzName.split("\\."); // Log.d(clazzNames[clazzNames.length - 1], msg); // } // } // // public static void v(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.v(TAG, msg); // } // // // 下面是传入自定义tag的函数 // public static void i(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(tag, msg); // } // // public static void d(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(tag, msg); // } // // public static void e(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(tag, msg); // } // // public static void v(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.v(tag, msg); // } // // public static void w(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.w(tag, msg); // } // // public static void wtf(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.wtf(tag, msg); // } // // } // // Path: app/src/main/java/com/sola/v2ex_android/util/ValidateUtil.java // public class ValidateUtil { // /** // * 是否为空 // * // * @return // */ // public static boolean isEmpty(Object o) { // if (null == o) // return true; // // if (o instanceof String) // return "".equals(o) ? true : false; // // if (o instanceof List) // return ((List) o).size() == 0 ? true : false; // // if (o instanceof Map) // return ((Map) o).size() == 0 ? true : false; // if (o instanceof String[]) // return ((String[]) o).length == 0 ? true : false; // if (o instanceof int[]) // return ((int[]) o).length == 0 ? true : false; // if (o instanceof Set) // return ((Set) o).size() == 0 ? true : false; // // return false; // } // // /** // * 是否不为空 // * // * @return // */ // public static boolean isNotEmpty(Object o) { // return !isEmpty(o); // } // // // // } // Path: app/src/main/java/com/sola/v2ex_android/ui/widget/PickerView.java import android.content.Context; import android.graphics.Color; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.sola.v2ex_android.R; import com.sola.v2ex_android.util.LogUtil; import com.sola.v2ex_android.util.ValidateUtil; import java.util.List; holder.mTextView.setBackground(null); } } @Override public int getItemCount() { // return mData.size(); return Integer.MAX_VALUE; } public float getItemWidth() { return mViewHeight / ITEM_NUM; } // 判断是否是高亮 public boolean isSelected(int position) { return mHighlight == position; } // 高亮中心, 更新前后位置 public void highlightItem(int position) { mHighlight = position; // int offset = ITEM_NUM / 2; // for (int i = position - offset; i <= position + offset; ++i) // notifyItemChanged(i); notifyDataSetChanged(); } public void appendItems(List<String> items) {
if(ValidateUtil.isNotEmpty(items))
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/network/V2exService.java
// Path: app/src/main/java/com/sola/v2ex_android/network/api/V2EXApi.java // public interface V2EXApi { // // @GET("topics/hot.json") //每天热门 // Observable<List<Topics>> getTopicHot(); // // @GET("topics/latest.json") //每天最新 // Observable<List<Topics>> getTopicLatest(); // // @GET("nodes/show.json") //节点详情 // Observable<NodeInfo> getNodeDetial(@Query("name") String name); // // @GET("nodes/all.json") //获取所有节点 // Observable<List<NodeInfo>> getAllNode(); // // @GET("topics/show.json") //根据节点名获取所有帖子 // Observable<List<Topics>> getTopicsByNodeName(@Query("node_name") String node_name); // // @GET("replies/show.json") //帖子回复 // Observable<List<Replies>> getReplise(@Query("topic_id") int topic_id); // // @GET("members/show.json") //获取用户详情 // Observable<UserInfo> getUserInfo(@Query("username") String username); // // @GET("topics/show.json") //用户发的帖子 // Observable<List<Topics>> getTopicsByUserName(@Query("username") String username); // } // // Path: app/src/main/java/com/sola/v2ex_android/util/Constants.java // public class Constants { // // public static String V2EX_URL = "https://www.v2ex.com/api/"; // // public static String V2EX_BASE_URL = "https://www.v2ex.com/"; // // // public static String makeUserLogo(String url){ // return "http:" + url; // } // // }
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sola.v2ex_android.network.api.V2EXApi; import com.sola.v2ex_android.util.Constants; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory;
package com.sola.v2ex_android.network; /** * Created by wei on 2016/11/14. */ public class V2exService { private static V2exService mInstance; private Gson mGson; private OkHttpClient mClient;
// Path: app/src/main/java/com/sola/v2ex_android/network/api/V2EXApi.java // public interface V2EXApi { // // @GET("topics/hot.json") //每天热门 // Observable<List<Topics>> getTopicHot(); // // @GET("topics/latest.json") //每天最新 // Observable<List<Topics>> getTopicLatest(); // // @GET("nodes/show.json") //节点详情 // Observable<NodeInfo> getNodeDetial(@Query("name") String name); // // @GET("nodes/all.json") //获取所有节点 // Observable<List<NodeInfo>> getAllNode(); // // @GET("topics/show.json") //根据节点名获取所有帖子 // Observable<List<Topics>> getTopicsByNodeName(@Query("node_name") String node_name); // // @GET("replies/show.json") //帖子回复 // Observable<List<Replies>> getReplise(@Query("topic_id") int topic_id); // // @GET("members/show.json") //获取用户详情 // Observable<UserInfo> getUserInfo(@Query("username") String username); // // @GET("topics/show.json") //用户发的帖子 // Observable<List<Topics>> getTopicsByUserName(@Query("username") String username); // } // // Path: app/src/main/java/com/sola/v2ex_android/util/Constants.java // public class Constants { // // public static String V2EX_URL = "https://www.v2ex.com/api/"; // // public static String V2EX_BASE_URL = "https://www.v2ex.com/"; // // // public static String makeUserLogo(String url){ // return "http:" + url; // } // // } // Path: app/src/main/java/com/sola/v2ex_android/network/V2exService.java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sola.v2ex_android.network.api.V2EXApi; import com.sola.v2ex_android.util.Constants; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; package com.sola.v2ex_android.network; /** * Created by wei on 2016/11/14. */ public class V2exService { private static V2exService mInstance; private Gson mGson; private OkHttpClient mClient;
private V2EXApi mV2exApi;
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/network/V2exService.java
// Path: app/src/main/java/com/sola/v2ex_android/network/api/V2EXApi.java // public interface V2EXApi { // // @GET("topics/hot.json") //每天热门 // Observable<List<Topics>> getTopicHot(); // // @GET("topics/latest.json") //每天最新 // Observable<List<Topics>> getTopicLatest(); // // @GET("nodes/show.json") //节点详情 // Observable<NodeInfo> getNodeDetial(@Query("name") String name); // // @GET("nodes/all.json") //获取所有节点 // Observable<List<NodeInfo>> getAllNode(); // // @GET("topics/show.json") //根据节点名获取所有帖子 // Observable<List<Topics>> getTopicsByNodeName(@Query("node_name") String node_name); // // @GET("replies/show.json") //帖子回复 // Observable<List<Replies>> getReplise(@Query("topic_id") int topic_id); // // @GET("members/show.json") //获取用户详情 // Observable<UserInfo> getUserInfo(@Query("username") String username); // // @GET("topics/show.json") //用户发的帖子 // Observable<List<Topics>> getTopicsByUserName(@Query("username") String username); // } // // Path: app/src/main/java/com/sola/v2ex_android/util/Constants.java // public class Constants { // // public static String V2EX_URL = "https://www.v2ex.com/api/"; // // public static String V2EX_BASE_URL = "https://www.v2ex.com/"; // // // public static String makeUserLogo(String url){ // return "http:" + url; // } // // }
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sola.v2ex_android.network.api.V2EXApi; import com.sola.v2ex_android.util.Constants; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory;
package com.sola.v2ex_android.network; /** * Created by wei on 2016/11/14. */ public class V2exService { private static V2exService mInstance; private Gson mGson; private OkHttpClient mClient; private V2EXApi mV2exApi; public static V2exService getInstance() { if (mInstance == null) { mInstance = new V2exService(); } return mInstance; } public V2exService(){ HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); mClient = new OkHttpClient.Builder() .readTimeout(12, TimeUnit.SECONDS) .addInterceptor(loggingInterceptor) .build(); mGson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .serializeNulls() .create(); } public V2EXApi getV2exApi() { if (mV2exApi == null) { Retrofit retrofit = new Retrofit.Builder()
// Path: app/src/main/java/com/sola/v2ex_android/network/api/V2EXApi.java // public interface V2EXApi { // // @GET("topics/hot.json") //每天热门 // Observable<List<Topics>> getTopicHot(); // // @GET("topics/latest.json") //每天最新 // Observable<List<Topics>> getTopicLatest(); // // @GET("nodes/show.json") //节点详情 // Observable<NodeInfo> getNodeDetial(@Query("name") String name); // // @GET("nodes/all.json") //获取所有节点 // Observable<List<NodeInfo>> getAllNode(); // // @GET("topics/show.json") //根据节点名获取所有帖子 // Observable<List<Topics>> getTopicsByNodeName(@Query("node_name") String node_name); // // @GET("replies/show.json") //帖子回复 // Observable<List<Replies>> getReplise(@Query("topic_id") int topic_id); // // @GET("members/show.json") //获取用户详情 // Observable<UserInfo> getUserInfo(@Query("username") String username); // // @GET("topics/show.json") //用户发的帖子 // Observable<List<Topics>> getTopicsByUserName(@Query("username") String username); // } // // Path: app/src/main/java/com/sola/v2ex_android/util/Constants.java // public class Constants { // // public static String V2EX_URL = "https://www.v2ex.com/api/"; // // public static String V2EX_BASE_URL = "https://www.v2ex.com/"; // // // public static String makeUserLogo(String url){ // return "http:" + url; // } // // } // Path: app/src/main/java/com/sola/v2ex_android/network/V2exService.java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sola.v2ex_android.network.api.V2EXApi; import com.sola.v2ex_android.util.Constants; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; package com.sola.v2ex_android.network; /** * Created by wei on 2016/11/14. */ public class V2exService { private static V2exService mInstance; private Gson mGson; private OkHttpClient mClient; private V2EXApi mV2exApi; public static V2exService getInstance() { if (mInstance == null) { mInstance = new V2exService(); } return mInstance; } public V2exService(){ HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); mClient = new OkHttpClient.Builder() .readTimeout(12, TimeUnit.SECONDS) .addInterceptor(loggingInterceptor) .build(); mGson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .serializeNulls() .create(); } public V2EXApi getV2exApi() { if (mV2exApi == null) { Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.V2EX_URL)
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/ui/base/BaseSwipeRefreshFragment.java
// Path: app/src/main/java/com/sola/v2ex_android/util/LogUtil.java // public class LogUtil { // // public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化 // private static final String TAG = "zuqiukong"; // // public LogUtil() { // } // // // 下面四个是默认tag的函数 // public static void i(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(TAG, msg); // } // // public static void d(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(TAG, msg); // } // // public static void e(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(TAG, msg); // } // public static void dClass(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // { // String clazzName = new Throwable().getStackTrace()[1].getClassName(); // String[] clazzNames = clazzName.split("\\."); // Log.d(clazzNames[clazzNames.length - 1], msg); // } // } // // public static void v(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.v(TAG, msg); // } // // // 下面是传入自定义tag的函数 // public static void i(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(tag, msg); // } // // public static void d(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(tag, msg); // } // // public static void e(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(tag, msg); // } // // public static void v(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.v(tag, msg); // } // // public static void w(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.w(tag, msg); // } // // public static void wtf(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.wtf(tag, msg); // } // // }
import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.View; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.sola.v2ex_android.R; import com.sola.v2ex_android.util.LogUtil; import java.lang.ref.WeakReference;
package com.sola.v2ex_android.ui.base; /** * Created by wei on 2016/10/31. */ public abstract class BaseSwipeRefreshFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener { SwipeRefreshLayout mSwipeRefreshLayout; public Handler mHandle; private View mRootView; @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Override public void initViews(View view){ mHandle = new MyHandler(getActivity()); mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swiperefreshlayout); if (null != mSwipeRefreshLayout) { mSwipeRefreshLayout.setOnRefreshListener(this); mSwipeRefreshLayout.setColorSchemeResources( android.R.color.holo_green_light, android.R.color.holo_blue_bright, android.R.color.holo_orange_light, android.R.color.holo_red_light); } } public void setSwipeRefreshEnabled(boolean isEnable){ if (null != mSwipeRefreshLayout) mSwipeRefreshLayout.setEnabled(isEnable); } public void setSwipeRefreshLayoutRefresh(boolean refresh){
// Path: app/src/main/java/com/sola/v2ex_android/util/LogUtil.java // public class LogUtil { // // public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化 // private static final String TAG = "zuqiukong"; // // public LogUtil() { // } // // // 下面四个是默认tag的函数 // public static void i(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(TAG, msg); // } // // public static void d(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(TAG, msg); // } // // public static void e(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(TAG, msg); // } // public static void dClass(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // { // String clazzName = new Throwable().getStackTrace()[1].getClassName(); // String[] clazzNames = clazzName.split("\\."); // Log.d(clazzNames[clazzNames.length - 1], msg); // } // } // // public static void v(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.v(TAG, msg); // } // // // 下面是传入自定义tag的函数 // public static void i(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(tag, msg); // } // // public static void d(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(tag, msg); // } // // public static void e(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(tag, msg); // } // // public static void v(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.v(tag, msg); // } // // public static void w(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.w(tag, msg); // } // // public static void wtf(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.wtf(tag, msg); // } // // } // Path: app/src/main/java/com/sola/v2ex_android/ui/base/BaseSwipeRefreshFragment.java import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.View; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.sola.v2ex_android.R; import com.sola.v2ex_android.util.LogUtil; import java.lang.ref.WeakReference; package com.sola.v2ex_android.ui.base; /** * Created by wei on 2016/10/31. */ public abstract class BaseSwipeRefreshFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener { SwipeRefreshLayout mSwipeRefreshLayout; public Handler mHandle; private View mRootView; @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Override public void initViews(View view){ mHandle = new MyHandler(getActivity()); mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swiperefreshlayout); if (null != mSwipeRefreshLayout) { mSwipeRefreshLayout.setOnRefreshListener(this); mSwipeRefreshLayout.setColorSchemeResources( android.R.color.holo_green_light, android.R.color.holo_blue_bright, android.R.color.holo_orange_light, android.R.color.holo_red_light); } } public void setSwipeRefreshEnabled(boolean isEnable){ if (null != mSwipeRefreshLayout) mSwipeRefreshLayout.setEnabled(isEnable); } public void setSwipeRefreshLayoutRefresh(boolean refresh){
LogUtil.d("BaseSwipeRefreshFragment","setSwipeRefreshLayoutRefresh");
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/ui/base/adapter/BaseRecyclerAdapter.java
// Path: app/src/main/java/com/sola/v2ex_android/ui/base/callback/OnItemClickListener.java // public interface OnItemClickListener { // void onItemClick(View view, int position); // } // // Path: app/src/main/java/com/sola/v2ex_android/util/ValidateUtil.java // public class ValidateUtil { // /** // * 是否为空 // * // * @return // */ // public static boolean isEmpty(Object o) { // if (null == o) // return true; // // if (o instanceof String) // return "".equals(o) ? true : false; // // if (o instanceof List) // return ((List) o).size() == 0 ? true : false; // // if (o instanceof Map) // return ((Map) o).size() == 0 ? true : false; // if (o instanceof String[]) // return ((String[]) o).length == 0 ? true : false; // if (o instanceof int[]) // return ((int[]) o).length == 0 ? true : false; // if (o instanceof Set) // return ((Set) o).size() == 0 ? true : false; // // return false; // } // // /** // * 是否不为空 // * // * @return // */ // public static boolean isNotEmpty(Object o) { // return !isEmpty(o); // } // // // // }
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.recyclerview.widget.RecyclerView; import com.sola.v2ex_android.ui.base.callback.OnItemClickListener; import com.sola.v2ex_android.util.ValidateUtil; import java.util.List;
package com.sola.v2ex_android.ui.base.adapter; public abstract class BaseRecyclerAdapter<T> extends RecyclerView.Adapter<BaseRecyclerViewHolder> { public static final int TYPE_HEADER = 1; public static final int TYPE_ITEM = 2; protected List<T> mData; protected Context mContext; protected LayoutInflater mInflater;
// Path: app/src/main/java/com/sola/v2ex_android/ui/base/callback/OnItemClickListener.java // public interface OnItemClickListener { // void onItemClick(View view, int position); // } // // Path: app/src/main/java/com/sola/v2ex_android/util/ValidateUtil.java // public class ValidateUtil { // /** // * 是否为空 // * // * @return // */ // public static boolean isEmpty(Object o) { // if (null == o) // return true; // // if (o instanceof String) // return "".equals(o) ? true : false; // // if (o instanceof List) // return ((List) o).size() == 0 ? true : false; // // if (o instanceof Map) // return ((Map) o).size() == 0 ? true : false; // if (o instanceof String[]) // return ((String[]) o).length == 0 ? true : false; // if (o instanceof int[]) // return ((int[]) o).length == 0 ? true : false; // if (o instanceof Set) // return ((Set) o).size() == 0 ? true : false; // // return false; // } // // /** // * 是否不为空 // * // * @return // */ // public static boolean isNotEmpty(Object o) { // return !isEmpty(o); // } // // // // } // Path: app/src/main/java/com/sola/v2ex_android/ui/base/adapter/BaseRecyclerAdapter.java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.recyclerview.widget.RecyclerView; import com.sola.v2ex_android.ui.base.callback.OnItemClickListener; import com.sola.v2ex_android.util.ValidateUtil; import java.util.List; package com.sola.v2ex_android.ui.base.adapter; public abstract class BaseRecyclerAdapter<T> extends RecyclerView.Adapter<BaseRecyclerViewHolder> { public static final int TYPE_HEADER = 1; public static final int TYPE_ITEM = 2; protected List<T> mData; protected Context mContext; protected LayoutInflater mInflater;
protected OnItemClickListener mClickListener;
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/ui/base/adapter/BaseRecyclerAdapter.java
// Path: app/src/main/java/com/sola/v2ex_android/ui/base/callback/OnItemClickListener.java // public interface OnItemClickListener { // void onItemClick(View view, int position); // } // // Path: app/src/main/java/com/sola/v2ex_android/util/ValidateUtil.java // public class ValidateUtil { // /** // * 是否为空 // * // * @return // */ // public static boolean isEmpty(Object o) { // if (null == o) // return true; // // if (o instanceof String) // return "".equals(o) ? true : false; // // if (o instanceof List) // return ((List) o).size() == 0 ? true : false; // // if (o instanceof Map) // return ((Map) o).size() == 0 ? true : false; // if (o instanceof String[]) // return ((String[]) o).length == 0 ? true : false; // if (o instanceof int[]) // return ((int[]) o).length == 0 ? true : false; // if (o instanceof Set) // return ((Set) o).size() == 0 ? true : false; // // return false; // } // // /** // * 是否不为空 // * // * @return // */ // public static boolean isNotEmpty(Object o) { // return !isEmpty(o); // } // // // // }
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.recyclerview.widget.RecyclerView; import com.sola.v2ex_android.ui.base.callback.OnItemClickListener; import com.sola.v2ex_android.util.ValidateUtil; import java.util.List;
private int mTypeCount = 1; public BaseRecyclerAdapter(Context context) { mContext = context; mInflater = LayoutInflater.from(context); } @Override public BaseRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final BaseRecyclerViewHolder holder = new BaseRecyclerViewHolder(mContext, mInflater.inflate(getItemLayoutId(viewType), parent, false)); if (mClickListener != null) { holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mClickListener.onItemClick(v, holder.getLayoutPosition()); } }); } return holder; } @Override public void onBindViewHolder(BaseRecyclerViewHolder holder, int position) { bindData(holder, position, mData.get(position)); } public void cleanData() {
// Path: app/src/main/java/com/sola/v2ex_android/ui/base/callback/OnItemClickListener.java // public interface OnItemClickListener { // void onItemClick(View view, int position); // } // // Path: app/src/main/java/com/sola/v2ex_android/util/ValidateUtil.java // public class ValidateUtil { // /** // * 是否为空 // * // * @return // */ // public static boolean isEmpty(Object o) { // if (null == o) // return true; // // if (o instanceof String) // return "".equals(o) ? true : false; // // if (o instanceof List) // return ((List) o).size() == 0 ? true : false; // // if (o instanceof Map) // return ((Map) o).size() == 0 ? true : false; // if (o instanceof String[]) // return ((String[]) o).length == 0 ? true : false; // if (o instanceof int[]) // return ((int[]) o).length == 0 ? true : false; // if (o instanceof Set) // return ((Set) o).size() == 0 ? true : false; // // return false; // } // // /** // * 是否不为空 // * // * @return // */ // public static boolean isNotEmpty(Object o) { // return !isEmpty(o); // } // // // // } // Path: app/src/main/java/com/sola/v2ex_android/ui/base/adapter/BaseRecyclerAdapter.java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.recyclerview.widget.RecyclerView; import com.sola.v2ex_android.ui.base.callback.OnItemClickListener; import com.sola.v2ex_android.util.ValidateUtil; import java.util.List; private int mTypeCount = 1; public BaseRecyclerAdapter(Context context) { mContext = context; mInflater = LayoutInflater.from(context); } @Override public BaseRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final BaseRecyclerViewHolder holder = new BaseRecyclerViewHolder(mContext, mInflater.inflate(getItemLayoutId(viewType), parent, false)); if (mClickListener != null) { holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mClickListener.onItemClick(v, holder.getLayoutPosition()); } }); } return holder; } @Override public void onBindViewHolder(BaseRecyclerViewHolder holder, int position) { bindData(holder, position, mData.get(position)); } public void cleanData() {
if(ValidateUtil.isNotEmpty(mData))
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/ui/MainContentFragment.java
// Path: app/src/main/java/com/sola/v2ex_android/ui/adapter/MainPageAdapter.java // public class MainPageAdapter extends FragmentPagerAdapter { // // private final String[] titles = { "主题", "节点"}; // // public MainPageAdapter(FragmentManager fm) { // super(fm); // } // // @Override // public Fragment getItem(int position) { // if (0 == position){ // return NewestTopicsFragment.newInstance(); // }else { // return NodeFragment.newInstance(); // } // } // // @Override // public CharSequence getPageTitle(int position) { // return titles[position]; // } // // @Override // public int getCount() { // return titles.length; // } // } // // Path: app/src/main/java/com/sola/v2ex_android/ui/base/BaseFragment.java // public abstract class BaseFragment extends Fragment { // // private CompositeSubscription mCompositeSubscription; // Unbinder unbind; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(getLayoutId(), container, false); // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // unbind = ButterKnife.bind(this, view); // initViews(view); // loadData(); // } // // // // public CompositeSubscription getCompositeSubscription() { // if (this.mCompositeSubscription == null) { // this.mCompositeSubscription = new CompositeSubscription(); // } // // return this.mCompositeSubscription; // } // // // public void addSubscription(Subscription s) { // if (this.mCompositeSubscription == null) { // this.mCompositeSubscription = new CompositeSubscription(); // } // // this.mCompositeSubscription.add(s); // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // unbind.unbind(); // if (this.mCompositeSubscription != null) { // this.mCompositeSubscription.unsubscribe(); // } // } // // protected abstract int getLayoutId(); // // protected abstract void initViews(View view); // // protected abstract void loadData(); // // // }
import android.view.View; import androidx.viewpager.widget.ViewPager; import com.google.android.material.tabs.TabLayout; import com.sola.v2ex_android.R; import com.sola.v2ex_android.ui.adapter.MainPageAdapter; import com.sola.v2ex_android.ui.base.BaseFragment; import butterknife.BindView;
package com.sola.v2ex_android.ui; public class MainContentFragment extends BaseFragment { @BindView(R.id.vp_main) ViewPager mVpMain; @BindView(R.id.tabs) TabLayout mTabs; @Override protected int getLayoutId() { return R.layout.fragment_main_content; } @Override protected void initViews(View view) {
// Path: app/src/main/java/com/sola/v2ex_android/ui/adapter/MainPageAdapter.java // public class MainPageAdapter extends FragmentPagerAdapter { // // private final String[] titles = { "主题", "节点"}; // // public MainPageAdapter(FragmentManager fm) { // super(fm); // } // // @Override // public Fragment getItem(int position) { // if (0 == position){ // return NewestTopicsFragment.newInstance(); // }else { // return NodeFragment.newInstance(); // } // } // // @Override // public CharSequence getPageTitle(int position) { // return titles[position]; // } // // @Override // public int getCount() { // return titles.length; // } // } // // Path: app/src/main/java/com/sola/v2ex_android/ui/base/BaseFragment.java // public abstract class BaseFragment extends Fragment { // // private CompositeSubscription mCompositeSubscription; // Unbinder unbind; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(getLayoutId(), container, false); // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // unbind = ButterKnife.bind(this, view); // initViews(view); // loadData(); // } // // // // public CompositeSubscription getCompositeSubscription() { // if (this.mCompositeSubscription == null) { // this.mCompositeSubscription = new CompositeSubscription(); // } // // return this.mCompositeSubscription; // } // // // public void addSubscription(Subscription s) { // if (this.mCompositeSubscription == null) { // this.mCompositeSubscription = new CompositeSubscription(); // } // // this.mCompositeSubscription.add(s); // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // unbind.unbind(); // if (this.mCompositeSubscription != null) { // this.mCompositeSubscription.unsubscribe(); // } // } // // protected abstract int getLayoutId(); // // protected abstract void initViews(View view); // // protected abstract void loadData(); // // // } // Path: app/src/main/java/com/sola/v2ex_android/ui/MainContentFragment.java import android.view.View; import androidx.viewpager.widget.ViewPager; import com.google.android.material.tabs.TabLayout; import com.sola.v2ex_android.R; import com.sola.v2ex_android.ui.adapter.MainPageAdapter; import com.sola.v2ex_android.ui.base.BaseFragment; import butterknife.BindView; package com.sola.v2ex_android.ui; public class MainContentFragment extends BaseFragment { @BindView(R.id.vp_main) ViewPager mVpMain; @BindView(R.id.tabs) TabLayout mTabs; @Override protected int getLayoutId() { return R.layout.fragment_main_content; } @Override protected void initViews(View view) {
MainPageAdapter adapter = new MainPageAdapter(getFragmentManager());
sooola/V2EX-Android
app/src/main/java/com/sola/v2ex_android/ui/base/adapter/FixEndlessRecyclerViewAdapter.java
// Path: app/src/main/java/com/sola/v2ex_android/util/LogUtil.java // public class LogUtil { // // public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化 // private static final String TAG = "zuqiukong"; // // public LogUtil() { // } // // // 下面四个是默认tag的函数 // public static void i(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(TAG, msg); // } // // public static void d(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(TAG, msg); // } // // public static void e(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(TAG, msg); // } // public static void dClass(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // { // String clazzName = new Throwable().getStackTrace()[1].getClassName(); // String[] clazzNames = clazzName.split("\\."); // Log.d(clazzNames[clazzNames.length - 1], msg); // } // } // // public static void v(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.v(TAG, msg); // } // // // 下面是传入自定义tag的函数 // public static void i(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(tag, msg); // } // // public static void d(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(tag, msg); // } // // public static void e(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(tag, msg); // } // // public static void v(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.v(tag, msg); // } // // public static void w(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.w(tag, msg); // } // // public static void wtf(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.wtf(tag, msg); // } // // }
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.LayoutRes; import androidx.recyclerview.widget.RecyclerView; import com.rockerhieu.rvadapter.RecyclerViewAdapterWrapper; import com.sola.v2ex_android.util.LogUtil; import java.util.concurrent.atomic.AtomicBoolean;
return LayoutInflater.from(context).inflate(pendingViewResId, viewGroup, false); } @Override public int getItemCount() { return super.getItemCount() + (keepOnAppending.get() ? 1 : 0); } @Override public int getItemViewType(int position) { if (position == getWrappedAdapter().getItemCount()) { return TYPE_PENDING; } return super.getItemViewType(position); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == TYPE_PENDING) { return new PendingViewHolder(getPendingView(parent)); } return super.onCreateViewHolder(parent, viewType); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (getItemViewType(position) == TYPE_PENDING) { if (!dataPending.get()) { dataPending.set(true); requestToLoadMoreListener.onLoadMoreRequested();
// Path: app/src/main/java/com/sola/v2ex_android/util/LogUtil.java // public class LogUtil { // // public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化 // private static final String TAG = "zuqiukong"; // // public LogUtil() { // } // // // 下面四个是默认tag的函数 // public static void i(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(TAG, msg); // } // // public static void d(String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(TAG, msg); // } // // public static void e(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(TAG, msg); // } // public static void dClass(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // { // String clazzName = new Throwable().getStackTrace()[1].getClassName(); // String[] clazzNames = clazzName.split("\\."); // Log.d(clazzNames[clazzNames.length - 1], msg); // } // } // // public static void v(String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.v(TAG, msg); // } // // // 下面是传入自定义tag的函数 // public static void i(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.i(tag, msg); // } // // public static void d(String tag, String msg) // { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.d(tag, msg); // } // // public static void e(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg)) // Log.e(tag, msg); // } // // public static void v(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.v(tag, msg); // } // // public static void w(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.w(tag, msg); // } // // public static void wtf(String tag, String msg) { // if (BuildConfig.LOG_DEBUG && ValidateUtil.isNotEmpty(msg) ) // Log.wtf(tag, msg); // } // // } // Path: app/src/main/java/com/sola/v2ex_android/ui/base/adapter/FixEndlessRecyclerViewAdapter.java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.LayoutRes; import androidx.recyclerview.widget.RecyclerView; import com.rockerhieu.rvadapter.RecyclerViewAdapterWrapper; import com.sola.v2ex_android.util.LogUtil; import java.util.concurrent.atomic.AtomicBoolean; return LayoutInflater.from(context).inflate(pendingViewResId, viewGroup, false); } @Override public int getItemCount() { return super.getItemCount() + (keepOnAppending.get() ? 1 : 0); } @Override public int getItemViewType(int position) { if (position == getWrappedAdapter().getItemCount()) { return TYPE_PENDING; } return super.getItemViewType(position); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == TYPE_PENDING) { return new PendingViewHolder(getPendingView(parent)); } return super.onCreateViewHolder(parent, viewType); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (getItemViewType(position) == TYPE_PENDING) { if (!dataPending.get()) { dataPending.set(true); requestToLoadMoreListener.onLoadMoreRequested();
LogUtil.d("FixEndlessRecyclerViewAdapter","onLoadMoreRequested");
twilmes/sql-gremlin
src/test/java/org/twilmes/sql/gremlin/adapter/GremlinSqlBasicSelectTest.java
// Path: src/test/java/org/twilmes/sql/gremlin/adapter/graphs/GraphConstants.java // public class GraphConstants { // public static final String STRING_VALUE = "value"; // public static final Long LONG_VALUE = 100L; // public static final Integer INTEGER_VALUE = LONG_VALUE.intValue(); // public static final Short SHORT_VALUE = LONG_VALUE.shortValue(); // public static final Byte BYTE_VALUE = LONG_VALUE.byteValue(); // public static final Double DOUBLE_VALUE = LONG_VALUE.doubleValue(); // public static final Float FLOAT_VALUE = LONG_VALUE.floatValue(); // public static final Date DATE_VALUE; // private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-mm-dd"); // // static { // Date date = null; // try { // date = DATE_FORMATTER.parse("1993-03-30"); // } catch (final ParseException e) { // e.printStackTrace(); // } // DATE_VALUE = date; // } // }
import com.google.common.collect.ImmutableList; import org.junit.jupiter.api.Test; import org.twilmes.sql.gremlin.adapter.graphs.GraphConstants; import java.sql.SQLException; import java.util.List;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.twilmes.sql.gremlin.adapter; public class GremlinSqlBasicSelectTest extends GremlinSqlBaseTest { GremlinSqlBasicSelectTest() throws SQLException { } @Override protected DataSet getDataSet() { return DataSet.DATA_TYPES; } @Test void testStringQuery() throws SQLException {
// Path: src/test/java/org/twilmes/sql/gremlin/adapter/graphs/GraphConstants.java // public class GraphConstants { // public static final String STRING_VALUE = "value"; // public static final Long LONG_VALUE = 100L; // public static final Integer INTEGER_VALUE = LONG_VALUE.intValue(); // public static final Short SHORT_VALUE = LONG_VALUE.shortValue(); // public static final Byte BYTE_VALUE = LONG_VALUE.byteValue(); // public static final Double DOUBLE_VALUE = LONG_VALUE.doubleValue(); // public static final Float FLOAT_VALUE = LONG_VALUE.floatValue(); // public static final Date DATE_VALUE; // private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-mm-dd"); // // static { // Date date = null; // try { // date = DATE_FORMATTER.parse("1993-03-30"); // } catch (final ParseException e) { // e.printStackTrace(); // } // DATE_VALUE = date; // } // } // Path: src/test/java/org/twilmes/sql/gremlin/adapter/GremlinSqlBasicSelectTest.java import com.google.common.collect.ImmutableList; import org.junit.jupiter.api.Test; import org.twilmes.sql.gremlin.adapter.graphs.GraphConstants; import java.sql.SQLException; import java.util.List; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.twilmes.sql.gremlin.adapter; public class GremlinSqlBasicSelectTest extends GremlinSqlBaseTest { GremlinSqlBasicSelectTest() throws SQLException { } @Override protected DataSet getDataSet() { return DataSet.DATA_TYPES; } @Test void testStringQuery() throws SQLException {
runQueryTestResults("SELECT \"key\" FROM stringtype", columns("key"), rows(r(GraphConstants.STRING_VALUE)));
twilmes/sql-gremlin
src/main/java/org/twilmes/sql/gremlin/adapter/converter/schema/gremlin/GremlinTableBase.java
// Path: src/main/java/org/twilmes/sql/gremlin/adapter/converter/schema/calcite/GremlinRel.java // public interface GremlinRel extends RelNode { // /** // * Calling convention for relational operations that occur in Gremlin. // */ // Convention CONVENTION = new Convention.Impl("GREMLIN", GremlinRel.class); // } // // Path: src/main/java/org/twilmes/sql/gremlin/adapter/converter/schema/calcite/GremlinTableScan.java // public class GremlinTableScan extends TableScan implements GremlinRel { // /** // * Calling convention for relational operations that occur in Gremlin. // */ // private final int[] fields; // // public GremlinTableScan(final RelOptCluster cluster, final RelTraitSet traitSet, // final RelOptTable table, final int[] fields) { // super(cluster, traitSet, table); // this.fields = fields; // } // // @Override // public RelNode copy(final RelTraitSet traitSet, final List<RelNode> inputs) { // assert inputs.isEmpty(); // return this; // } // // @Override // public RelDataType deriveRowType() { // final List<RelDataTypeField> fieldList = table.getRowType().getFieldList(); // final RelDataTypeFactory.FieldInfoBuilder builder = // getCluster().getTypeFactory().builder(); // for (final int field : fields) { // builder.add(fieldList.get(field)); // } // return builder.build(); // } // // @Override // public void register(final RelOptPlanner planner) { // planner.addRule(GremlinToEnumerableConverterRule.INSTANCE); // for (final RelOptRule rule : GremlinRules.RULES) { // planner.addRule(rule); // } // } // }
import org.twilmes.sql.gremlin.adapter.converter.schema.calcite.GremlinRel; import org.twilmes.sql.gremlin.adapter.converter.schema.calcite.GremlinTableScan; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import lombok.Getter; import org.apache.calcite.adapter.java.AbstractQueryableTable; import org.apache.calcite.linq4j.QueryProvider; import org.apache.calcite.linq4j.Queryable; import org.apache.calcite.plan.RelOptTable; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.calcite.schema.SchemaPlus; import org.apache.calcite.schema.TranslatableTable; import org.apache.calcite.util.Pair;
public GremlinTableBase(final String label, final Boolean isVertex, final Map<String, GremlinProperty> columns) { super(Object[].class); this.label = label; this.isVertex = isVertex; this.columns = columns; } public GremlinProperty getColumn(final String column) throws SQLException { for (final String key : columns.keySet()) { if (key.equalsIgnoreCase(column)) { return columns.get(key); } } throw new SQLException(String.format( "Error: Could not find column '%s' on %s with label '%s'.", column, isVertex ? "vertex" : "edge", label)); } @Override public <T> Queryable<T> asQueryable(final QueryProvider queryProvider, final SchemaPlus schema, final String tableName) { return null; } @Override public RelNode toRel(final RelOptTable.ToRelContext context, final RelOptTable relOptTable) { final int[] fields = new int[columns.size()]; for (int i = 0; i < fields.length; i++) { fields[i] = i; }
// Path: src/main/java/org/twilmes/sql/gremlin/adapter/converter/schema/calcite/GremlinRel.java // public interface GremlinRel extends RelNode { // /** // * Calling convention for relational operations that occur in Gremlin. // */ // Convention CONVENTION = new Convention.Impl("GREMLIN", GremlinRel.class); // } // // Path: src/main/java/org/twilmes/sql/gremlin/adapter/converter/schema/calcite/GremlinTableScan.java // public class GremlinTableScan extends TableScan implements GremlinRel { // /** // * Calling convention for relational operations that occur in Gremlin. // */ // private final int[] fields; // // public GremlinTableScan(final RelOptCluster cluster, final RelTraitSet traitSet, // final RelOptTable table, final int[] fields) { // super(cluster, traitSet, table); // this.fields = fields; // } // // @Override // public RelNode copy(final RelTraitSet traitSet, final List<RelNode> inputs) { // assert inputs.isEmpty(); // return this; // } // // @Override // public RelDataType deriveRowType() { // final List<RelDataTypeField> fieldList = table.getRowType().getFieldList(); // final RelDataTypeFactory.FieldInfoBuilder builder = // getCluster().getTypeFactory().builder(); // for (final int field : fields) { // builder.add(fieldList.get(field)); // } // return builder.build(); // } // // @Override // public void register(final RelOptPlanner planner) { // planner.addRule(GremlinToEnumerableConverterRule.INSTANCE); // for (final RelOptRule rule : GremlinRules.RULES) { // planner.addRule(rule); // } // } // } // Path: src/main/java/org/twilmes/sql/gremlin/adapter/converter/schema/gremlin/GremlinTableBase.java import org.twilmes.sql.gremlin.adapter.converter.schema.calcite.GremlinRel; import org.twilmes.sql.gremlin.adapter.converter.schema.calcite.GremlinTableScan; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import lombok.Getter; import org.apache.calcite.adapter.java.AbstractQueryableTable; import org.apache.calcite.linq4j.QueryProvider; import org.apache.calcite.linq4j.Queryable; import org.apache.calcite.plan.RelOptTable; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.calcite.schema.SchemaPlus; import org.apache.calcite.schema.TranslatableTable; import org.apache.calcite.util.Pair; public GremlinTableBase(final String label, final Boolean isVertex, final Map<String, GremlinProperty> columns) { super(Object[].class); this.label = label; this.isVertex = isVertex; this.columns = columns; } public GremlinProperty getColumn(final String column) throws SQLException { for (final String key : columns.keySet()) { if (key.equalsIgnoreCase(column)) { return columns.get(key); } } throw new SQLException(String.format( "Error: Could not find column '%s' on %s with label '%s'.", column, isVertex ? "vertex" : "edge", label)); } @Override public <T> Queryable<T> asQueryable(final QueryProvider queryProvider, final SchemaPlus schema, final String tableName) { return null; } @Override public RelNode toRel(final RelOptTable.ToRelContext context, final RelOptTable relOptTable) { final int[] fields = new int[columns.size()]; for (int i = 0; i < fields.length; i++) { fields[i] = i; }
return new GremlinTableScan(context.getCluster(), context.getCluster().traitSetOf(GremlinRel.CONVENTION), relOptTable, fields);
twilmes/sql-gremlin
src/main/java/org/twilmes/sql/gremlin/adapter/converter/schema/gremlin/GremlinTableBase.java
// Path: src/main/java/org/twilmes/sql/gremlin/adapter/converter/schema/calcite/GremlinRel.java // public interface GremlinRel extends RelNode { // /** // * Calling convention for relational operations that occur in Gremlin. // */ // Convention CONVENTION = new Convention.Impl("GREMLIN", GremlinRel.class); // } // // Path: src/main/java/org/twilmes/sql/gremlin/adapter/converter/schema/calcite/GremlinTableScan.java // public class GremlinTableScan extends TableScan implements GremlinRel { // /** // * Calling convention for relational operations that occur in Gremlin. // */ // private final int[] fields; // // public GremlinTableScan(final RelOptCluster cluster, final RelTraitSet traitSet, // final RelOptTable table, final int[] fields) { // super(cluster, traitSet, table); // this.fields = fields; // } // // @Override // public RelNode copy(final RelTraitSet traitSet, final List<RelNode> inputs) { // assert inputs.isEmpty(); // return this; // } // // @Override // public RelDataType deriveRowType() { // final List<RelDataTypeField> fieldList = table.getRowType().getFieldList(); // final RelDataTypeFactory.FieldInfoBuilder builder = // getCluster().getTypeFactory().builder(); // for (final int field : fields) { // builder.add(fieldList.get(field)); // } // return builder.build(); // } // // @Override // public void register(final RelOptPlanner planner) { // planner.addRule(GremlinToEnumerableConverterRule.INSTANCE); // for (final RelOptRule rule : GremlinRules.RULES) { // planner.addRule(rule); // } // } // }
import org.twilmes.sql.gremlin.adapter.converter.schema.calcite.GremlinRel; import org.twilmes.sql.gremlin.adapter.converter.schema.calcite.GremlinTableScan; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import lombok.Getter; import org.apache.calcite.adapter.java.AbstractQueryableTable; import org.apache.calcite.linq4j.QueryProvider; import org.apache.calcite.linq4j.Queryable; import org.apache.calcite.plan.RelOptTable; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.calcite.schema.SchemaPlus; import org.apache.calcite.schema.TranslatableTable; import org.apache.calcite.util.Pair;
public GremlinTableBase(final String label, final Boolean isVertex, final Map<String, GremlinProperty> columns) { super(Object[].class); this.label = label; this.isVertex = isVertex; this.columns = columns; } public GremlinProperty getColumn(final String column) throws SQLException { for (final String key : columns.keySet()) { if (key.equalsIgnoreCase(column)) { return columns.get(key); } } throw new SQLException(String.format( "Error: Could not find column '%s' on %s with label '%s'.", column, isVertex ? "vertex" : "edge", label)); } @Override public <T> Queryable<T> asQueryable(final QueryProvider queryProvider, final SchemaPlus schema, final String tableName) { return null; } @Override public RelNode toRel(final RelOptTable.ToRelContext context, final RelOptTable relOptTable) { final int[] fields = new int[columns.size()]; for (int i = 0; i < fields.length; i++) { fields[i] = i; }
// Path: src/main/java/org/twilmes/sql/gremlin/adapter/converter/schema/calcite/GremlinRel.java // public interface GremlinRel extends RelNode { // /** // * Calling convention for relational operations that occur in Gremlin. // */ // Convention CONVENTION = new Convention.Impl("GREMLIN", GremlinRel.class); // } // // Path: src/main/java/org/twilmes/sql/gremlin/adapter/converter/schema/calcite/GremlinTableScan.java // public class GremlinTableScan extends TableScan implements GremlinRel { // /** // * Calling convention for relational operations that occur in Gremlin. // */ // private final int[] fields; // // public GremlinTableScan(final RelOptCluster cluster, final RelTraitSet traitSet, // final RelOptTable table, final int[] fields) { // super(cluster, traitSet, table); // this.fields = fields; // } // // @Override // public RelNode copy(final RelTraitSet traitSet, final List<RelNode> inputs) { // assert inputs.isEmpty(); // return this; // } // // @Override // public RelDataType deriveRowType() { // final List<RelDataTypeField> fieldList = table.getRowType().getFieldList(); // final RelDataTypeFactory.FieldInfoBuilder builder = // getCluster().getTypeFactory().builder(); // for (final int field : fields) { // builder.add(fieldList.get(field)); // } // return builder.build(); // } // // @Override // public void register(final RelOptPlanner planner) { // planner.addRule(GremlinToEnumerableConverterRule.INSTANCE); // for (final RelOptRule rule : GremlinRules.RULES) { // planner.addRule(rule); // } // } // } // Path: src/main/java/org/twilmes/sql/gremlin/adapter/converter/schema/gremlin/GremlinTableBase.java import org.twilmes.sql.gremlin.adapter.converter.schema.calcite.GremlinRel; import org.twilmes.sql.gremlin.adapter.converter.schema.calcite.GremlinTableScan; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import lombok.Getter; import org.apache.calcite.adapter.java.AbstractQueryableTable; import org.apache.calcite.linq4j.QueryProvider; import org.apache.calcite.linq4j.Queryable; import org.apache.calcite.plan.RelOptTable; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.calcite.schema.SchemaPlus; import org.apache.calcite.schema.TranslatableTable; import org.apache.calcite.util.Pair; public GremlinTableBase(final String label, final Boolean isVertex, final Map<String, GremlinProperty> columns) { super(Object[].class); this.label = label; this.isVertex = isVertex; this.columns = columns; } public GremlinProperty getColumn(final String column) throws SQLException { for (final String key : columns.keySet()) { if (key.equalsIgnoreCase(column)) { return columns.get(key); } } throw new SQLException(String.format( "Error: Could not find column '%s' on %s with label '%s'.", column, isVertex ? "vertex" : "edge", label)); } @Override public <T> Queryable<T> asQueryable(final QueryProvider queryProvider, final SchemaPlus schema, final String tableName) { return null; } @Override public RelNode toRel(final RelOptTable.ToRelContext context, final RelOptTable relOptTable) { final int[] fields = new int[columns.size()]; for (int i = 0; i < fields.length; i++) { fields[i] = i; }
return new GremlinTableScan(context.getCluster(), context.getCluster().traitSetOf(GremlinRel.CONVENTION), relOptTable, fields);
twilmes/sql-gremlin
src/main/java/org/twilmes/sql/gremlin/adapter/results/pagination/Pagination.java
// Path: src/main/java/org/twilmes/sql/gremlin/adapter/results/SqlGremlinQueryResult.java // @Getter // public class SqlGremlinQueryResult { // public static final String EMPTY_MESSAGE = "No more results."; // public static final String NULL_VALUE = "$%#NULL#%$"; // private final List<String> columns; // private final List<String> columnTypes = new ArrayList<>(); // private final Object assertEmptyLock = new Object(); // private final BlockingQueue<List<Object>> blockingQueueRows = new LinkedBlockingQueue<>(); // private boolean isEmpty = false; // private SQLException paginationException = null; // private Thread currThread = null; // // public SqlGremlinQueryResult(final List<String> columns, final List<GremlinTableBase> gremlinTableBases, // final SqlMetadata sqlMetadata) throws SQLException { // this.columns = columns; // for (final String column : columns) { // GremlinProperty col = null; // for (final GremlinTableBase gremlinTableBase : gremlinTableBases) { // if (sqlMetadata.getTableHasColumn(gremlinTableBase, column)) { // col = sqlMetadata.getGremlinProperty(gremlinTableBase.getLabel(), column); // break; // } // } // columnTypes.add((col == null || col.getType() == null) ? "string" : col.getType()); // } // } // // public void setPaginationException(final SQLException e) { // synchronized (assertEmptyLock) { // paginationException = e; // if (currThread != null && blockingQueueRows.size() == 0) { // currThread.interrupt(); // } // } // } // // public boolean getIsEmpty() throws SQLException { // if (paginationException == null) { // return isEmpty; // } // throw paginationException; // } // // public void assertIsEmpty() { // synchronized (assertEmptyLock) { // if (currThread != null && blockingQueueRows.size() == 0) { // currThread.interrupt(); // } // isEmpty = true; // } // } // // public void addResults(final List<List<Object>> rows) { // for (final List<Object> row : rows) { // for (int i = 0; i < row.size(); i++) { // if (row.get(i) instanceof String && row.get(i).toString().equals(NULL_VALUE)) { // row.set(i, null); // } // } // } // blockingQueueRows.addAll(rows); // } // // private boolean getShouldExit() throws SQLException { // synchronized (assertEmptyLock) { // return (getIsEmpty() && blockingQueueRows.size() == 0); // } // } // // public Object getResult() throws SQLException { // synchronized (assertEmptyLock) { // this.currThread = Thread.currentThread(); // } // while (!getShouldExit()) { // try { // return this.blockingQueueRows.take(); // } catch (final InterruptedException ignored) { // if (paginationException != null) { // throw paginationException; // } // } // } // throw new SQLException(EMPTY_MESSAGE); // } // }
import java.util.List; import java.util.Map; import lombok.AllArgsConstructor; import org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.twilmes.sql.gremlin.adapter.results.SqlGremlinQueryResult; import java.io.PrintWriter; import java.io.StringWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.twilmes.sql.gremlin.adapter.results.pagination; @AllArgsConstructor public class Pagination implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(Pagination.class); private static final int DEFAULT_PAGE_SIZE = 1000; private final int pageSize = DEFAULT_PAGE_SIZE; private final GetRowFromMap getRowFromMap; private final GraphTraversal<?, ?> traversal;
// Path: src/main/java/org/twilmes/sql/gremlin/adapter/results/SqlGremlinQueryResult.java // @Getter // public class SqlGremlinQueryResult { // public static final String EMPTY_MESSAGE = "No more results."; // public static final String NULL_VALUE = "$%#NULL#%$"; // private final List<String> columns; // private final List<String> columnTypes = new ArrayList<>(); // private final Object assertEmptyLock = new Object(); // private final BlockingQueue<List<Object>> blockingQueueRows = new LinkedBlockingQueue<>(); // private boolean isEmpty = false; // private SQLException paginationException = null; // private Thread currThread = null; // // public SqlGremlinQueryResult(final List<String> columns, final List<GremlinTableBase> gremlinTableBases, // final SqlMetadata sqlMetadata) throws SQLException { // this.columns = columns; // for (final String column : columns) { // GremlinProperty col = null; // for (final GremlinTableBase gremlinTableBase : gremlinTableBases) { // if (sqlMetadata.getTableHasColumn(gremlinTableBase, column)) { // col = sqlMetadata.getGremlinProperty(gremlinTableBase.getLabel(), column); // break; // } // } // columnTypes.add((col == null || col.getType() == null) ? "string" : col.getType()); // } // } // // public void setPaginationException(final SQLException e) { // synchronized (assertEmptyLock) { // paginationException = e; // if (currThread != null && blockingQueueRows.size() == 0) { // currThread.interrupt(); // } // } // } // // public boolean getIsEmpty() throws SQLException { // if (paginationException == null) { // return isEmpty; // } // throw paginationException; // } // // public void assertIsEmpty() { // synchronized (assertEmptyLock) { // if (currThread != null && blockingQueueRows.size() == 0) { // currThread.interrupt(); // } // isEmpty = true; // } // } // // public void addResults(final List<List<Object>> rows) { // for (final List<Object> row : rows) { // for (int i = 0; i < row.size(); i++) { // if (row.get(i) instanceof String && row.get(i).toString().equals(NULL_VALUE)) { // row.set(i, null); // } // } // } // blockingQueueRows.addAll(rows); // } // // private boolean getShouldExit() throws SQLException { // synchronized (assertEmptyLock) { // return (getIsEmpty() && blockingQueueRows.size() == 0); // } // } // // public Object getResult() throws SQLException { // synchronized (assertEmptyLock) { // this.currThread = Thread.currentThread(); // } // while (!getShouldExit()) { // try { // return this.blockingQueueRows.take(); // } catch (final InterruptedException ignored) { // if (paginationException != null) { // throw paginationException; // } // } // } // throw new SQLException(EMPTY_MESSAGE); // } // } // Path: src/main/java/org/twilmes/sql/gremlin/adapter/results/pagination/Pagination.java import java.util.List; import java.util.Map; import lombok.AllArgsConstructor; import org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.twilmes.sql.gremlin.adapter.results.SqlGremlinQueryResult; import java.io.PrintWriter; import java.io.StringWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.twilmes.sql.gremlin.adapter.results.pagination; @AllArgsConstructor public class Pagination implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(Pagination.class); private static final int DEFAULT_PAGE_SIZE = 1000; private final int pageSize = DEFAULT_PAGE_SIZE; private final GetRowFromMap getRowFromMap; private final GraphTraversal<?, ?> traversal;
private final SqlGremlinQueryResult sqlGremlinQueryResult;
twilmes/sql-gremlin
src/test/java/org/twilmes/sql/gremlin/adapter/graphs/TestGraphFactory.java
// Path: src/test/java/org/twilmes/sql/gremlin/adapter/GremlinSqlBaseTest.java // public abstract class GremlinSqlBaseTest { // private final Graph graph; // private final GraphTraversalSource g; // private final SqlConverter converter; // // GremlinSqlBaseTest() throws SQLException { // graph = TestGraphFactory.createGraph(getDataSet()); // g = graph.traversal(); // final GremlinSchema gremlinSchema = SqlSchemaGrabber.getSchema(g, SqlSchemaGrabber.ScanType.All); // converter = new SqlConverter(gremlinSchema, g); // } // // protected abstract DataSet getDataSet(); // // protected void runQueryTestResults(final String query, final List<String> columnNames, // final List<List<Object>> rows) // throws SQLException { // final SqlGremlinTestResult result = new SqlGremlinTestResult(converter.executeQuery(query)); // assertRows(result.getRows(), rows); // assertColumns(result.getColumns(), columnNames); // } // // public List<List<Object>> rows(final List<Object>... rows) { // return new ArrayList<>(Arrays.asList(rows)); // } // // public List<String> columns(final String... columns) { // return new ArrayList<>(Arrays.asList(columns)); // } // // public List<Object> r(final Object... row) { // return new ArrayList<>(Arrays.asList(row)); // } // // public void assertRows(final List<List<Object>> actual, final List<List<Object>> expected) { // Assertions.assertEquals(expected.size(), actual.size()); // for (int i = 0; i < actual.size(); i++) { // Assertions.assertEquals(expected.get(i).size(), actual.get(i).size()); // for (int j = 0; j < actual.get(i).size(); j++) { // Assertions.assertEquals(expected.get(i).get(j), actual.get(i).get(j)); // } // } // } // // public void assertColumns(final List<String> actual, final List<String> expected) { // Assertions.assertEquals(expected.size(), actual.size()); // for (int i = 0; i < actual.size(); i++) { // Assertions.assertEquals(expected.get(i), actual.get(i)); // } // } // // public enum DataSet { // SPACE, // DATA_TYPES // } // // @Getter // static class SqlGremlinTestResult { // private final List<List<Object>> rows = new ArrayList<>(); // private final List<String> columns; // // SqlGremlinTestResult(final SqlGremlinQueryResult sqlGremlinQueryResult) throws SQLException { // columns = sqlGremlinQueryResult.getColumns(); // Object res; // do { // try { // res = sqlGremlinQueryResult.getResult(); // } catch (final SQLException e) { // if (e.getMessage().equals(SqlGremlinQueryResult.EMPTY_MESSAGE)) { // break; // } else { // throw e; // } // } // this.rows.add((List<Object>) res); // } while (true); // } // } // }
import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; import org.twilmes.sql.gremlin.adapter.GremlinSqlBaseTest;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.twilmes.sql.gremlin.adapter.graphs; public class TestGraphFactory { private static final TestGraph SPACE_GRAPH = new SpaceTestGraph(); private static final TestGraph DATA_TYPE_GRAPH = new DataTypeGraph();
// Path: src/test/java/org/twilmes/sql/gremlin/adapter/GremlinSqlBaseTest.java // public abstract class GremlinSqlBaseTest { // private final Graph graph; // private final GraphTraversalSource g; // private final SqlConverter converter; // // GremlinSqlBaseTest() throws SQLException { // graph = TestGraphFactory.createGraph(getDataSet()); // g = graph.traversal(); // final GremlinSchema gremlinSchema = SqlSchemaGrabber.getSchema(g, SqlSchemaGrabber.ScanType.All); // converter = new SqlConverter(gremlinSchema, g); // } // // protected abstract DataSet getDataSet(); // // protected void runQueryTestResults(final String query, final List<String> columnNames, // final List<List<Object>> rows) // throws SQLException { // final SqlGremlinTestResult result = new SqlGremlinTestResult(converter.executeQuery(query)); // assertRows(result.getRows(), rows); // assertColumns(result.getColumns(), columnNames); // } // // public List<List<Object>> rows(final List<Object>... rows) { // return new ArrayList<>(Arrays.asList(rows)); // } // // public List<String> columns(final String... columns) { // return new ArrayList<>(Arrays.asList(columns)); // } // // public List<Object> r(final Object... row) { // return new ArrayList<>(Arrays.asList(row)); // } // // public void assertRows(final List<List<Object>> actual, final List<List<Object>> expected) { // Assertions.assertEquals(expected.size(), actual.size()); // for (int i = 0; i < actual.size(); i++) { // Assertions.assertEquals(expected.get(i).size(), actual.get(i).size()); // for (int j = 0; j < actual.get(i).size(); j++) { // Assertions.assertEquals(expected.get(i).get(j), actual.get(i).get(j)); // } // } // } // // public void assertColumns(final List<String> actual, final List<String> expected) { // Assertions.assertEquals(expected.size(), actual.size()); // for (int i = 0; i < actual.size(); i++) { // Assertions.assertEquals(expected.get(i), actual.get(i)); // } // } // // public enum DataSet { // SPACE, // DATA_TYPES // } // // @Getter // static class SqlGremlinTestResult { // private final List<List<Object>> rows = new ArrayList<>(); // private final List<String> columns; // // SqlGremlinTestResult(final SqlGremlinQueryResult sqlGremlinQueryResult) throws SQLException { // columns = sqlGremlinQueryResult.getColumns(); // Object res; // do { // try { // res = sqlGremlinQueryResult.getResult(); // } catch (final SQLException e) { // if (e.getMessage().equals(SqlGremlinQueryResult.EMPTY_MESSAGE)) { // break; // } else { // throw e; // } // } // this.rows.add((List<Object>) res); // } while (true); // } // } // } // Path: src/test/java/org/twilmes/sql/gremlin/adapter/graphs/TestGraphFactory.java import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; import org.twilmes.sql.gremlin.adapter.GremlinSqlBaseTest; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.twilmes.sql.gremlin.adapter.graphs; public class TestGraphFactory { private static final TestGraph SPACE_GRAPH = new SpaceTestGraph(); private static final TestGraph DATA_TYPE_GRAPH = new DataTypeGraph();
public static Graph createGraph(final GremlinSqlBaseTest.DataSet dataSet) {
testinfected/mario
src/main/java/com/vtence/mario/ElementActions.java
// Path: src/main/java/com/vtence/mario/ElementManipulation.java // public static ElementAction manipulate(String description, Manipulation manipulation) { // return new ElementManipulation(description, manipulation); // }
import org.openqa.selenium.WebElement; import static com.vtence.mario.ElementManipulation.manipulate;
package com.vtence.mario; public class ElementActions { public static ElementAction click() {
// Path: src/main/java/com/vtence/mario/ElementManipulation.java // public static ElementAction manipulate(String description, Manipulation manipulation) { // return new ElementManipulation(description, manipulation); // } // Path: src/main/java/com/vtence/mario/ElementActions.java import org.openqa.selenium.WebElement; import static com.vtence.mario.ElementManipulation.manipulate; package com.vtence.mario; public class ElementActions { public static ElementAction click() {
return manipulate("click on", WebElement::click);
GoogleCloudPlatform/dlp-dataflow-deidentification
src/test/java/com/google/swarm/tokenization/avro/GenericRecordCoderTest.java
// Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static List<GenericRecord> generateGenericRecords(long count) { // ArrayList<GenericRecord> result = new ArrayList<>(); // GenericRecordBuilder builder = new GenericRecordBuilder(schema); // for (int i = 0; i < count; i++) { // GenericRecord record = builder.set("user", "abcd").set("message", "Message #" + i).build(); // result.add(record); // } // return result; // }
import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.generateGenericRecords; import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.apache.avro.generic.GenericRecord; import org.junit.Test;
/* * Copyright 2020 Google LLC * * 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.google.swarm.tokenization.avro; public class GenericRecordCoderTest { @Test public void testGenericRecordCoder() throws IOException {
// Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static List<GenericRecord> generateGenericRecords(long count) { // ArrayList<GenericRecord> result = new ArrayList<>(); // GenericRecordBuilder builder = new GenericRecordBuilder(schema); // for (int i = 0; i < count; i++) { // GenericRecord record = builder.set("user", "abcd").set("message", "Message #" + i).build(); // result.add(record); // } // return result; // } // Path: src/test/java/com/google/swarm/tokenization/avro/GenericRecordCoderTest.java import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.generateGenericRecords; import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.apache.avro.generic.GenericRecord; import org.junit.Test; /* * Copyright 2020 Google LLC * * 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.google.swarm.tokenization.avro; public class GenericRecordCoderTest { @Test public void testGenericRecordCoder() throws IOException {
GenericRecord record = generateGenericRecords(1).get(0);
GoogleCloudPlatform/dlp-dataflow-deidentification
src/main/java/com/google/swarm/tokenization/common/ExtractColumnNamesTransform.java
// Path: src/main/java/com/google/swarm/tokenization/avro/AvroColumnNamesDoFn.java // public class AvroColumnNamesDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // public static final Logger LOG = LoggerFactory.getLogger(AvroColumnNamesDoFn.class); // // @ProcessElement // public void processElement(ProcessContext c) { // ReadableFile avroFile = c.element().getValue(); // try (AvroUtil.AvroSeekableByteChannel channel = AvroUtil.getChannel(avroFile)) { // DatumReader<GenericRecord> reader = new GenericDatumReader<>(); // DataFileReader<GenericRecord> fileReader = new DataFileReader<>(channel, reader); // List<String> fieldNames = new ArrayList<>(); // AvroUtil.flattenFieldNames(fileReader.getSchema(), fieldNames, ""); // // String fileName = c.element().getKey(); // c.output(KV.of(fileName, fieldNames)); // // LOG.info("Avro header fields: {}", String.join(",", fieldNames)); // } catch (IOException e) { // LOG.error("Failed to get Avro header values: {}", e.getMessage()); // throw new RuntimeException(e); // } // } // } // // Path: src/main/java/com/google/swarm/tokenization/common/Util.java // public enum FileType { // CSV, // AVRO, // JSON, // TXT // } // // Path: src/main/java/com/google/swarm/tokenization/json/JsonColumnNameDoFn.java // @SuppressWarnings("serial") // public class JsonColumnNameDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // private List<String> headers; // // public JsonColumnNameDoFn(List<String> headers) { // this.headers = headers; // } // // @ProcessElement // public void processContext(ProcessContext c) { // String fileName = c.element().getKey(); // c.output(KV.of(fileName, headers)); // } // } // // Path: src/main/java/com/google/swarm/tokenization/txt/TxtColumnNameDoFn.java // public class TxtColumnNameDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // private List<String> headers; // // public TxtColumnNameDoFn(List<String> headers) { // this.headers = headers; // } // // @ProcessElement // public void processContext(ProcessContext c) { // String fileName = c.element().getKey(); // c.output(KV.of(fileName, headers)); // } // }
import com.google.auto.value.AutoValue; import com.google.swarm.tokenization.avro.AvroColumnNamesDoFn; import com.google.swarm.tokenization.common.Util.FileType; import com.google.swarm.tokenization.json.JsonColumnNameDoFn; import com.google.swarm.tokenization.txt.TxtColumnNameDoFn; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import org.apache.beam.sdk.io.FileIO; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.View; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionView;
/* * Copyright 2020 Google LLC * * 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.google.swarm.tokenization.common; @SuppressWarnings("serial") @AutoValue public abstract class ExtractColumnNamesTransform extends PTransform< PCollection<KV<String, FileIO.ReadableFile>>, PCollectionView<Map<String, List<String>>>> {
// Path: src/main/java/com/google/swarm/tokenization/avro/AvroColumnNamesDoFn.java // public class AvroColumnNamesDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // public static final Logger LOG = LoggerFactory.getLogger(AvroColumnNamesDoFn.class); // // @ProcessElement // public void processElement(ProcessContext c) { // ReadableFile avroFile = c.element().getValue(); // try (AvroUtil.AvroSeekableByteChannel channel = AvroUtil.getChannel(avroFile)) { // DatumReader<GenericRecord> reader = new GenericDatumReader<>(); // DataFileReader<GenericRecord> fileReader = new DataFileReader<>(channel, reader); // List<String> fieldNames = new ArrayList<>(); // AvroUtil.flattenFieldNames(fileReader.getSchema(), fieldNames, ""); // // String fileName = c.element().getKey(); // c.output(KV.of(fileName, fieldNames)); // // LOG.info("Avro header fields: {}", String.join(",", fieldNames)); // } catch (IOException e) { // LOG.error("Failed to get Avro header values: {}", e.getMessage()); // throw new RuntimeException(e); // } // } // } // // Path: src/main/java/com/google/swarm/tokenization/common/Util.java // public enum FileType { // CSV, // AVRO, // JSON, // TXT // } // // Path: src/main/java/com/google/swarm/tokenization/json/JsonColumnNameDoFn.java // @SuppressWarnings("serial") // public class JsonColumnNameDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // private List<String> headers; // // public JsonColumnNameDoFn(List<String> headers) { // this.headers = headers; // } // // @ProcessElement // public void processContext(ProcessContext c) { // String fileName = c.element().getKey(); // c.output(KV.of(fileName, headers)); // } // } // // Path: src/main/java/com/google/swarm/tokenization/txt/TxtColumnNameDoFn.java // public class TxtColumnNameDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // private List<String> headers; // // public TxtColumnNameDoFn(List<String> headers) { // this.headers = headers; // } // // @ProcessElement // public void processContext(ProcessContext c) { // String fileName = c.element().getKey(); // c.output(KV.of(fileName, headers)); // } // } // Path: src/main/java/com/google/swarm/tokenization/common/ExtractColumnNamesTransform.java import com.google.auto.value.AutoValue; import com.google.swarm.tokenization.avro.AvroColumnNamesDoFn; import com.google.swarm.tokenization.common.Util.FileType; import com.google.swarm.tokenization.json.JsonColumnNameDoFn; import com.google.swarm.tokenization.txt.TxtColumnNameDoFn; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import org.apache.beam.sdk.io.FileIO; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.View; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionView; /* * Copyright 2020 Google LLC * * 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.google.swarm.tokenization.common; @SuppressWarnings("serial") @AutoValue public abstract class ExtractColumnNamesTransform extends PTransform< PCollection<KV<String, FileIO.ReadableFile>>, PCollectionView<Map<String, List<String>>>> {
public abstract FileType fileType();
GoogleCloudPlatform/dlp-dataflow-deidentification
src/main/java/com/google/swarm/tokenization/common/ExtractColumnNamesTransform.java
// Path: src/main/java/com/google/swarm/tokenization/avro/AvroColumnNamesDoFn.java // public class AvroColumnNamesDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // public static final Logger LOG = LoggerFactory.getLogger(AvroColumnNamesDoFn.class); // // @ProcessElement // public void processElement(ProcessContext c) { // ReadableFile avroFile = c.element().getValue(); // try (AvroUtil.AvroSeekableByteChannel channel = AvroUtil.getChannel(avroFile)) { // DatumReader<GenericRecord> reader = new GenericDatumReader<>(); // DataFileReader<GenericRecord> fileReader = new DataFileReader<>(channel, reader); // List<String> fieldNames = new ArrayList<>(); // AvroUtil.flattenFieldNames(fileReader.getSchema(), fieldNames, ""); // // String fileName = c.element().getKey(); // c.output(KV.of(fileName, fieldNames)); // // LOG.info("Avro header fields: {}", String.join(",", fieldNames)); // } catch (IOException e) { // LOG.error("Failed to get Avro header values: {}", e.getMessage()); // throw new RuntimeException(e); // } // } // } // // Path: src/main/java/com/google/swarm/tokenization/common/Util.java // public enum FileType { // CSV, // AVRO, // JSON, // TXT // } // // Path: src/main/java/com/google/swarm/tokenization/json/JsonColumnNameDoFn.java // @SuppressWarnings("serial") // public class JsonColumnNameDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // private List<String> headers; // // public JsonColumnNameDoFn(List<String> headers) { // this.headers = headers; // } // // @ProcessElement // public void processContext(ProcessContext c) { // String fileName = c.element().getKey(); // c.output(KV.of(fileName, headers)); // } // } // // Path: src/main/java/com/google/swarm/tokenization/txt/TxtColumnNameDoFn.java // public class TxtColumnNameDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // private List<String> headers; // // public TxtColumnNameDoFn(List<String> headers) { // this.headers = headers; // } // // @ProcessElement // public void processContext(ProcessContext c) { // String fileName = c.element().getKey(); // c.output(KV.of(fileName, headers)); // } // }
import com.google.auto.value.AutoValue; import com.google.swarm.tokenization.avro.AvroColumnNamesDoFn; import com.google.swarm.tokenization.common.Util.FileType; import com.google.swarm.tokenization.json.JsonColumnNameDoFn; import com.google.swarm.tokenization.txt.TxtColumnNameDoFn; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import org.apache.beam.sdk.io.FileIO; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.View; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionView;
/* * Copyright 2020 Google LLC * * 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.google.swarm.tokenization.common; @SuppressWarnings("serial") @AutoValue public abstract class ExtractColumnNamesTransform extends PTransform< PCollection<KV<String, FileIO.ReadableFile>>, PCollectionView<Map<String, List<String>>>> { public abstract FileType fileType(); @Nullable public abstract List<String> headers(); @AutoValue.Builder public abstract static class Builder { public abstract ExtractColumnNamesTransform.Builder setFileType(FileType fileType); public abstract ExtractColumnNamesTransform.Builder setHeaders(List<String> headers); public abstract ExtractColumnNamesTransform build(); } public static ExtractColumnNamesTransform.Builder newBuilder() { return new AutoValue_ExtractColumnNamesTransform.Builder(); } @Override public PCollectionView<Map<String, List<String>>> expand( PCollection<KV<String, FileIO.ReadableFile>> input) { PCollection<KV<String, List<String>>> readHeader; switch (fileType()) { case CSV: readHeader = input.apply("ReadHeader", ParDo.of(new CSVColumnNamesDoFn())); break; case AVRO:
// Path: src/main/java/com/google/swarm/tokenization/avro/AvroColumnNamesDoFn.java // public class AvroColumnNamesDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // public static final Logger LOG = LoggerFactory.getLogger(AvroColumnNamesDoFn.class); // // @ProcessElement // public void processElement(ProcessContext c) { // ReadableFile avroFile = c.element().getValue(); // try (AvroUtil.AvroSeekableByteChannel channel = AvroUtil.getChannel(avroFile)) { // DatumReader<GenericRecord> reader = new GenericDatumReader<>(); // DataFileReader<GenericRecord> fileReader = new DataFileReader<>(channel, reader); // List<String> fieldNames = new ArrayList<>(); // AvroUtil.flattenFieldNames(fileReader.getSchema(), fieldNames, ""); // // String fileName = c.element().getKey(); // c.output(KV.of(fileName, fieldNames)); // // LOG.info("Avro header fields: {}", String.join(",", fieldNames)); // } catch (IOException e) { // LOG.error("Failed to get Avro header values: {}", e.getMessage()); // throw new RuntimeException(e); // } // } // } // // Path: src/main/java/com/google/swarm/tokenization/common/Util.java // public enum FileType { // CSV, // AVRO, // JSON, // TXT // } // // Path: src/main/java/com/google/swarm/tokenization/json/JsonColumnNameDoFn.java // @SuppressWarnings("serial") // public class JsonColumnNameDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // private List<String> headers; // // public JsonColumnNameDoFn(List<String> headers) { // this.headers = headers; // } // // @ProcessElement // public void processContext(ProcessContext c) { // String fileName = c.element().getKey(); // c.output(KV.of(fileName, headers)); // } // } // // Path: src/main/java/com/google/swarm/tokenization/txt/TxtColumnNameDoFn.java // public class TxtColumnNameDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // private List<String> headers; // // public TxtColumnNameDoFn(List<String> headers) { // this.headers = headers; // } // // @ProcessElement // public void processContext(ProcessContext c) { // String fileName = c.element().getKey(); // c.output(KV.of(fileName, headers)); // } // } // Path: src/main/java/com/google/swarm/tokenization/common/ExtractColumnNamesTransform.java import com.google.auto.value.AutoValue; import com.google.swarm.tokenization.avro.AvroColumnNamesDoFn; import com.google.swarm.tokenization.common.Util.FileType; import com.google.swarm.tokenization.json.JsonColumnNameDoFn; import com.google.swarm.tokenization.txt.TxtColumnNameDoFn; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import org.apache.beam.sdk.io.FileIO; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.View; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionView; /* * Copyright 2020 Google LLC * * 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.google.swarm.tokenization.common; @SuppressWarnings("serial") @AutoValue public abstract class ExtractColumnNamesTransform extends PTransform< PCollection<KV<String, FileIO.ReadableFile>>, PCollectionView<Map<String, List<String>>>> { public abstract FileType fileType(); @Nullable public abstract List<String> headers(); @AutoValue.Builder public abstract static class Builder { public abstract ExtractColumnNamesTransform.Builder setFileType(FileType fileType); public abstract ExtractColumnNamesTransform.Builder setHeaders(List<String> headers); public abstract ExtractColumnNamesTransform build(); } public static ExtractColumnNamesTransform.Builder newBuilder() { return new AutoValue_ExtractColumnNamesTransform.Builder(); } @Override public PCollectionView<Map<String, List<String>>> expand( PCollection<KV<String, FileIO.ReadableFile>> input) { PCollection<KV<String, List<String>>> readHeader; switch (fileType()) { case CSV: readHeader = input.apply("ReadHeader", ParDo.of(new CSVColumnNamesDoFn())); break; case AVRO:
readHeader = input.apply("ReadHeader", ParDo.of(new AvroColumnNamesDoFn()));
GoogleCloudPlatform/dlp-dataflow-deidentification
src/main/java/com/google/swarm/tokenization/common/ExtractColumnNamesTransform.java
// Path: src/main/java/com/google/swarm/tokenization/avro/AvroColumnNamesDoFn.java // public class AvroColumnNamesDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // public static final Logger LOG = LoggerFactory.getLogger(AvroColumnNamesDoFn.class); // // @ProcessElement // public void processElement(ProcessContext c) { // ReadableFile avroFile = c.element().getValue(); // try (AvroUtil.AvroSeekableByteChannel channel = AvroUtil.getChannel(avroFile)) { // DatumReader<GenericRecord> reader = new GenericDatumReader<>(); // DataFileReader<GenericRecord> fileReader = new DataFileReader<>(channel, reader); // List<String> fieldNames = new ArrayList<>(); // AvroUtil.flattenFieldNames(fileReader.getSchema(), fieldNames, ""); // // String fileName = c.element().getKey(); // c.output(KV.of(fileName, fieldNames)); // // LOG.info("Avro header fields: {}", String.join(",", fieldNames)); // } catch (IOException e) { // LOG.error("Failed to get Avro header values: {}", e.getMessage()); // throw new RuntimeException(e); // } // } // } // // Path: src/main/java/com/google/swarm/tokenization/common/Util.java // public enum FileType { // CSV, // AVRO, // JSON, // TXT // } // // Path: src/main/java/com/google/swarm/tokenization/json/JsonColumnNameDoFn.java // @SuppressWarnings("serial") // public class JsonColumnNameDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // private List<String> headers; // // public JsonColumnNameDoFn(List<String> headers) { // this.headers = headers; // } // // @ProcessElement // public void processContext(ProcessContext c) { // String fileName = c.element().getKey(); // c.output(KV.of(fileName, headers)); // } // } // // Path: src/main/java/com/google/swarm/tokenization/txt/TxtColumnNameDoFn.java // public class TxtColumnNameDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // private List<String> headers; // // public TxtColumnNameDoFn(List<String> headers) { // this.headers = headers; // } // // @ProcessElement // public void processContext(ProcessContext c) { // String fileName = c.element().getKey(); // c.output(KV.of(fileName, headers)); // } // }
import com.google.auto.value.AutoValue; import com.google.swarm.tokenization.avro.AvroColumnNamesDoFn; import com.google.swarm.tokenization.common.Util.FileType; import com.google.swarm.tokenization.json.JsonColumnNameDoFn; import com.google.swarm.tokenization.txt.TxtColumnNameDoFn; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import org.apache.beam.sdk.io.FileIO; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.View; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionView;
/* * Copyright 2020 Google LLC * * 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.google.swarm.tokenization.common; @SuppressWarnings("serial") @AutoValue public abstract class ExtractColumnNamesTransform extends PTransform< PCollection<KV<String, FileIO.ReadableFile>>, PCollectionView<Map<String, List<String>>>> { public abstract FileType fileType(); @Nullable public abstract List<String> headers(); @AutoValue.Builder public abstract static class Builder { public abstract ExtractColumnNamesTransform.Builder setFileType(FileType fileType); public abstract ExtractColumnNamesTransform.Builder setHeaders(List<String> headers); public abstract ExtractColumnNamesTransform build(); } public static ExtractColumnNamesTransform.Builder newBuilder() { return new AutoValue_ExtractColumnNamesTransform.Builder(); } @Override public PCollectionView<Map<String, List<String>>> expand( PCollection<KV<String, FileIO.ReadableFile>> input) { PCollection<KV<String, List<String>>> readHeader; switch (fileType()) { case CSV: readHeader = input.apply("ReadHeader", ParDo.of(new CSVColumnNamesDoFn())); break; case AVRO: readHeader = input.apply("ReadHeader", ParDo.of(new AvroColumnNamesDoFn())); break; case JSON:
// Path: src/main/java/com/google/swarm/tokenization/avro/AvroColumnNamesDoFn.java // public class AvroColumnNamesDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // public static final Logger LOG = LoggerFactory.getLogger(AvroColumnNamesDoFn.class); // // @ProcessElement // public void processElement(ProcessContext c) { // ReadableFile avroFile = c.element().getValue(); // try (AvroUtil.AvroSeekableByteChannel channel = AvroUtil.getChannel(avroFile)) { // DatumReader<GenericRecord> reader = new GenericDatumReader<>(); // DataFileReader<GenericRecord> fileReader = new DataFileReader<>(channel, reader); // List<String> fieldNames = new ArrayList<>(); // AvroUtil.flattenFieldNames(fileReader.getSchema(), fieldNames, ""); // // String fileName = c.element().getKey(); // c.output(KV.of(fileName, fieldNames)); // // LOG.info("Avro header fields: {}", String.join(",", fieldNames)); // } catch (IOException e) { // LOG.error("Failed to get Avro header values: {}", e.getMessage()); // throw new RuntimeException(e); // } // } // } // // Path: src/main/java/com/google/swarm/tokenization/common/Util.java // public enum FileType { // CSV, // AVRO, // JSON, // TXT // } // // Path: src/main/java/com/google/swarm/tokenization/json/JsonColumnNameDoFn.java // @SuppressWarnings("serial") // public class JsonColumnNameDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // private List<String> headers; // // public JsonColumnNameDoFn(List<String> headers) { // this.headers = headers; // } // // @ProcessElement // public void processContext(ProcessContext c) { // String fileName = c.element().getKey(); // c.output(KV.of(fileName, headers)); // } // } // // Path: src/main/java/com/google/swarm/tokenization/txt/TxtColumnNameDoFn.java // public class TxtColumnNameDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // private List<String> headers; // // public TxtColumnNameDoFn(List<String> headers) { // this.headers = headers; // } // // @ProcessElement // public void processContext(ProcessContext c) { // String fileName = c.element().getKey(); // c.output(KV.of(fileName, headers)); // } // } // Path: src/main/java/com/google/swarm/tokenization/common/ExtractColumnNamesTransform.java import com.google.auto.value.AutoValue; import com.google.swarm.tokenization.avro.AvroColumnNamesDoFn; import com.google.swarm.tokenization.common.Util.FileType; import com.google.swarm.tokenization.json.JsonColumnNameDoFn; import com.google.swarm.tokenization.txt.TxtColumnNameDoFn; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import org.apache.beam.sdk.io.FileIO; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.View; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionView; /* * Copyright 2020 Google LLC * * 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.google.swarm.tokenization.common; @SuppressWarnings("serial") @AutoValue public abstract class ExtractColumnNamesTransform extends PTransform< PCollection<KV<String, FileIO.ReadableFile>>, PCollectionView<Map<String, List<String>>>> { public abstract FileType fileType(); @Nullable public abstract List<String> headers(); @AutoValue.Builder public abstract static class Builder { public abstract ExtractColumnNamesTransform.Builder setFileType(FileType fileType); public abstract ExtractColumnNamesTransform.Builder setHeaders(List<String> headers); public abstract ExtractColumnNamesTransform build(); } public static ExtractColumnNamesTransform.Builder newBuilder() { return new AutoValue_ExtractColumnNamesTransform.Builder(); } @Override public PCollectionView<Map<String, List<String>>> expand( PCollection<KV<String, FileIO.ReadableFile>> input) { PCollection<KV<String, List<String>>> readHeader; switch (fileType()) { case CSV: readHeader = input.apply("ReadHeader", ParDo.of(new CSVColumnNamesDoFn())); break; case AVRO: readHeader = input.apply("ReadHeader", ParDo.of(new AvroColumnNamesDoFn())); break; case JSON:
readHeader = input.apply("ReadHeader", ParDo.of(new JsonColumnNameDoFn(headers())));
GoogleCloudPlatform/dlp-dataflow-deidentification
src/main/java/com/google/swarm/tokenization/common/ExtractColumnNamesTransform.java
// Path: src/main/java/com/google/swarm/tokenization/avro/AvroColumnNamesDoFn.java // public class AvroColumnNamesDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // public static final Logger LOG = LoggerFactory.getLogger(AvroColumnNamesDoFn.class); // // @ProcessElement // public void processElement(ProcessContext c) { // ReadableFile avroFile = c.element().getValue(); // try (AvroUtil.AvroSeekableByteChannel channel = AvroUtil.getChannel(avroFile)) { // DatumReader<GenericRecord> reader = new GenericDatumReader<>(); // DataFileReader<GenericRecord> fileReader = new DataFileReader<>(channel, reader); // List<String> fieldNames = new ArrayList<>(); // AvroUtil.flattenFieldNames(fileReader.getSchema(), fieldNames, ""); // // String fileName = c.element().getKey(); // c.output(KV.of(fileName, fieldNames)); // // LOG.info("Avro header fields: {}", String.join(",", fieldNames)); // } catch (IOException e) { // LOG.error("Failed to get Avro header values: {}", e.getMessage()); // throw new RuntimeException(e); // } // } // } // // Path: src/main/java/com/google/swarm/tokenization/common/Util.java // public enum FileType { // CSV, // AVRO, // JSON, // TXT // } // // Path: src/main/java/com/google/swarm/tokenization/json/JsonColumnNameDoFn.java // @SuppressWarnings("serial") // public class JsonColumnNameDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // private List<String> headers; // // public JsonColumnNameDoFn(List<String> headers) { // this.headers = headers; // } // // @ProcessElement // public void processContext(ProcessContext c) { // String fileName = c.element().getKey(); // c.output(KV.of(fileName, headers)); // } // } // // Path: src/main/java/com/google/swarm/tokenization/txt/TxtColumnNameDoFn.java // public class TxtColumnNameDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // private List<String> headers; // // public TxtColumnNameDoFn(List<String> headers) { // this.headers = headers; // } // // @ProcessElement // public void processContext(ProcessContext c) { // String fileName = c.element().getKey(); // c.output(KV.of(fileName, headers)); // } // }
import com.google.auto.value.AutoValue; import com.google.swarm.tokenization.avro.AvroColumnNamesDoFn; import com.google.swarm.tokenization.common.Util.FileType; import com.google.swarm.tokenization.json.JsonColumnNameDoFn; import com.google.swarm.tokenization.txt.TxtColumnNameDoFn; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import org.apache.beam.sdk.io.FileIO; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.View; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionView;
public abstract ExtractColumnNamesTransform.Builder setFileType(FileType fileType); public abstract ExtractColumnNamesTransform.Builder setHeaders(List<String> headers); public abstract ExtractColumnNamesTransform build(); } public static ExtractColumnNamesTransform.Builder newBuilder() { return new AutoValue_ExtractColumnNamesTransform.Builder(); } @Override public PCollectionView<Map<String, List<String>>> expand( PCollection<KV<String, FileIO.ReadableFile>> input) { PCollection<KV<String, List<String>>> readHeader; switch (fileType()) { case CSV: readHeader = input.apply("ReadHeader", ParDo.of(new CSVColumnNamesDoFn())); break; case AVRO: readHeader = input.apply("ReadHeader", ParDo.of(new AvroColumnNamesDoFn())); break; case JSON: readHeader = input.apply("ReadHeader", ParDo.of(new JsonColumnNameDoFn(headers()))); break; case TXT:
// Path: src/main/java/com/google/swarm/tokenization/avro/AvroColumnNamesDoFn.java // public class AvroColumnNamesDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // public static final Logger LOG = LoggerFactory.getLogger(AvroColumnNamesDoFn.class); // // @ProcessElement // public void processElement(ProcessContext c) { // ReadableFile avroFile = c.element().getValue(); // try (AvroUtil.AvroSeekableByteChannel channel = AvroUtil.getChannel(avroFile)) { // DatumReader<GenericRecord> reader = new GenericDatumReader<>(); // DataFileReader<GenericRecord> fileReader = new DataFileReader<>(channel, reader); // List<String> fieldNames = new ArrayList<>(); // AvroUtil.flattenFieldNames(fileReader.getSchema(), fieldNames, ""); // // String fileName = c.element().getKey(); // c.output(KV.of(fileName, fieldNames)); // // LOG.info("Avro header fields: {}", String.join(",", fieldNames)); // } catch (IOException e) { // LOG.error("Failed to get Avro header values: {}", e.getMessage()); // throw new RuntimeException(e); // } // } // } // // Path: src/main/java/com/google/swarm/tokenization/common/Util.java // public enum FileType { // CSV, // AVRO, // JSON, // TXT // } // // Path: src/main/java/com/google/swarm/tokenization/json/JsonColumnNameDoFn.java // @SuppressWarnings("serial") // public class JsonColumnNameDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // private List<String> headers; // // public JsonColumnNameDoFn(List<String> headers) { // this.headers = headers; // } // // @ProcessElement // public void processContext(ProcessContext c) { // String fileName = c.element().getKey(); // c.output(KV.of(fileName, headers)); // } // } // // Path: src/main/java/com/google/swarm/tokenization/txt/TxtColumnNameDoFn.java // public class TxtColumnNameDoFn extends DoFn<KV<String, ReadableFile>, KV<String, List<String>>> { // // private List<String> headers; // // public TxtColumnNameDoFn(List<String> headers) { // this.headers = headers; // } // // @ProcessElement // public void processContext(ProcessContext c) { // String fileName = c.element().getKey(); // c.output(KV.of(fileName, headers)); // } // } // Path: src/main/java/com/google/swarm/tokenization/common/ExtractColumnNamesTransform.java import com.google.auto.value.AutoValue; import com.google.swarm.tokenization.avro.AvroColumnNamesDoFn; import com.google.swarm.tokenization.common.Util.FileType; import com.google.swarm.tokenization.json.JsonColumnNameDoFn; import com.google.swarm.tokenization.txt.TxtColumnNameDoFn; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import org.apache.beam.sdk.io.FileIO; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.View; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionView; public abstract ExtractColumnNamesTransform.Builder setFileType(FileType fileType); public abstract ExtractColumnNamesTransform.Builder setHeaders(List<String> headers); public abstract ExtractColumnNamesTransform build(); } public static ExtractColumnNamesTransform.Builder newBuilder() { return new AutoValue_ExtractColumnNamesTransform.Builder(); } @Override public PCollectionView<Map<String, List<String>>> expand( PCollection<KV<String, FileIO.ReadableFile>> input) { PCollection<KV<String, List<String>>> readHeader; switch (fileType()) { case CSV: readHeader = input.apply("ReadHeader", ParDo.of(new CSVColumnNamesDoFn())); break; case AVRO: readHeader = input.apply("ReadHeader", ParDo.of(new AvroColumnNamesDoFn())); break; case JSON: readHeader = input.apply("ReadHeader", ParDo.of(new JsonColumnNameDoFn(headers()))); break; case TXT:
readHeader = input.apply("ReadHeader", ParDo.of(new TxtColumnNameDoFn(headers())));
GoogleCloudPlatform/dlp-dataflow-deidentification
src/main/java/com/google/swarm/tokenization/DLPTextToBigQueryStreamingV2PipelineOptions.java
// Path: src/main/java/com/google/swarm/tokenization/common/Util.java // public enum DLPMethod { // INSPECT, // DEID, // REID // } // // Path: src/main/java/com/google/swarm/tokenization/common/Util.java // public enum FileType { // CSV, // AVRO, // JSON, // TXT // }
import com.google.privacy.dlp.v2.LocationName; import com.google.swarm.tokenization.common.Util.DLPMethod; import com.google.swarm.tokenization.common.Util.FileType; import java.util.List; import org.apache.beam.runners.dataflow.options.DataflowPipelineOptions; import org.apache.beam.sdk.io.aws.options.S3Options; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TypedRead.Method; import org.apache.beam.sdk.options.*;
/* * Copyright 2020 Google LLC * * 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.google.swarm.tokenization; public interface DLPTextToBigQueryStreamingV2PipelineOptions extends DataflowPipelineOptions, S3Options { @Validation.Required String getFilePattern(); void setFilePattern(String csvFilePattern); @Description("DLP Inspect Template Name") String getInspectTemplateName(); void setInspectTemplateName(String value); @Description("DLP DeIdentify Template Name") String getDeidentifyTemplateName(); void setDeidentifyTemplateName(String value); @Description("DLP method deid,inspect,reid") @Default.Enum("INSPECT")
// Path: src/main/java/com/google/swarm/tokenization/common/Util.java // public enum DLPMethod { // INSPECT, // DEID, // REID // } // // Path: src/main/java/com/google/swarm/tokenization/common/Util.java // public enum FileType { // CSV, // AVRO, // JSON, // TXT // } // Path: src/main/java/com/google/swarm/tokenization/DLPTextToBigQueryStreamingV2PipelineOptions.java import com.google.privacy.dlp.v2.LocationName; import com.google.swarm.tokenization.common.Util.DLPMethod; import com.google.swarm.tokenization.common.Util.FileType; import java.util.List; import org.apache.beam.runners.dataflow.options.DataflowPipelineOptions; import org.apache.beam.sdk.io.aws.options.S3Options; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TypedRead.Method; import org.apache.beam.sdk.options.*; /* * Copyright 2020 Google LLC * * 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.google.swarm.tokenization; public interface DLPTextToBigQueryStreamingV2PipelineOptions extends DataflowPipelineOptions, S3Options { @Validation.Required String getFilePattern(); void setFilePattern(String csvFilePattern); @Description("DLP Inspect Template Name") String getInspectTemplateName(); void setInspectTemplateName(String value); @Description("DLP DeIdentify Template Name") String getDeidentifyTemplateName(); void setDeidentifyTemplateName(String value); @Description("DLP method deid,inspect,reid") @Default.Enum("INSPECT")
DLPMethod getDLPMethod();
GoogleCloudPlatform/dlp-dataflow-deidentification
src/main/java/com/google/swarm/tokenization/DLPTextToBigQueryStreamingV2PipelineOptions.java
// Path: src/main/java/com/google/swarm/tokenization/common/Util.java // public enum DLPMethod { // INSPECT, // DEID, // REID // } // // Path: src/main/java/com/google/swarm/tokenization/common/Util.java // public enum FileType { // CSV, // AVRO, // JSON, // TXT // }
import com.google.privacy.dlp.v2.LocationName; import com.google.swarm.tokenization.common.Util.DLPMethod; import com.google.swarm.tokenization.common.Util.FileType; import java.util.List; import org.apache.beam.runners.dataflow.options.DataflowPipelineOptions; import org.apache.beam.sdk.io.aws.options.S3Options; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TypedRead.Method; import org.apache.beam.sdk.options.*;
Method getReadMethod(); void setReadMethod(Method method); @Description("Query") String getQueryPath(); void setQueryPath(String topic); @Description("Topic to use for reid result") String getTopic(); void setTopic(String topic); @Default.Integer(900 * 1000) Integer getSplitSize(); void setSplitSize(Integer value); @Description("DLP Table Headers- Required for Json type") List<String> getHeaders(); void setHeaders(List<String> topic); @Description("Number of shards for DLP request batches. " + "Can be used to controls parallelism of DLP requests.") @Default.Integer(100) int getNumShardsPerDLPRequestBatching(); void setNumShardsPerDLPRequestBatching(int value);
// Path: src/main/java/com/google/swarm/tokenization/common/Util.java // public enum DLPMethod { // INSPECT, // DEID, // REID // } // // Path: src/main/java/com/google/swarm/tokenization/common/Util.java // public enum FileType { // CSV, // AVRO, // JSON, // TXT // } // Path: src/main/java/com/google/swarm/tokenization/DLPTextToBigQueryStreamingV2PipelineOptions.java import com.google.privacy.dlp.v2.LocationName; import com.google.swarm.tokenization.common.Util.DLPMethod; import com.google.swarm.tokenization.common.Util.FileType; import java.util.List; import org.apache.beam.runners.dataflow.options.DataflowPipelineOptions; import org.apache.beam.sdk.io.aws.options.S3Options; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO; import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TypedRead.Method; import org.apache.beam.sdk.options.*; Method getReadMethod(); void setReadMethod(Method method); @Description("Query") String getQueryPath(); void setQueryPath(String topic); @Description("Topic to use for reid result") String getTopic(); void setTopic(String topic); @Default.Integer(900 * 1000) Integer getSplitSize(); void setSplitSize(Integer value); @Description("DLP Table Headers- Required for Json type") List<String> getHeaders(); void setHeaders(List<String> topic); @Description("Number of shards for DLP request batches. " + "Can be used to controls parallelism of DLP requests.") @Default.Integer(100) int getNumShardsPerDLPRequestBatching(); void setNumShardsPerDLPRequestBatching(int value);
class FileTypeFactory implements DefaultValueFactory<FileType> {
GoogleCloudPlatform/dlp-dataflow-deidentification
src/test/java/com/google/swarm/tokenization/avro/ConvertAvroRecordToDlpRowDoFnTest.java
// Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static List<Table.Row> generateDLPRows(long count) { // ArrayList<Table.Row> result = new ArrayList<>(); // for (int i = 0; i < count; i++) { // Table.Row.Builder rowBuilder = Table.Row.newBuilder(); // Value user = Value.newBuilder().setStringValue("abcd").build(); // Value message = Value.newBuilder().setStringValue("Message #" + i).build(); // Table.Row row = rowBuilder.addValues(user).addValues(message).build(); // result.add(row); // } // return result; // } // // Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static List<GenericRecord> generateGenericRecords(long count) { // ArrayList<GenericRecord> result = new ArrayList<>(); // GenericRecordBuilder builder = new GenericRecordBuilder(schema); // for (int i = 0; i < count; i++) { // GenericRecord record = builder.set("user", "abcd").set("message", "Message #" + i).build(); // result.add(record); // } // return result; // } // // Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static final Schema schema = // SchemaBuilder.record("root") // .fields() // .name("user") // .type() // .stringType() // .noDefault() // .name("message") // .type() // .stringType() // .noDefault() // .endRecord();
import org.apache.beam.sdk.transforms.WithKeys; import org.apache.beam.sdk.values.PCollection; import org.junit.Rule; import org.junit.Test; import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.generateDLPRows; import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.generateGenericRecords; import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.schema; import com.google.privacy.dlp.v2.Table; import java.util.List; import org.apache.avro.generic.GenericRecord; import org.apache.beam.sdk.coders.AvroCoder; import org.apache.beam.sdk.coders.KvCoder; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.Values;
/* * Copyright 2020 Google LLC * * 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.google.swarm.tokenization.avro; public class ConvertAvroRecordToDlpRowDoFnTest { @Rule public transient TestPipeline pipeline = TestPipeline.create(); @Test public void testConvertAvroRecordToDlpRowDoFn() { int numRecords = 10;
// Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static List<Table.Row> generateDLPRows(long count) { // ArrayList<Table.Row> result = new ArrayList<>(); // for (int i = 0; i < count; i++) { // Table.Row.Builder rowBuilder = Table.Row.newBuilder(); // Value user = Value.newBuilder().setStringValue("abcd").build(); // Value message = Value.newBuilder().setStringValue("Message #" + i).build(); // Table.Row row = rowBuilder.addValues(user).addValues(message).build(); // result.add(row); // } // return result; // } // // Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static List<GenericRecord> generateGenericRecords(long count) { // ArrayList<GenericRecord> result = new ArrayList<>(); // GenericRecordBuilder builder = new GenericRecordBuilder(schema); // for (int i = 0; i < count; i++) { // GenericRecord record = builder.set("user", "abcd").set("message", "Message #" + i).build(); // result.add(record); // } // return result; // } // // Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static final Schema schema = // SchemaBuilder.record("root") // .fields() // .name("user") // .type() // .stringType() // .noDefault() // .name("message") // .type() // .stringType() // .noDefault() // .endRecord(); // Path: src/test/java/com/google/swarm/tokenization/avro/ConvertAvroRecordToDlpRowDoFnTest.java import org.apache.beam.sdk.transforms.WithKeys; import org.apache.beam.sdk.values.PCollection; import org.junit.Rule; import org.junit.Test; import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.generateDLPRows; import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.generateGenericRecords; import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.schema; import com.google.privacy.dlp.v2.Table; import java.util.List; import org.apache.avro.generic.GenericRecord; import org.apache.beam.sdk.coders.AvroCoder; import org.apache.beam.sdk.coders.KvCoder; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.Values; /* * Copyright 2020 Google LLC * * 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.google.swarm.tokenization.avro; public class ConvertAvroRecordToDlpRowDoFnTest { @Rule public transient TestPipeline pipeline = TestPipeline.create(); @Test public void testConvertAvroRecordToDlpRowDoFn() { int numRecords = 10;
List<GenericRecord> records = generateGenericRecords(numRecords);
GoogleCloudPlatform/dlp-dataflow-deidentification
src/test/java/com/google/swarm/tokenization/avro/ConvertAvroRecordToDlpRowDoFnTest.java
// Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static List<Table.Row> generateDLPRows(long count) { // ArrayList<Table.Row> result = new ArrayList<>(); // for (int i = 0; i < count; i++) { // Table.Row.Builder rowBuilder = Table.Row.newBuilder(); // Value user = Value.newBuilder().setStringValue("abcd").build(); // Value message = Value.newBuilder().setStringValue("Message #" + i).build(); // Table.Row row = rowBuilder.addValues(user).addValues(message).build(); // result.add(row); // } // return result; // } // // Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static List<GenericRecord> generateGenericRecords(long count) { // ArrayList<GenericRecord> result = new ArrayList<>(); // GenericRecordBuilder builder = new GenericRecordBuilder(schema); // for (int i = 0; i < count; i++) { // GenericRecord record = builder.set("user", "abcd").set("message", "Message #" + i).build(); // result.add(record); // } // return result; // } // // Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static final Schema schema = // SchemaBuilder.record("root") // .fields() // .name("user") // .type() // .stringType() // .noDefault() // .name("message") // .type() // .stringType() // .noDefault() // .endRecord();
import org.apache.beam.sdk.transforms.WithKeys; import org.apache.beam.sdk.values.PCollection; import org.junit.Rule; import org.junit.Test; import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.generateDLPRows; import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.generateGenericRecords; import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.schema; import com.google.privacy.dlp.v2.Table; import java.util.List; import org.apache.avro.generic.GenericRecord; import org.apache.beam.sdk.coders.AvroCoder; import org.apache.beam.sdk.coders.KvCoder; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.Values;
/* * Copyright 2020 Google LLC * * 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.google.swarm.tokenization.avro; public class ConvertAvroRecordToDlpRowDoFnTest { @Rule public transient TestPipeline pipeline = TestPipeline.create(); @Test public void testConvertAvroRecordToDlpRowDoFn() { int numRecords = 10; List<GenericRecord> records = generateGenericRecords(numRecords);
// Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static List<Table.Row> generateDLPRows(long count) { // ArrayList<Table.Row> result = new ArrayList<>(); // for (int i = 0; i < count; i++) { // Table.Row.Builder rowBuilder = Table.Row.newBuilder(); // Value user = Value.newBuilder().setStringValue("abcd").build(); // Value message = Value.newBuilder().setStringValue("Message #" + i).build(); // Table.Row row = rowBuilder.addValues(user).addValues(message).build(); // result.add(row); // } // return result; // } // // Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static List<GenericRecord> generateGenericRecords(long count) { // ArrayList<GenericRecord> result = new ArrayList<>(); // GenericRecordBuilder builder = new GenericRecordBuilder(schema); // for (int i = 0; i < count; i++) { // GenericRecord record = builder.set("user", "abcd").set("message", "Message #" + i).build(); // result.add(record); // } // return result; // } // // Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static final Schema schema = // SchemaBuilder.record("root") // .fields() // .name("user") // .type() // .stringType() // .noDefault() // .name("message") // .type() // .stringType() // .noDefault() // .endRecord(); // Path: src/test/java/com/google/swarm/tokenization/avro/ConvertAvroRecordToDlpRowDoFnTest.java import org.apache.beam.sdk.transforms.WithKeys; import org.apache.beam.sdk.values.PCollection; import org.junit.Rule; import org.junit.Test; import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.generateDLPRows; import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.generateGenericRecords; import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.schema; import com.google.privacy.dlp.v2.Table; import java.util.List; import org.apache.avro.generic.GenericRecord; import org.apache.beam.sdk.coders.AvroCoder; import org.apache.beam.sdk.coders.KvCoder; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.Values; /* * Copyright 2020 Google LLC * * 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.google.swarm.tokenization.avro; public class ConvertAvroRecordToDlpRowDoFnTest { @Rule public transient TestPipeline pipeline = TestPipeline.create(); @Test public void testConvertAvroRecordToDlpRowDoFn() { int numRecords = 10; List<GenericRecord> records = generateGenericRecords(numRecords);
List<Table.Row> rows = generateDLPRows(numRecords);
GoogleCloudPlatform/dlp-dataflow-deidentification
src/test/java/com/google/swarm/tokenization/avro/ConvertAvroRecordToDlpRowDoFnTest.java
// Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static List<Table.Row> generateDLPRows(long count) { // ArrayList<Table.Row> result = new ArrayList<>(); // for (int i = 0; i < count; i++) { // Table.Row.Builder rowBuilder = Table.Row.newBuilder(); // Value user = Value.newBuilder().setStringValue("abcd").build(); // Value message = Value.newBuilder().setStringValue("Message #" + i).build(); // Table.Row row = rowBuilder.addValues(user).addValues(message).build(); // result.add(row); // } // return result; // } // // Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static List<GenericRecord> generateGenericRecords(long count) { // ArrayList<GenericRecord> result = new ArrayList<>(); // GenericRecordBuilder builder = new GenericRecordBuilder(schema); // for (int i = 0; i < count; i++) { // GenericRecord record = builder.set("user", "abcd").set("message", "Message #" + i).build(); // result.add(record); // } // return result; // } // // Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static final Schema schema = // SchemaBuilder.record("root") // .fields() // .name("user") // .type() // .stringType() // .noDefault() // .name("message") // .type() // .stringType() // .noDefault() // .endRecord();
import org.apache.beam.sdk.transforms.WithKeys; import org.apache.beam.sdk.values.PCollection; import org.junit.Rule; import org.junit.Test; import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.generateDLPRows; import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.generateGenericRecords; import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.schema; import com.google.privacy.dlp.v2.Table; import java.util.List; import org.apache.avro.generic.GenericRecord; import org.apache.beam.sdk.coders.AvroCoder; import org.apache.beam.sdk.coders.KvCoder; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.Values;
/* * Copyright 2020 Google LLC * * 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.google.swarm.tokenization.avro; public class ConvertAvroRecordToDlpRowDoFnTest { @Rule public transient TestPipeline pipeline = TestPipeline.create(); @Test public void testConvertAvroRecordToDlpRowDoFn() { int numRecords = 10; List<GenericRecord> records = generateGenericRecords(numRecords); List<Table.Row> rows = generateDLPRows(numRecords); PCollection<Table.Row> results = pipeline
// Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static List<Table.Row> generateDLPRows(long count) { // ArrayList<Table.Row> result = new ArrayList<>(); // for (int i = 0; i < count; i++) { // Table.Row.Builder rowBuilder = Table.Row.newBuilder(); // Value user = Value.newBuilder().setStringValue("abcd").build(); // Value message = Value.newBuilder().setStringValue("Message #" + i).build(); // Table.Row row = rowBuilder.addValues(user).addValues(message).build(); // result.add(row); // } // return result; // } // // Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static List<GenericRecord> generateGenericRecords(long count) { // ArrayList<GenericRecord> result = new ArrayList<>(); // GenericRecordBuilder builder = new GenericRecordBuilder(schema); // for (int i = 0; i < count; i++) { // GenericRecord record = builder.set("user", "abcd").set("message", "Message #" + i).build(); // result.add(record); // } // return result; // } // // Path: src/test/java/com/google/swarm/tokenization/avro/AvroReaderSplittableDoFnTest.java // public static final Schema schema = // SchemaBuilder.record("root") // .fields() // .name("user") // .type() // .stringType() // .noDefault() // .name("message") // .type() // .stringType() // .noDefault() // .endRecord(); // Path: src/test/java/com/google/swarm/tokenization/avro/ConvertAvroRecordToDlpRowDoFnTest.java import org.apache.beam.sdk.transforms.WithKeys; import org.apache.beam.sdk.values.PCollection; import org.junit.Rule; import org.junit.Test; import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.generateDLPRows; import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.generateGenericRecords; import static com.google.swarm.tokenization.avro.AvroReaderSplittableDoFnTest.schema; import com.google.privacy.dlp.v2.Table; import java.util.List; import org.apache.avro.generic.GenericRecord; import org.apache.beam.sdk.coders.AvroCoder; import org.apache.beam.sdk.coders.KvCoder; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.Values; /* * Copyright 2020 Google LLC * * 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.google.swarm.tokenization.avro; public class ConvertAvroRecordToDlpRowDoFnTest { @Rule public transient TestPipeline pipeline = TestPipeline.create(); @Test public void testConvertAvroRecordToDlpRowDoFn() { int numRecords = 10; List<GenericRecord> records = generateGenericRecords(numRecords); List<Table.Row> rows = generateDLPRows(numRecords); PCollection<Table.Row> results = pipeline
.apply(Create.of(records).withCoder(AvroCoder.of(schema)))
once2go/mvp.recar.io
app/src/main/java/io/recar/once2go/easynavi/util/MusicPlayerManager.java
// Path: app/src/main/java/io/recar/once2go/easynavi/data/Mp3Song.java // public class Mp3Song { // // private long id; // private String title; // private String artist; // private String duration; // // public Mp3Song(long id, String title, String artist, String duration) { // this.id = id; // this.title = title; // this.artist = artist; // this.duration = duration; // } // // public long getId() { // return id; // } // // public String getTitle() { // return title; // } // // public String getArtist() { // return artist; // } // // public String getDuration() { // return duration; // } // } // // Path: app/src/main/java/io/recar/once2go/easynavi/interfaces/MusicPlayerControlsListener.java // public interface MusicPlayerControlsListener { // // void play(); // // void playPrevious(); // // void playNext(); // // void pause(); // // void volumeUp(); // // void volumeDown(); // // void stop(); // } // // Path: app/src/main/java/io/recar/once2go/easynavi/interfaces/MusicPlayerListener.java // public interface MusicPlayerListener { // // void playFinished(); // // void playingNow(String title, String artist, String duration); // }
import android.content.ContentUris; import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.support.annotation.NonNull; import java.io.IOException; import java.util.List; import io.recar.once2go.easynavi.data.Mp3Song; import io.recar.once2go.easynavi.interfaces.MusicPlayerControlsListener; import io.recar.once2go.easynavi.interfaces.MusicPlayerListener;
package io.recar.once2go.easynavi.util; /** * Created by once2go on 11.04.16. */ public class MusicPlayerManager implements MusicPlayerControlsListener { private Context mContext;
// Path: app/src/main/java/io/recar/once2go/easynavi/data/Mp3Song.java // public class Mp3Song { // // private long id; // private String title; // private String artist; // private String duration; // // public Mp3Song(long id, String title, String artist, String duration) { // this.id = id; // this.title = title; // this.artist = artist; // this.duration = duration; // } // // public long getId() { // return id; // } // // public String getTitle() { // return title; // } // // public String getArtist() { // return artist; // } // // public String getDuration() { // return duration; // } // } // // Path: app/src/main/java/io/recar/once2go/easynavi/interfaces/MusicPlayerControlsListener.java // public interface MusicPlayerControlsListener { // // void play(); // // void playPrevious(); // // void playNext(); // // void pause(); // // void volumeUp(); // // void volumeDown(); // // void stop(); // } // // Path: app/src/main/java/io/recar/once2go/easynavi/interfaces/MusicPlayerListener.java // public interface MusicPlayerListener { // // void playFinished(); // // void playingNow(String title, String artist, String duration); // } // Path: app/src/main/java/io/recar/once2go/easynavi/util/MusicPlayerManager.java import android.content.ContentUris; import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.support.annotation.NonNull; import java.io.IOException; import java.util.List; import io.recar.once2go.easynavi.data.Mp3Song; import io.recar.once2go.easynavi.interfaces.MusicPlayerControlsListener; import io.recar.once2go.easynavi.interfaces.MusicPlayerListener; package io.recar.once2go.easynavi.util; /** * Created by once2go on 11.04.16. */ public class MusicPlayerManager implements MusicPlayerControlsListener { private Context mContext;
private List<Mp3Song> mMp3SongList;
once2go/mvp.recar.io
app/src/main/java/io/recar/once2go/easynavi/util/MusicPlayerManager.java
// Path: app/src/main/java/io/recar/once2go/easynavi/data/Mp3Song.java // public class Mp3Song { // // private long id; // private String title; // private String artist; // private String duration; // // public Mp3Song(long id, String title, String artist, String duration) { // this.id = id; // this.title = title; // this.artist = artist; // this.duration = duration; // } // // public long getId() { // return id; // } // // public String getTitle() { // return title; // } // // public String getArtist() { // return artist; // } // // public String getDuration() { // return duration; // } // } // // Path: app/src/main/java/io/recar/once2go/easynavi/interfaces/MusicPlayerControlsListener.java // public interface MusicPlayerControlsListener { // // void play(); // // void playPrevious(); // // void playNext(); // // void pause(); // // void volumeUp(); // // void volumeDown(); // // void stop(); // } // // Path: app/src/main/java/io/recar/once2go/easynavi/interfaces/MusicPlayerListener.java // public interface MusicPlayerListener { // // void playFinished(); // // void playingNow(String title, String artist, String duration); // }
import android.content.ContentUris; import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.support.annotation.NonNull; import java.io.IOException; import java.util.List; import io.recar.once2go.easynavi.data.Mp3Song; import io.recar.once2go.easynavi.interfaces.MusicPlayerControlsListener; import io.recar.once2go.easynavi.interfaces.MusicPlayerListener;
package io.recar.once2go.easynavi.util; /** * Created by once2go on 11.04.16. */ public class MusicPlayerManager implements MusicPlayerControlsListener { private Context mContext; private List<Mp3Song> mMp3SongList;
// Path: app/src/main/java/io/recar/once2go/easynavi/data/Mp3Song.java // public class Mp3Song { // // private long id; // private String title; // private String artist; // private String duration; // // public Mp3Song(long id, String title, String artist, String duration) { // this.id = id; // this.title = title; // this.artist = artist; // this.duration = duration; // } // // public long getId() { // return id; // } // // public String getTitle() { // return title; // } // // public String getArtist() { // return artist; // } // // public String getDuration() { // return duration; // } // } // // Path: app/src/main/java/io/recar/once2go/easynavi/interfaces/MusicPlayerControlsListener.java // public interface MusicPlayerControlsListener { // // void play(); // // void playPrevious(); // // void playNext(); // // void pause(); // // void volumeUp(); // // void volumeDown(); // // void stop(); // } // // Path: app/src/main/java/io/recar/once2go/easynavi/interfaces/MusicPlayerListener.java // public interface MusicPlayerListener { // // void playFinished(); // // void playingNow(String title, String artist, String duration); // } // Path: app/src/main/java/io/recar/once2go/easynavi/util/MusicPlayerManager.java import android.content.ContentUris; import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.support.annotation.NonNull; import java.io.IOException; import java.util.List; import io.recar.once2go.easynavi.data.Mp3Song; import io.recar.once2go.easynavi.interfaces.MusicPlayerControlsListener; import io.recar.once2go.easynavi.interfaces.MusicPlayerListener; package io.recar.once2go.easynavi.util; /** * Created by once2go on 11.04.16. */ public class MusicPlayerManager implements MusicPlayerControlsListener { private Context mContext; private List<Mp3Song> mMp3SongList;
private MusicPlayerListener mMusicPlayerListener;
once2go/mvp.recar.io
app/src/main/java/io/recar/once2go/easynavi/MapsActivity.java
// Path: app/src/main/java/io/recar/once2go/easynavi/framents/MusicPlayerFragment.java // public class MusicPlayerFragment extends Fragment implements View.OnClickListener, MusicPlayerListener { // // private TextView mSongTitle; // private TextView mSongArtist; // private TextView mSongDuration; // // private ImageButton mPlay; // private ImageButton mPrevious; // private ImageButton mNext; // private ImageButton mVolumeUp; // private ImageButton getmVolumeDown; // // private boolean isPlay; // // private MusicPlayerControlsListener mMusicPlayerControlsListener; // // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.music_player_layout, container, false); // assigneView(view); // MusicPlayerManager musicPlayerManager = new MusicPlayerManager(getActivity(), this); // mMusicPlayerControlsListener = musicPlayerManager.getMusicControlsListener(); // return view; // } // // private void assigneView(View view) { // mSongTitle = (TextView) view.findViewById(R.id.player_song_title); // mSongArtist = (TextView) view.findViewById(R.id.player_song_artist); // mSongDuration = (TextView) view.findViewById(R.id.player_song_duration); // // mPlay = (ImageButton) view.findViewById(R.id.player_song_play); // mPrevious = (ImageButton) view.findViewById(R.id.player_song_previous); // mNext = (ImageButton) view.findViewById(R.id.player_song_next); // // mVolumeUp = (ImageButton) view.findViewById(R.id.player_volume_up); // getmVolumeDown = (ImageButton) view.findViewById(R.id.player_volume_down); // // // mPlay.setOnClickListener(this); // mPrevious.setOnClickListener(this); // mNext.setOnClickListener(this); // mVolumeUp.setOnClickListener(this); // getmVolumeDown.setOnClickListener(this); // } // // @Override // public void onClick(View v) { // switch (v.getId()) { // case R.id.player_song_play: // if (isPlay){ // isPlay = false; // mPlay.setImageResource(android.R.drawable.ic_media_pause); // } else { // isPlay = true; // mPlay.setImageResource(android.R.drawable.ic_media_play); // } // if (mMusicPlayerControlsListener != null) { // mMusicPlayerControlsListener.play(); // } // break; // case R.id.player_song_previous: // if (mMusicPlayerControlsListener != null) { // mMusicPlayerControlsListener.playPrevious(); // } // break; // case R.id.player_song_next: // if (mMusicPlayerControlsListener != null) { // mMusicPlayerControlsListener.playNext(); // } // break; // case R.id.player_volume_up: // if (mMusicPlayerControlsListener != null) { // mMusicPlayerControlsListener.volumeUp(); // } // break; // case R.id.player_volume_down: // if (mMusicPlayerControlsListener != null) { // mMusicPlayerControlsListener.volumeDown(); // } // break; // } // // } // // @Override // public void onPause() { // if (mMusicPlayerControlsListener != null) { // mMusicPlayerControlsListener.stop(); // } // super.onPause(); // } // // @Override // public void onDestroy() { // if (mMusicPlayerControlsListener != null) { // mMusicPlayerControlsListener.stop(); // } // super.onDestroy(); // } // // @Override // public void playFinished() { // // } // // @Override // public void playingNow(String title, String artist, String duration) { // mSongTitle.setText(title); // mSongArtist.setText(artist); // mSongDuration.setText(duration); // } // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.FragmentActivity; import android.view.View; import android.view.WindowManager; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import io.recar.once2go.easynavi.framents.MusicPlayerFragment;
package io.recar.once2go.easynavi; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener , View.OnSystemUiVisibilityChangeListener{ private GoogleMap mMap; private LocationManager mlocationManager; private MarkerOptions mCarLocationMarker; private Bitmap mCarMarker; private static final int AUTO_HIDE_DELAY_MILLIS = 5000; private View mDecorView; private final Handler mHideHandler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.louncher_container); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); mlocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mlocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 5, this); mCarMarker = BitmapFactory.decodeResource(getResources(), R.drawable.car_icon); mCarMarker = Bitmap.createScaledBitmap(mCarMarker, 48, 48, false); getSupportFragmentManager().beginTransaction()
// Path: app/src/main/java/io/recar/once2go/easynavi/framents/MusicPlayerFragment.java // public class MusicPlayerFragment extends Fragment implements View.OnClickListener, MusicPlayerListener { // // private TextView mSongTitle; // private TextView mSongArtist; // private TextView mSongDuration; // // private ImageButton mPlay; // private ImageButton mPrevious; // private ImageButton mNext; // private ImageButton mVolumeUp; // private ImageButton getmVolumeDown; // // private boolean isPlay; // // private MusicPlayerControlsListener mMusicPlayerControlsListener; // // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.music_player_layout, container, false); // assigneView(view); // MusicPlayerManager musicPlayerManager = new MusicPlayerManager(getActivity(), this); // mMusicPlayerControlsListener = musicPlayerManager.getMusicControlsListener(); // return view; // } // // private void assigneView(View view) { // mSongTitle = (TextView) view.findViewById(R.id.player_song_title); // mSongArtist = (TextView) view.findViewById(R.id.player_song_artist); // mSongDuration = (TextView) view.findViewById(R.id.player_song_duration); // // mPlay = (ImageButton) view.findViewById(R.id.player_song_play); // mPrevious = (ImageButton) view.findViewById(R.id.player_song_previous); // mNext = (ImageButton) view.findViewById(R.id.player_song_next); // // mVolumeUp = (ImageButton) view.findViewById(R.id.player_volume_up); // getmVolumeDown = (ImageButton) view.findViewById(R.id.player_volume_down); // // // mPlay.setOnClickListener(this); // mPrevious.setOnClickListener(this); // mNext.setOnClickListener(this); // mVolumeUp.setOnClickListener(this); // getmVolumeDown.setOnClickListener(this); // } // // @Override // public void onClick(View v) { // switch (v.getId()) { // case R.id.player_song_play: // if (isPlay){ // isPlay = false; // mPlay.setImageResource(android.R.drawable.ic_media_pause); // } else { // isPlay = true; // mPlay.setImageResource(android.R.drawable.ic_media_play); // } // if (mMusicPlayerControlsListener != null) { // mMusicPlayerControlsListener.play(); // } // break; // case R.id.player_song_previous: // if (mMusicPlayerControlsListener != null) { // mMusicPlayerControlsListener.playPrevious(); // } // break; // case R.id.player_song_next: // if (mMusicPlayerControlsListener != null) { // mMusicPlayerControlsListener.playNext(); // } // break; // case R.id.player_volume_up: // if (mMusicPlayerControlsListener != null) { // mMusicPlayerControlsListener.volumeUp(); // } // break; // case R.id.player_volume_down: // if (mMusicPlayerControlsListener != null) { // mMusicPlayerControlsListener.volumeDown(); // } // break; // } // // } // // @Override // public void onPause() { // if (mMusicPlayerControlsListener != null) { // mMusicPlayerControlsListener.stop(); // } // super.onPause(); // } // // @Override // public void onDestroy() { // if (mMusicPlayerControlsListener != null) { // mMusicPlayerControlsListener.stop(); // } // super.onDestroy(); // } // // @Override // public void playFinished() { // // } // // @Override // public void playingNow(String title, String artist, String duration) { // mSongTitle.setText(title); // mSongArtist.setText(artist); // mSongDuration.setText(duration); // } // } // Path: app/src/main/java/io/recar/once2go/easynavi/MapsActivity.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.FragmentActivity; import android.view.View; import android.view.WindowManager; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import io.recar.once2go.easynavi.framents.MusicPlayerFragment; package io.recar.once2go.easynavi; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener , View.OnSystemUiVisibilityChangeListener{ private GoogleMap mMap; private LocationManager mlocationManager; private MarkerOptions mCarLocationMarker; private Bitmap mCarMarker; private static final int AUTO_HIDE_DELAY_MILLIS = 5000; private View mDecorView; private final Handler mHideHandler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.louncher_container); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); mlocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mlocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 5, this); mCarMarker = BitmapFactory.decodeResource(getResources(), R.drawable.car_icon); mCarMarker = Bitmap.createScaledBitmap(mCarMarker, 48, 48, false); getSupportFragmentManager().beginTransaction()
.replace(R.id.player_container, new MusicPlayerFragment())
once2go/mvp.recar.io
app/src/main/java/io/recar/once2go/easynavi/framents/MusicPlayerFragment.java
// Path: app/src/main/java/io/recar/once2go/easynavi/interfaces/MusicPlayerControlsListener.java // public interface MusicPlayerControlsListener { // // void play(); // // void playPrevious(); // // void playNext(); // // void pause(); // // void volumeUp(); // // void volumeDown(); // // void stop(); // } // // Path: app/src/main/java/io/recar/once2go/easynavi/interfaces/MusicPlayerListener.java // public interface MusicPlayerListener { // // void playFinished(); // // void playingNow(String title, String artist, String duration); // } // // Path: app/src/main/java/io/recar/once2go/easynavi/util/MusicPlayerManager.java // public class MusicPlayerManager implements MusicPlayerControlsListener { // // private Context mContext; // private List<Mp3Song> mMp3SongList; // private MusicPlayerListener mMusicPlayerListener; // private MediaPlayer mMediaPlayer; // private int curentSong; // // float mInitVolume = 0.5f; // // public MusicPlayerManager(Context context, @NonNull MusicPlayerListener musicPlayerListener) { // mContext = context; // mMp3SongList = MusicSearchHelper.getMusicList(context); // mMusicPlayerListener = musicPlayerListener; // } // // // @Override // public void play() { // if(mMediaPlayer != null && mMediaPlayer.isPlaying()){ // releaseMediaPlayer(); // } else { // playMusic(curentSong); // } // } // // @Override // public void playPrevious() { // releaseMediaPlayer(); // curentSong--; // if (curentSong < 0) { // curentSong = 0; // } // playMusic(curentSong); // } // // @Override // public void playNext() { // releaseMediaPlayer(); // curentSong++; // if (curentSong > mMp3SongList.size() - 1) { // curentSong = 0; // } // playMusic(curentSong); // } // // @Override // public void pause() { // // } // // @Override // public void volumeUp() { // if (mMediaPlayer!=null && mInitVolume < 1.0f) { // mInitVolume += 0.1f; // mMediaPlayer.setVolume(mInitVolume, mInitVolume); // } // } // // @Override // public void volumeDown() { // if (mMediaPlayer!=null && mInitVolume > 0) { // mInitVolume -= 0.1f; // mMediaPlayer.setVolume(mInitVolume, mInitVolume); // } // } // // @Override // public void stop() { // releaseMediaPlayer(); // } // // public MusicPlayerControlsListener getMusicControlsListener() { // return this; // } // // private void playMusic(int id) { // Uri contentUri = ContentUris.withAppendedId( // android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mMp3SongList.get(id).getId()); // mMediaPlayer = new MediaPlayer(); // mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); // mMediaPlayer.setVolume(mInitVolume, mInitVolume); // try { // mMediaPlayer.setDataSource(mContext, contentUri); // } catch (IOException e) { // e.printStackTrace(); // } // mMediaPlayer.prepareAsync(); // mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { // @Override // public void onPrepared(MediaPlayer mp) { // mp.start(); // String artist = mMp3SongList.get(curentSong).getArtist(); // String title = mMp3SongList.get(curentSong).getTitle(); // String duration = mMp3SongList.get(curentSong).getDuration(); // mMusicPlayerListener.playingNow(title, artist, duration); // } // }); // mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { // @Override // public void onCompletion(MediaPlayer mp) { // curentSong++; // releaseMediaPlayer(); // if (curentSong == mMp3SongList.size() - 1) { // mMusicPlayerListener.playFinished(); // } else { // playMusic(curentSong); // } // } // }); // } // // private void releaseMediaPlayer() { // if (mMediaPlayer != null) { // if (mMediaPlayer.isPlaying()) { // mMediaPlayer.stop(); // } // mMediaPlayer.release(); // mMediaPlayer = null; // } // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.TextView; import io.recar.once2go.easynavi.R; import io.recar.once2go.easynavi.interfaces.MusicPlayerControlsListener; import io.recar.once2go.easynavi.interfaces.MusicPlayerListener; import io.recar.once2go.easynavi.util.MusicPlayerManager;
package io.recar.once2go.easynavi.framents; /** * Created by once2go on 11.04.16. */ public class MusicPlayerFragment extends Fragment implements View.OnClickListener, MusicPlayerListener { private TextView mSongTitle; private TextView mSongArtist; private TextView mSongDuration; private ImageButton mPlay; private ImageButton mPrevious; private ImageButton mNext; private ImageButton mVolumeUp; private ImageButton getmVolumeDown; private boolean isPlay;
// Path: app/src/main/java/io/recar/once2go/easynavi/interfaces/MusicPlayerControlsListener.java // public interface MusicPlayerControlsListener { // // void play(); // // void playPrevious(); // // void playNext(); // // void pause(); // // void volumeUp(); // // void volumeDown(); // // void stop(); // } // // Path: app/src/main/java/io/recar/once2go/easynavi/interfaces/MusicPlayerListener.java // public interface MusicPlayerListener { // // void playFinished(); // // void playingNow(String title, String artist, String duration); // } // // Path: app/src/main/java/io/recar/once2go/easynavi/util/MusicPlayerManager.java // public class MusicPlayerManager implements MusicPlayerControlsListener { // // private Context mContext; // private List<Mp3Song> mMp3SongList; // private MusicPlayerListener mMusicPlayerListener; // private MediaPlayer mMediaPlayer; // private int curentSong; // // float mInitVolume = 0.5f; // // public MusicPlayerManager(Context context, @NonNull MusicPlayerListener musicPlayerListener) { // mContext = context; // mMp3SongList = MusicSearchHelper.getMusicList(context); // mMusicPlayerListener = musicPlayerListener; // } // // // @Override // public void play() { // if(mMediaPlayer != null && mMediaPlayer.isPlaying()){ // releaseMediaPlayer(); // } else { // playMusic(curentSong); // } // } // // @Override // public void playPrevious() { // releaseMediaPlayer(); // curentSong--; // if (curentSong < 0) { // curentSong = 0; // } // playMusic(curentSong); // } // // @Override // public void playNext() { // releaseMediaPlayer(); // curentSong++; // if (curentSong > mMp3SongList.size() - 1) { // curentSong = 0; // } // playMusic(curentSong); // } // // @Override // public void pause() { // // } // // @Override // public void volumeUp() { // if (mMediaPlayer!=null && mInitVolume < 1.0f) { // mInitVolume += 0.1f; // mMediaPlayer.setVolume(mInitVolume, mInitVolume); // } // } // // @Override // public void volumeDown() { // if (mMediaPlayer!=null && mInitVolume > 0) { // mInitVolume -= 0.1f; // mMediaPlayer.setVolume(mInitVolume, mInitVolume); // } // } // // @Override // public void stop() { // releaseMediaPlayer(); // } // // public MusicPlayerControlsListener getMusicControlsListener() { // return this; // } // // private void playMusic(int id) { // Uri contentUri = ContentUris.withAppendedId( // android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mMp3SongList.get(id).getId()); // mMediaPlayer = new MediaPlayer(); // mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); // mMediaPlayer.setVolume(mInitVolume, mInitVolume); // try { // mMediaPlayer.setDataSource(mContext, contentUri); // } catch (IOException e) { // e.printStackTrace(); // } // mMediaPlayer.prepareAsync(); // mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { // @Override // public void onPrepared(MediaPlayer mp) { // mp.start(); // String artist = mMp3SongList.get(curentSong).getArtist(); // String title = mMp3SongList.get(curentSong).getTitle(); // String duration = mMp3SongList.get(curentSong).getDuration(); // mMusicPlayerListener.playingNow(title, artist, duration); // } // }); // mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { // @Override // public void onCompletion(MediaPlayer mp) { // curentSong++; // releaseMediaPlayer(); // if (curentSong == mMp3SongList.size() - 1) { // mMusicPlayerListener.playFinished(); // } else { // playMusic(curentSong); // } // } // }); // } // // private void releaseMediaPlayer() { // if (mMediaPlayer != null) { // if (mMediaPlayer.isPlaying()) { // mMediaPlayer.stop(); // } // mMediaPlayer.release(); // mMediaPlayer = null; // } // } // } // Path: app/src/main/java/io/recar/once2go/easynavi/framents/MusicPlayerFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.TextView; import io.recar.once2go.easynavi.R; import io.recar.once2go.easynavi.interfaces.MusicPlayerControlsListener; import io.recar.once2go.easynavi.interfaces.MusicPlayerListener; import io.recar.once2go.easynavi.util.MusicPlayerManager; package io.recar.once2go.easynavi.framents; /** * Created by once2go on 11.04.16. */ public class MusicPlayerFragment extends Fragment implements View.OnClickListener, MusicPlayerListener { private TextView mSongTitle; private TextView mSongArtist; private TextView mSongDuration; private ImageButton mPlay; private ImageButton mPrevious; private ImageButton mNext; private ImageButton mVolumeUp; private ImageButton getmVolumeDown; private boolean isPlay;
private MusicPlayerControlsListener mMusicPlayerControlsListener;
once2go/mvp.recar.io
app/src/main/java/io/recar/once2go/easynavi/framents/MusicPlayerFragment.java
// Path: app/src/main/java/io/recar/once2go/easynavi/interfaces/MusicPlayerControlsListener.java // public interface MusicPlayerControlsListener { // // void play(); // // void playPrevious(); // // void playNext(); // // void pause(); // // void volumeUp(); // // void volumeDown(); // // void stop(); // } // // Path: app/src/main/java/io/recar/once2go/easynavi/interfaces/MusicPlayerListener.java // public interface MusicPlayerListener { // // void playFinished(); // // void playingNow(String title, String artist, String duration); // } // // Path: app/src/main/java/io/recar/once2go/easynavi/util/MusicPlayerManager.java // public class MusicPlayerManager implements MusicPlayerControlsListener { // // private Context mContext; // private List<Mp3Song> mMp3SongList; // private MusicPlayerListener mMusicPlayerListener; // private MediaPlayer mMediaPlayer; // private int curentSong; // // float mInitVolume = 0.5f; // // public MusicPlayerManager(Context context, @NonNull MusicPlayerListener musicPlayerListener) { // mContext = context; // mMp3SongList = MusicSearchHelper.getMusicList(context); // mMusicPlayerListener = musicPlayerListener; // } // // // @Override // public void play() { // if(mMediaPlayer != null && mMediaPlayer.isPlaying()){ // releaseMediaPlayer(); // } else { // playMusic(curentSong); // } // } // // @Override // public void playPrevious() { // releaseMediaPlayer(); // curentSong--; // if (curentSong < 0) { // curentSong = 0; // } // playMusic(curentSong); // } // // @Override // public void playNext() { // releaseMediaPlayer(); // curentSong++; // if (curentSong > mMp3SongList.size() - 1) { // curentSong = 0; // } // playMusic(curentSong); // } // // @Override // public void pause() { // // } // // @Override // public void volumeUp() { // if (mMediaPlayer!=null && mInitVolume < 1.0f) { // mInitVolume += 0.1f; // mMediaPlayer.setVolume(mInitVolume, mInitVolume); // } // } // // @Override // public void volumeDown() { // if (mMediaPlayer!=null && mInitVolume > 0) { // mInitVolume -= 0.1f; // mMediaPlayer.setVolume(mInitVolume, mInitVolume); // } // } // // @Override // public void stop() { // releaseMediaPlayer(); // } // // public MusicPlayerControlsListener getMusicControlsListener() { // return this; // } // // private void playMusic(int id) { // Uri contentUri = ContentUris.withAppendedId( // android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mMp3SongList.get(id).getId()); // mMediaPlayer = new MediaPlayer(); // mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); // mMediaPlayer.setVolume(mInitVolume, mInitVolume); // try { // mMediaPlayer.setDataSource(mContext, contentUri); // } catch (IOException e) { // e.printStackTrace(); // } // mMediaPlayer.prepareAsync(); // mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { // @Override // public void onPrepared(MediaPlayer mp) { // mp.start(); // String artist = mMp3SongList.get(curentSong).getArtist(); // String title = mMp3SongList.get(curentSong).getTitle(); // String duration = mMp3SongList.get(curentSong).getDuration(); // mMusicPlayerListener.playingNow(title, artist, duration); // } // }); // mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { // @Override // public void onCompletion(MediaPlayer mp) { // curentSong++; // releaseMediaPlayer(); // if (curentSong == mMp3SongList.size() - 1) { // mMusicPlayerListener.playFinished(); // } else { // playMusic(curentSong); // } // } // }); // } // // private void releaseMediaPlayer() { // if (mMediaPlayer != null) { // if (mMediaPlayer.isPlaying()) { // mMediaPlayer.stop(); // } // mMediaPlayer.release(); // mMediaPlayer = null; // } // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.TextView; import io.recar.once2go.easynavi.R; import io.recar.once2go.easynavi.interfaces.MusicPlayerControlsListener; import io.recar.once2go.easynavi.interfaces.MusicPlayerListener; import io.recar.once2go.easynavi.util.MusicPlayerManager;
package io.recar.once2go.easynavi.framents; /** * Created by once2go on 11.04.16. */ public class MusicPlayerFragment extends Fragment implements View.OnClickListener, MusicPlayerListener { private TextView mSongTitle; private TextView mSongArtist; private TextView mSongDuration; private ImageButton mPlay; private ImageButton mPrevious; private ImageButton mNext; private ImageButton mVolumeUp; private ImageButton getmVolumeDown; private boolean isPlay; private MusicPlayerControlsListener mMusicPlayerControlsListener; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.music_player_layout, container, false); assigneView(view);
// Path: app/src/main/java/io/recar/once2go/easynavi/interfaces/MusicPlayerControlsListener.java // public interface MusicPlayerControlsListener { // // void play(); // // void playPrevious(); // // void playNext(); // // void pause(); // // void volumeUp(); // // void volumeDown(); // // void stop(); // } // // Path: app/src/main/java/io/recar/once2go/easynavi/interfaces/MusicPlayerListener.java // public interface MusicPlayerListener { // // void playFinished(); // // void playingNow(String title, String artist, String duration); // } // // Path: app/src/main/java/io/recar/once2go/easynavi/util/MusicPlayerManager.java // public class MusicPlayerManager implements MusicPlayerControlsListener { // // private Context mContext; // private List<Mp3Song> mMp3SongList; // private MusicPlayerListener mMusicPlayerListener; // private MediaPlayer mMediaPlayer; // private int curentSong; // // float mInitVolume = 0.5f; // // public MusicPlayerManager(Context context, @NonNull MusicPlayerListener musicPlayerListener) { // mContext = context; // mMp3SongList = MusicSearchHelper.getMusicList(context); // mMusicPlayerListener = musicPlayerListener; // } // // // @Override // public void play() { // if(mMediaPlayer != null && mMediaPlayer.isPlaying()){ // releaseMediaPlayer(); // } else { // playMusic(curentSong); // } // } // // @Override // public void playPrevious() { // releaseMediaPlayer(); // curentSong--; // if (curentSong < 0) { // curentSong = 0; // } // playMusic(curentSong); // } // // @Override // public void playNext() { // releaseMediaPlayer(); // curentSong++; // if (curentSong > mMp3SongList.size() - 1) { // curentSong = 0; // } // playMusic(curentSong); // } // // @Override // public void pause() { // // } // // @Override // public void volumeUp() { // if (mMediaPlayer!=null && mInitVolume < 1.0f) { // mInitVolume += 0.1f; // mMediaPlayer.setVolume(mInitVolume, mInitVolume); // } // } // // @Override // public void volumeDown() { // if (mMediaPlayer!=null && mInitVolume > 0) { // mInitVolume -= 0.1f; // mMediaPlayer.setVolume(mInitVolume, mInitVolume); // } // } // // @Override // public void stop() { // releaseMediaPlayer(); // } // // public MusicPlayerControlsListener getMusicControlsListener() { // return this; // } // // private void playMusic(int id) { // Uri contentUri = ContentUris.withAppendedId( // android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mMp3SongList.get(id).getId()); // mMediaPlayer = new MediaPlayer(); // mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); // mMediaPlayer.setVolume(mInitVolume, mInitVolume); // try { // mMediaPlayer.setDataSource(mContext, contentUri); // } catch (IOException e) { // e.printStackTrace(); // } // mMediaPlayer.prepareAsync(); // mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { // @Override // public void onPrepared(MediaPlayer mp) { // mp.start(); // String artist = mMp3SongList.get(curentSong).getArtist(); // String title = mMp3SongList.get(curentSong).getTitle(); // String duration = mMp3SongList.get(curentSong).getDuration(); // mMusicPlayerListener.playingNow(title, artist, duration); // } // }); // mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { // @Override // public void onCompletion(MediaPlayer mp) { // curentSong++; // releaseMediaPlayer(); // if (curentSong == mMp3SongList.size() - 1) { // mMusicPlayerListener.playFinished(); // } else { // playMusic(curentSong); // } // } // }); // } // // private void releaseMediaPlayer() { // if (mMediaPlayer != null) { // if (mMediaPlayer.isPlaying()) { // mMediaPlayer.stop(); // } // mMediaPlayer.release(); // mMediaPlayer = null; // } // } // } // Path: app/src/main/java/io/recar/once2go/easynavi/framents/MusicPlayerFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.TextView; import io.recar.once2go.easynavi.R; import io.recar.once2go.easynavi.interfaces.MusicPlayerControlsListener; import io.recar.once2go.easynavi.interfaces.MusicPlayerListener; import io.recar.once2go.easynavi.util.MusicPlayerManager; package io.recar.once2go.easynavi.framents; /** * Created by once2go on 11.04.16. */ public class MusicPlayerFragment extends Fragment implements View.OnClickListener, MusicPlayerListener { private TextView mSongTitle; private TextView mSongArtist; private TextView mSongDuration; private ImageButton mPlay; private ImageButton mPrevious; private ImageButton mNext; private ImageButton mVolumeUp; private ImageButton getmVolumeDown; private boolean isPlay; private MusicPlayerControlsListener mMusicPlayerControlsListener; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.music_player_layout, container, false); assigneView(view);
MusicPlayerManager musicPlayerManager = new MusicPlayerManager(getActivity(), this);
once2go/mvp.recar.io
usbserial/src/main/java/io/recar/once2go/usbserial/usbserial/UsbSerialDebugger.java
// Path: usbserial/src/main/java/io/recar/once2go/usbserial/utils/HexData.java // public class HexData // { // private static final String HEXES = "0123456789ABCDEF"; // private static final String HEX_INDICATOR = "0x"; // private static final String SPACE = " "; // // private HexData() // { // // } // // public static String hexToString(byte[] data) // { // if(data != null) // { // StringBuilder hex = new StringBuilder(2*data.length); // for(int i=0;i<=data.length-1;i++) // { // byte dataAtIndex = data[i]; // hex.append(HEX_INDICATOR); // hex.append(HEXES.charAt((dataAtIndex & 0xF0) >> 4)) // .append(HEXES.charAt((dataAtIndex & 0x0F))); // hex.append(SPACE); // } // return hex.toString(); // }else // { // return null; // } // } // // public static byte[] stringTobytes(String hexString) // { // String stringProcessed = hexString.trim().replaceAll("0x", ""); // stringProcessed = stringProcessed.replaceAll("\\s+",""); // byte[] data = new byte[stringProcessed.length()/2]; // int i = 0; // int j = 0; // while(i <= stringProcessed.length()-1) // { // byte character = (byte) Integer.parseInt(stringProcessed.substring(i, i+2), 16); // data[j] = character; // j++; // i += 2; // } // return data; // } // // public static String hex4digits(String id) // { // if(id.length() == 1) return "000" + id; // if(id.length() == 2) return "00" + id; // if(id.length() == 3) return "0" + id; // else return id; // } // }
import android.util.Log; import io.recar.once2go.usbserial.utils.HexData;
package io.recar.once2go.usbserial.usbserial; public class UsbSerialDebugger { private static final String CLASS_ID = UsbSerialDebugger.class.getSimpleName(); public static final String ENCODING = "UTF-8"; private UsbSerialDebugger() { } public static void printLogGet(byte[] src, boolean verbose) { if(!verbose) { Log.i(CLASS_ID, "Data obtained from write buffer: " + new String(src)); }else { Log.i(CLASS_ID, "Data obtained from write buffer: " + new String(src));
// Path: usbserial/src/main/java/io/recar/once2go/usbserial/utils/HexData.java // public class HexData // { // private static final String HEXES = "0123456789ABCDEF"; // private static final String HEX_INDICATOR = "0x"; // private static final String SPACE = " "; // // private HexData() // { // // } // // public static String hexToString(byte[] data) // { // if(data != null) // { // StringBuilder hex = new StringBuilder(2*data.length); // for(int i=0;i<=data.length-1;i++) // { // byte dataAtIndex = data[i]; // hex.append(HEX_INDICATOR); // hex.append(HEXES.charAt((dataAtIndex & 0xF0) >> 4)) // .append(HEXES.charAt((dataAtIndex & 0x0F))); // hex.append(SPACE); // } // return hex.toString(); // }else // { // return null; // } // } // // public static byte[] stringTobytes(String hexString) // { // String stringProcessed = hexString.trim().replaceAll("0x", ""); // stringProcessed = stringProcessed.replaceAll("\\s+",""); // byte[] data = new byte[stringProcessed.length()/2]; // int i = 0; // int j = 0; // while(i <= stringProcessed.length()-1) // { // byte character = (byte) Integer.parseInt(stringProcessed.substring(i, i+2), 16); // data[j] = character; // j++; // i += 2; // } // return data; // } // // public static String hex4digits(String id) // { // if(id.length() == 1) return "000" + id; // if(id.length() == 2) return "00" + id; // if(id.length() == 3) return "0" + id; // else return id; // } // } // Path: usbserial/src/main/java/io/recar/once2go/usbserial/usbserial/UsbSerialDebugger.java import android.util.Log; import io.recar.once2go.usbserial.utils.HexData; package io.recar.once2go.usbserial.usbserial; public class UsbSerialDebugger { private static final String CLASS_ID = UsbSerialDebugger.class.getSimpleName(); public static final String ENCODING = "UTF-8"; private UsbSerialDebugger() { } public static void printLogGet(byte[] src, boolean verbose) { if(!verbose) { Log.i(CLASS_ID, "Data obtained from write buffer: " + new String(src)); }else { Log.i(CLASS_ID, "Data obtained from write buffer: " + new String(src));
Log.i(CLASS_ID, "Raw data from write buffer: " + HexData.hexToString(src));
dlew/android-sotm
project/src/main/java/com/idunnolol/sotm/data/Db.java
// Path: project/src/main/java/com/idunnolol/sotm/data/Card.java // public static enum Type { // HERO, // VILLAIN, // ENVIRONMENT, // }
import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import android.util.JsonReader; import android.util.Pair; import android.util.SparseIntArray; import com.danlew.utils.Log; import com.danlew.utils.ResourceUtils; import com.idunnolol.sotm.R; import com.idunnolol.sotm.data.Card.Type; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set;
private static final String PREFERENCE_CARD_STATE = "com.idunnolol.sotm.cards.state"; private Map<String, Card> mCards = new HashMap<String, Card>(); private List<CardSet> mCardSets = new ArrayList<CardSet>(); private SparseIntArray mNumPlayerPoints = new SparseIntArray(); private SparseIntArray mDifficultyScale = new SparseIntArray(); private Map<String, String> mNameConversions = new HashMap<String, String>(); private Map<Card, Set<Card>> mAlternates = new HashMap<Card, Set<Card>>(); // Just used during parsing; if needed this can be more robust private Map<Card, CardSet> mReverseCardSetCache = new HashMap<Card, CardSet>(); private Map<Card, String> mTeams = new HashMap<Card, String>(); private int mMinDifficultyPoints; private int mMaxDifficultyPoints; public static List<CardSet> getCardSets() { return sInstance.mCardSets; } /** * Returns all cards of a particular type. Only returns enabled cards. */
// Path: project/src/main/java/com/idunnolol/sotm/data/Card.java // public static enum Type { // HERO, // VILLAIN, // ENVIRONMENT, // } // Path: project/src/main/java/com/idunnolol/sotm/data/Db.java import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import android.util.JsonReader; import android.util.Pair; import android.util.SparseIntArray; import com.danlew.utils.Log; import com.danlew.utils.ResourceUtils; import com.idunnolol.sotm.R; import com.idunnolol.sotm.data.Card.Type; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; private static final String PREFERENCE_CARD_STATE = "com.idunnolol.sotm.cards.state"; private Map<String, Card> mCards = new HashMap<String, Card>(); private List<CardSet> mCardSets = new ArrayList<CardSet>(); private SparseIntArray mNumPlayerPoints = new SparseIntArray(); private SparseIntArray mDifficultyScale = new SparseIntArray(); private Map<String, String> mNameConversions = new HashMap<String, String>(); private Map<Card, Set<Card>> mAlternates = new HashMap<Card, Set<Card>>(); // Just used during parsing; if needed this can be more robust private Map<Card, CardSet> mReverseCardSetCache = new HashMap<Card, CardSet>(); private Map<Card, String> mTeams = new HashMap<Card, String>(); private int mMinDifficultyPoints; private int mMaxDifficultyPoints; public static List<CardSet> getCardSets() { return sInstance.mCardSets; } /** * Returns all cards of a particular type. Only returns enabled cards. */
public static List<Card> getCards(Type type) {
dlew/android-sotm
project/src/main/java/com/idunnolol/sotm/widget/DifficultyAdapter.java
// Path: project/src/main/java/com/idunnolol/sotm/data/Difficulty.java // public enum Difficulty { // // RANDOM(-1, R.string.difficulty_random), // EASY(90, R.string.difficulty_easy), // MEDIUM(75, R.string.difficulty_medium), // HARD(50, R.string.difficulty_hard), // VERY_HARD(30, R.string.difficulty_very_hard), // GOOD_LUCK(15, R.string.difficulty_good_luck), // PICK_YOUR_OWN(-1, R.string.difficulty_specify); // // private int mTargetWinPercent; // private int mStrResId; // // private Difficulty(int targetWinPercent, int strResId) { // mTargetWinPercent = targetWinPercent; // mStrResId = strResId; // } // // public int getTargetWinPercent() { // return mTargetWinPercent; // } // // public int getStrResId() { // return mStrResId; // } // }
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.idunnolol.sotm.R; import com.idunnolol.sotm.data.Difficulty;
package com.idunnolol.sotm.widget; public class DifficultyAdapter extends BaseAdapter { private Context mContext; public DifficultyAdapter(Context context) { mContext = context; } @Override public int getCount() {
// Path: project/src/main/java/com/idunnolol/sotm/data/Difficulty.java // public enum Difficulty { // // RANDOM(-1, R.string.difficulty_random), // EASY(90, R.string.difficulty_easy), // MEDIUM(75, R.string.difficulty_medium), // HARD(50, R.string.difficulty_hard), // VERY_HARD(30, R.string.difficulty_very_hard), // GOOD_LUCK(15, R.string.difficulty_good_luck), // PICK_YOUR_OWN(-1, R.string.difficulty_specify); // // private int mTargetWinPercent; // private int mStrResId; // // private Difficulty(int targetWinPercent, int strResId) { // mTargetWinPercent = targetWinPercent; // mStrResId = strResId; // } // // public int getTargetWinPercent() { // return mTargetWinPercent; // } // // public int getStrResId() { // return mStrResId; // } // } // Path: project/src/main/java/com/idunnolol/sotm/widget/DifficultyAdapter.java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.idunnolol.sotm.R; import com.idunnolol.sotm.data.Difficulty; package com.idunnolol.sotm.widget; public class DifficultyAdapter extends BaseAdapter { private Context mContext; public DifficultyAdapter(Context context) { mContext = context; } @Override public int getCount() {
return Difficulty.values().length;
dlew/android-sotm
project/src/main/java/com/idunnolol/sotm/data/GameSetup.java
// Path: project/src/main/java/com/idunnolol/sotm/data/Card.java // public static enum Type { // HERO, // VILLAIN, // ENVIRONMENT, // }
import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.util.Pair; import com.idunnolol.sotm.data.Card.Type; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set;
} // Villain is either random with no team, or is random but hasn't selected a team if (mVillain.isRandom() && (!mVillain.isTeam() || mVillainTeam.size() == 0)) { return true; } return mEnvironment.isRandom(); } public boolean isCompletelyRandom() { for (Card card : mHeroes) { if (!card.equals(Card.RANDOM_HERO)) { return false; } } return mVillain.equals(Card.RANDOM_VILLAIN) && mEnvironment.equals(Card.RANDOM_ENVIRONMENT); } /** * We might not be able to randomize if there aren't enough options available */ public boolean canRandomize() { return getFirstLackingType() == null; } /** * @return the first type without enough enabled cards, or null if we're good to go */
// Path: project/src/main/java/com/idunnolol/sotm/data/Card.java // public static enum Type { // HERO, // VILLAIN, // ENVIRONMENT, // } // Path: project/src/main/java/com/idunnolol/sotm/data/GameSetup.java import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.util.Pair; import com.idunnolol.sotm.data.Card.Type; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; } // Villain is either random with no team, or is random but hasn't selected a team if (mVillain.isRandom() && (!mVillain.isTeam() || mVillainTeam.size() == 0)) { return true; } return mEnvironment.isRandom(); } public boolean isCompletelyRandom() { for (Card card : mHeroes) { if (!card.equals(Card.RANDOM_HERO)) { return false; } } return mVillain.equals(Card.RANDOM_VILLAIN) && mEnvironment.equals(Card.RANDOM_ENVIRONMENT); } /** * We might not be able to randomize if there aren't enough options available */ public boolean canRandomize() { return getFirstLackingType() == null; } /** * @return the first type without enough enabled cards, or null if we're good to go */
public Type getFirstLackingType() {
dlew/android-sotm
project/src/main/java/com/idunnolol/sotm/fragment/DifficultyDialogFragment.java
// Path: project/src/main/java/com/idunnolol/sotm/data/Difficulty.java // public enum Difficulty { // // RANDOM(-1, R.string.difficulty_random), // EASY(90, R.string.difficulty_easy), // MEDIUM(75, R.string.difficulty_medium), // HARD(50, R.string.difficulty_hard), // VERY_HARD(30, R.string.difficulty_very_hard), // GOOD_LUCK(15, R.string.difficulty_good_luck), // PICK_YOUR_OWN(-1, R.string.difficulty_specify); // // private int mTargetWinPercent; // private int mStrResId; // // private Difficulty(int targetWinPercent, int strResId) { // mTargetWinPercent = targetWinPercent; // mStrResId = strResId; // } // // public int getTargetWinPercent() { // return mTargetWinPercent; // } // // public int getStrResId() { // return mStrResId; // } // } // // Path: project/src/main/java/com/idunnolol/sotm/widget/DifficultyAdapter.java // public class DifficultyAdapter extends BaseAdapter { // // private Context mContext; // // public DifficultyAdapter(Context context) { // mContext = context; // } // // @Override // public int getCount() { // return Difficulty.values().length; // } // // @Override // public Difficulty getItem(int position) { // return Difficulty.values()[position]; // } // // @Override // public long getItemId(int position) { // return position; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // if (convertView == null) { // convertView = LayoutInflater.from(mContext).inflate(R.layout.row_dialog, parent, false); // } // // TextView textView = (TextView) convertView; // Difficulty difficulty = getItem(position); // // CharSequence text; // if (difficulty.getTargetWinPercent() == -1) { // text = mContext.getString(difficulty.getStrResId()); // } // else { // text = mContext.getString(R.string.template_win_rate, mContext.getString(difficulty.getStrResId()), // difficulty.getTargetWinPercent()); // } // textView.setText(text); // // return convertView; // } // // }
import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import com.idunnolol.sotm.R; import com.idunnolol.sotm.data.Difficulty; import com.idunnolol.sotm.widget.DifficultyAdapter;
package com.idunnolol.sotm.fragment; public class DifficultyDialogFragment extends DialogFragment { public static final String TAG = DifficultyDialogFragment.class.getName(); private DifficultyDialogFragmentListener mListener;
// Path: project/src/main/java/com/idunnolol/sotm/data/Difficulty.java // public enum Difficulty { // // RANDOM(-1, R.string.difficulty_random), // EASY(90, R.string.difficulty_easy), // MEDIUM(75, R.string.difficulty_medium), // HARD(50, R.string.difficulty_hard), // VERY_HARD(30, R.string.difficulty_very_hard), // GOOD_LUCK(15, R.string.difficulty_good_luck), // PICK_YOUR_OWN(-1, R.string.difficulty_specify); // // private int mTargetWinPercent; // private int mStrResId; // // private Difficulty(int targetWinPercent, int strResId) { // mTargetWinPercent = targetWinPercent; // mStrResId = strResId; // } // // public int getTargetWinPercent() { // return mTargetWinPercent; // } // // public int getStrResId() { // return mStrResId; // } // } // // Path: project/src/main/java/com/idunnolol/sotm/widget/DifficultyAdapter.java // public class DifficultyAdapter extends BaseAdapter { // // private Context mContext; // // public DifficultyAdapter(Context context) { // mContext = context; // } // // @Override // public int getCount() { // return Difficulty.values().length; // } // // @Override // public Difficulty getItem(int position) { // return Difficulty.values()[position]; // } // // @Override // public long getItemId(int position) { // return position; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // if (convertView == null) { // convertView = LayoutInflater.from(mContext).inflate(R.layout.row_dialog, parent, false); // } // // TextView textView = (TextView) convertView; // Difficulty difficulty = getItem(position); // // CharSequence text; // if (difficulty.getTargetWinPercent() == -1) { // text = mContext.getString(difficulty.getStrResId()); // } // else { // text = mContext.getString(R.string.template_win_rate, mContext.getString(difficulty.getStrResId()), // difficulty.getTargetWinPercent()); // } // textView.setText(text); // // return convertView; // } // // } // Path: project/src/main/java/com/idunnolol/sotm/fragment/DifficultyDialogFragment.java import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import com.idunnolol.sotm.R; import com.idunnolol.sotm.data.Difficulty; import com.idunnolol.sotm.widget.DifficultyAdapter; package com.idunnolol.sotm.fragment; public class DifficultyDialogFragment extends DialogFragment { public static final String TAG = DifficultyDialogFragment.class.getName(); private DifficultyDialogFragmentListener mListener;
private DifficultyAdapter mAdapter;
dlew/android-sotm
project/src/main/java/com/idunnolol/sotm/fragment/DifficultyDialogFragment.java
// Path: project/src/main/java/com/idunnolol/sotm/data/Difficulty.java // public enum Difficulty { // // RANDOM(-1, R.string.difficulty_random), // EASY(90, R.string.difficulty_easy), // MEDIUM(75, R.string.difficulty_medium), // HARD(50, R.string.difficulty_hard), // VERY_HARD(30, R.string.difficulty_very_hard), // GOOD_LUCK(15, R.string.difficulty_good_luck), // PICK_YOUR_OWN(-1, R.string.difficulty_specify); // // private int mTargetWinPercent; // private int mStrResId; // // private Difficulty(int targetWinPercent, int strResId) { // mTargetWinPercent = targetWinPercent; // mStrResId = strResId; // } // // public int getTargetWinPercent() { // return mTargetWinPercent; // } // // public int getStrResId() { // return mStrResId; // } // } // // Path: project/src/main/java/com/idunnolol/sotm/widget/DifficultyAdapter.java // public class DifficultyAdapter extends BaseAdapter { // // private Context mContext; // // public DifficultyAdapter(Context context) { // mContext = context; // } // // @Override // public int getCount() { // return Difficulty.values().length; // } // // @Override // public Difficulty getItem(int position) { // return Difficulty.values()[position]; // } // // @Override // public long getItemId(int position) { // return position; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // if (convertView == null) { // convertView = LayoutInflater.from(mContext).inflate(R.layout.row_dialog, parent, false); // } // // TextView textView = (TextView) convertView; // Difficulty difficulty = getItem(position); // // CharSequence text; // if (difficulty.getTargetWinPercent() == -1) { // text = mContext.getString(difficulty.getStrResId()); // } // else { // text = mContext.getString(R.string.template_win_rate, mContext.getString(difficulty.getStrResId()), // difficulty.getTargetWinPercent()); // } // textView.setText(text); // // return convertView; // } // // }
import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import com.idunnolol.sotm.R; import com.idunnolol.sotm.data.Difficulty; import com.idunnolol.sotm.widget.DifficultyAdapter;
package com.idunnolol.sotm.fragment; public class DifficultyDialogFragment extends DialogFragment { public static final String TAG = DifficultyDialogFragment.class.getName(); private DifficultyDialogFragmentListener mListener; private DifficultyAdapter mAdapter; @Override public void onAttach(Activity activity) { super.onAttach(activity); mListener = (DifficultyDialogFragmentListener) activity; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { mAdapter = new DifficultyAdapter(getActivity()); return new AlertDialog.Builder(getActivity()) .setTitle(R.string.title_difficulty) .setSingleChoiceItems(mAdapter, 0, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismissAllowingStateLoss(); mListener.onDifficultyChosen(mAdapter.getItem(which)); } }) .setNegativeButton(R.string.cancel, null) .create(); } ////////////////////////////////////////////////////////////////////////// // Listener public interface DifficultyDialogFragmentListener {
// Path: project/src/main/java/com/idunnolol/sotm/data/Difficulty.java // public enum Difficulty { // // RANDOM(-1, R.string.difficulty_random), // EASY(90, R.string.difficulty_easy), // MEDIUM(75, R.string.difficulty_medium), // HARD(50, R.string.difficulty_hard), // VERY_HARD(30, R.string.difficulty_very_hard), // GOOD_LUCK(15, R.string.difficulty_good_luck), // PICK_YOUR_OWN(-1, R.string.difficulty_specify); // // private int mTargetWinPercent; // private int mStrResId; // // private Difficulty(int targetWinPercent, int strResId) { // mTargetWinPercent = targetWinPercent; // mStrResId = strResId; // } // // public int getTargetWinPercent() { // return mTargetWinPercent; // } // // public int getStrResId() { // return mStrResId; // } // } // // Path: project/src/main/java/com/idunnolol/sotm/widget/DifficultyAdapter.java // public class DifficultyAdapter extends BaseAdapter { // // private Context mContext; // // public DifficultyAdapter(Context context) { // mContext = context; // } // // @Override // public int getCount() { // return Difficulty.values().length; // } // // @Override // public Difficulty getItem(int position) { // return Difficulty.values()[position]; // } // // @Override // public long getItemId(int position) { // return position; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // if (convertView == null) { // convertView = LayoutInflater.from(mContext).inflate(R.layout.row_dialog, parent, false); // } // // TextView textView = (TextView) convertView; // Difficulty difficulty = getItem(position); // // CharSequence text; // if (difficulty.getTargetWinPercent() == -1) { // text = mContext.getString(difficulty.getStrResId()); // } // else { // text = mContext.getString(R.string.template_win_rate, mContext.getString(difficulty.getStrResId()), // difficulty.getTargetWinPercent()); // } // textView.setText(text); // // return convertView; // } // // } // Path: project/src/main/java/com/idunnolol/sotm/fragment/DifficultyDialogFragment.java import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import com.idunnolol.sotm.R; import com.idunnolol.sotm.data.Difficulty; import com.idunnolol.sotm.widget.DifficultyAdapter; package com.idunnolol.sotm.fragment; public class DifficultyDialogFragment extends DialogFragment { public static final String TAG = DifficultyDialogFragment.class.getName(); private DifficultyDialogFragmentListener mListener; private DifficultyAdapter mAdapter; @Override public void onAttach(Activity activity) { super.onAttach(activity); mListener = (DifficultyDialogFragmentListener) activity; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { mAdapter = new DifficultyAdapter(getActivity()); return new AlertDialog.Builder(getActivity()) .setTitle(R.string.title_difficulty) .setSingleChoiceItems(mAdapter, 0, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismissAllowingStateLoss(); mListener.onDifficultyChosen(mAdapter.getItem(which)); } }) .setNegativeButton(R.string.cancel, null) .create(); } ////////////////////////////////////////////////////////////////////////// // Listener public interface DifficultyDialogFragmentListener {
public void onDifficultyChosen(Difficulty difficulty);
openmrs/openmrs-module-dataimporttool
api/src/main/java/org/openmrs/module/dataimporttool/matchingschema/ValueMatchType.java
// Path: api/src/main/java/org/openmrs/module/dataimporttool/dmt/xls/Sheets.java // public class Sheets { // // public static final class TUPLE { // public static final String NAME = "TUPLE"; // public static final int INDEX = 0; // public static final int ROW_START = 1; // public static final int ID = 0; // public static final int TERMINOLOGY = 1; // public static final int TABLE = 2; // public static final int PREDECESSOR = 3; // public static final int DESC = 4; // } // // public static final class MATCH_L_TO_R { // public static final String NAME = "MATCH_L_TO_R"; // public static final int INDEX = 1; // public static final int ROW_START = 2; // public static final int TUPLE_ID = 0; // public static final int TERMINOLOGY = 1; // public static final int COLUMN_L = 2; // public static final int DATATYPE_L = 3; // public static final int SIZE_L = 4; // public static final int REQUIRED_L = 5; // public static final int PK = 6; // public static final int TABLE_R = 7; // public static final int COLUMN_R = 8; // public static final int DATATYPE_R = 9; // public static final int SIZE_R = 10; // public static final int REQUIRED_R = 11; // public static final int MATCH_ID = 12; // public static final int OBS = 13; // public static final int DEFAULT_VALUE = 14; // public static final int VALUE_MATCH = 15; // public static final int POOL = 16; // } // // public static final class REFERENCES { // public static final String NAME_L = "REFERENCES_L"; // public static final int INDEX_L = 2; // public static final String NAME_R = "REFERENCES_R"; // public static final int INDEX_R = 3; // public static final int ROW_START = 1; // public static final int ID = 0; // public static final int TUPLE_MATCH_ID = 1; // public static final int REFERENCE_TABLE = 2; // public static final int REFERENCE_COLUMN = 3; // public static final int REFERENCED_TABLE = 4; // public static final int REFERENCED_COLUMN = 5; // public static final int DATATYPE = 6; // public static final int SIZE = 7; // public static final int REFERENCED_VALUE = 8; // public static final int SEQUENCE = 9; // public static final int NAME_DESC = 10; // } // // public static final class VALUE_MATCH { // public static final String NAME = "VALUE_MATCH"; // public static final int INDEX = 4; // public static final int ROW_START = 2; // public static final int ID = 0; // public static final int GROUP_NAME = 1; // public static final int TABLE_L = 2; // public static final int COLUMN_L = 3; // public static final int VALUE_L = 4; // public static final int PK_L = 5; // public static final int TABLE_R = 6; // public static final int COLUMN_R = 7; // public static final int VALUE_R = 8; // public static final int PK_R = 9; // } // }
import org.openmrs.module.dataimporttool.dmt.xls.XlsProcessor; import java.util.HashMap; import java.util.Map; import org.openmrs.module.dataimporttool.dmt.xls.Sheets;
/** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.module.dataimporttool.matchingschema; /** * This class builds the value mapping representation from the XLS mapping file * */ public class ValueMatchType { public static final Map<Integer, Map<String, String>> valueMatches = new HashMap<Integer, Map<String, String>>(); private static final XlsProcessor pr = new XlsProcessor(); static { int lastGroupId = 0; Map<String, String> valueMapGroup = null;
// Path: api/src/main/java/org/openmrs/module/dataimporttool/dmt/xls/Sheets.java // public class Sheets { // // public static final class TUPLE { // public static final String NAME = "TUPLE"; // public static final int INDEX = 0; // public static final int ROW_START = 1; // public static final int ID = 0; // public static final int TERMINOLOGY = 1; // public static final int TABLE = 2; // public static final int PREDECESSOR = 3; // public static final int DESC = 4; // } // // public static final class MATCH_L_TO_R { // public static final String NAME = "MATCH_L_TO_R"; // public static final int INDEX = 1; // public static final int ROW_START = 2; // public static final int TUPLE_ID = 0; // public static final int TERMINOLOGY = 1; // public static final int COLUMN_L = 2; // public static final int DATATYPE_L = 3; // public static final int SIZE_L = 4; // public static final int REQUIRED_L = 5; // public static final int PK = 6; // public static final int TABLE_R = 7; // public static final int COLUMN_R = 8; // public static final int DATATYPE_R = 9; // public static final int SIZE_R = 10; // public static final int REQUIRED_R = 11; // public static final int MATCH_ID = 12; // public static final int OBS = 13; // public static final int DEFAULT_VALUE = 14; // public static final int VALUE_MATCH = 15; // public static final int POOL = 16; // } // // public static final class REFERENCES { // public static final String NAME_L = "REFERENCES_L"; // public static final int INDEX_L = 2; // public static final String NAME_R = "REFERENCES_R"; // public static final int INDEX_R = 3; // public static final int ROW_START = 1; // public static final int ID = 0; // public static final int TUPLE_MATCH_ID = 1; // public static final int REFERENCE_TABLE = 2; // public static final int REFERENCE_COLUMN = 3; // public static final int REFERENCED_TABLE = 4; // public static final int REFERENCED_COLUMN = 5; // public static final int DATATYPE = 6; // public static final int SIZE = 7; // public static final int REFERENCED_VALUE = 8; // public static final int SEQUENCE = 9; // public static final int NAME_DESC = 10; // } // // public static final class VALUE_MATCH { // public static final String NAME = "VALUE_MATCH"; // public static final int INDEX = 4; // public static final int ROW_START = 2; // public static final int ID = 0; // public static final int GROUP_NAME = 1; // public static final int TABLE_L = 2; // public static final int COLUMN_L = 3; // public static final int VALUE_L = 4; // public static final int PK_L = 5; // public static final int TABLE_R = 6; // public static final int COLUMN_R = 7; // public static final int VALUE_R = 8; // public static final int PK_R = 9; // } // } // Path: api/src/main/java/org/openmrs/module/dataimporttool/matchingschema/ValueMatchType.java import org.openmrs.module.dataimporttool.dmt.xls.XlsProcessor; import java.util.HashMap; import java.util.Map; import org.openmrs.module.dataimporttool.dmt.xls.Sheets; /** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.module.dataimporttool.matchingschema; /** * This class builds the value mapping representation from the XLS mapping file * */ public class ValueMatchType { public static final Map<Integer, Map<String, String>> valueMatches = new HashMap<Integer, Map<String, String>>(); private static final XlsProcessor pr = new XlsProcessor(); static { int lastGroupId = 0; Map<String, String> valueMapGroup = null;
for (int i = Sheets.VALUE_MATCH.ROW_START; i < pr
openmrs/openmrs-module-dataimporttool
api/src/main/java/org/openmrs/module/dataimporttool/dmt/util/TupleTree.java
// Path: api/src/main/java/org/openmrs/module/dataimporttool/matchingschema/TupleType.java // @SuppressWarnings("restriction") // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "tupleType", propOrder = { // "terminology", // "table", // "desc", // "matches", // "references" // }) // public class TupleType implements ReferencedPart { // // @XmlElement(required = true) // protected String terminology; // @XmlElement(required = true) // protected String table; // @XmlElement(required = true) // protected String desc; // @XmlElement(required = true) // protected List<MatchType> matches; // protected Map<Integer, ReferenceType> references;//L-References // @XmlAttribute(name = "id", required = true) // protected Integer id; // // /** // * Gets the value of the terminology property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getTerminology() { // return terminology; // } // // /** // * Sets the value of the terminology property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setTerminology(String value) { // this.terminology = value; // } // // /** // * Gets the value of the table property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getTable() { // return table; // } // // /** // * Sets the value of the table property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setTable(String value) { // this.table = value; // } // // /** // * Gets the value of the desc property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getDesc() { // return desc; // } // // /** // * Sets the value of the desc property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setDesc(String value) { // this.desc = value; // } // // /** // * Gets the value of the match property. // * // * <p> // * This accessor method returns a reference to the live list, // * not a snapshot. Therefore any modification you make to the // * returned list will be present inside the JAXB object. // * This is why there is not a <CODE>set</CODE> method for the match property. // * // * <p> // * For example, to add a new item, do as follows: // * <pre> // * getMatch().add(newItem); // * </pre> // * // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link MatchType } // * // * // */ // public List<MatchType> getMatches() { // if (matches == null) { // matches = new ArrayList<MatchType>(); // } // return this.matches; // } // // /** // * Gets the value of the leftReference property. // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link ReferenceType } // * // * // */ // public Map<Integer, ReferenceType> getReferences() { // if(references == null) { // references = new HashMap<Integer, ReferenceType>(); // } // return this.references; // } // // /** // * Sets the value of the leftReference property. // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link ReferenceType } // * // * // */ // public void setReferences(Map<Integer, ReferenceType> references) { // this.references = references; // } // // /** // * Gets the value of the id property. // * // * @return // * possible object is // * {@link Integer } // * // */ // public Integer getId() { // return id; // } // // /** // * Sets the value of the id property. // * // * @param value // * allowed object is // * {@link Integer } // * // */ // public void setId(Integer value) { // this.id = value; // } // // }
import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import org.openmrs.module.dataimporttool.matchingschema.TupleType;
/** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.module.dataimporttool.dmt.util; public class TupleTree { //to be set during translation phase private Object top; private Object curr;
// Path: api/src/main/java/org/openmrs/module/dataimporttool/matchingschema/TupleType.java // @SuppressWarnings("restriction") // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "tupleType", propOrder = { // "terminology", // "table", // "desc", // "matches", // "references" // }) // public class TupleType implements ReferencedPart { // // @XmlElement(required = true) // protected String terminology; // @XmlElement(required = true) // protected String table; // @XmlElement(required = true) // protected String desc; // @XmlElement(required = true) // protected List<MatchType> matches; // protected Map<Integer, ReferenceType> references;//L-References // @XmlAttribute(name = "id", required = true) // protected Integer id; // // /** // * Gets the value of the terminology property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getTerminology() { // return terminology; // } // // /** // * Sets the value of the terminology property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setTerminology(String value) { // this.terminology = value; // } // // /** // * Gets the value of the table property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getTable() { // return table; // } // // /** // * Sets the value of the table property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setTable(String value) { // this.table = value; // } // // /** // * Gets the value of the desc property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getDesc() { // return desc; // } // // /** // * Sets the value of the desc property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setDesc(String value) { // this.desc = value; // } // // /** // * Gets the value of the match property. // * // * <p> // * This accessor method returns a reference to the live list, // * not a snapshot. Therefore any modification you make to the // * returned list will be present inside the JAXB object. // * This is why there is not a <CODE>set</CODE> method for the match property. // * // * <p> // * For example, to add a new item, do as follows: // * <pre> // * getMatch().add(newItem); // * </pre> // * // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link MatchType } // * // * // */ // public List<MatchType> getMatches() { // if (matches == null) { // matches = new ArrayList<MatchType>(); // } // return this.matches; // } // // /** // * Gets the value of the leftReference property. // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link ReferenceType } // * // * // */ // public Map<Integer, ReferenceType> getReferences() { // if(references == null) { // references = new HashMap<Integer, ReferenceType>(); // } // return this.references; // } // // /** // * Sets the value of the leftReference property. // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link ReferenceType } // * // * // */ // public void setReferences(Map<Integer, ReferenceType> references) { // this.references = references; // } // // /** // * Gets the value of the id property. // * // * @return // * possible object is // * {@link Integer } // * // */ // public Integer getId() { // return id; // } // // /** // * Sets the value of the id property. // * // * @param value // * allowed object is // * {@link Integer } // * // */ // public void setId(Integer value) { // this.id = value; // } // // } // Path: api/src/main/java/org/openmrs/module/dataimporttool/dmt/util/TupleTree.java import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import org.openmrs.module.dataimporttool.matchingschema.TupleType; /** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.module.dataimporttool.dmt.util; public class TupleTree { //to be set during translation phase private Object top; private Object curr;
private TupleType head;
openmrs/openmrs-module-dataimporttool
api/src/main/java/org/openmrs/module/dataimporttool/matchingschema/MatchType.java
// Path: api/src/main/java/org/openmrs/module/dataimporttool/dmt/helper/ValidationStatuses.java // public enum ValidationStatuses { // RIGHT_TO_LEFT_DATATYPE_COMPATIBILITY, // RIGHT_TO_LEFT_DATATYPE_INCOMPATIBILITY, // LEFT_TO_RIGT_DATATYPE_COMPATIBILITY, // LEFT_TO_RIGT_DATATYPE_INCOMPATIBILITY, // LEFT_TO_RIGHT_SIZE_INCOMPATIBILITY // // }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import org.openmrs.module.dataimporttool.dmt.helper.ValidationStatuses;
@XmlType(name = "matchType", propOrder = { "tupleId", "terminology", "left", "right", "valueMatchId", "references" }) public class MatchType implements ReferencedPart { @XmlElement(required = true) private Integer tupleId; @XmlElement(required = true) protected String terminology; @XmlElement(required = true) protected MatchSideType left; @XmlElement(required = true) protected MatchSideType right; @XmlElement(defaultValue = "false") protected Object valueMatchId; protected Map<Integer, ReferenceType> references;//R-References @XmlAttribute(name = "id", required = true) @XmlElement(required = false) protected Object defaultValue; @XmlElement(required = true) protected Integer id; @XmlElement(required = true) private String pk; @XmlElement(required = true) private String pool;
// Path: api/src/main/java/org/openmrs/module/dataimporttool/dmt/helper/ValidationStatuses.java // public enum ValidationStatuses { // RIGHT_TO_LEFT_DATATYPE_COMPATIBILITY, // RIGHT_TO_LEFT_DATATYPE_INCOMPATIBILITY, // LEFT_TO_RIGT_DATATYPE_COMPATIBILITY, // LEFT_TO_RIGT_DATATYPE_INCOMPATIBILITY, // LEFT_TO_RIGHT_SIZE_INCOMPATIBILITY // // } // Path: api/src/main/java/org/openmrs/module/dataimporttool/matchingschema/MatchType.java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import org.openmrs.module.dataimporttool.dmt.helper.ValidationStatuses; @XmlType(name = "matchType", propOrder = { "tupleId", "terminology", "left", "right", "valueMatchId", "references" }) public class MatchType implements ReferencedPart { @XmlElement(required = true) private Integer tupleId; @XmlElement(required = true) protected String terminology; @XmlElement(required = true) protected MatchSideType left; @XmlElement(required = true) protected MatchSideType right; @XmlElement(defaultValue = "false") protected Object valueMatchId; protected Map<Integer, ReferenceType> references;//R-References @XmlAttribute(name = "id", required = true) @XmlElement(required = false) protected Object defaultValue; @XmlElement(required = true) protected Integer id; @XmlElement(required = true) private String pk; @XmlElement(required = true) private String pool;
private List<ValidationStatuses> validationStatuses;
openmrs/openmrs-module-dataimporttool
api/src/main/java/org/openmrs/module/dataimporttool/matchingschema/ReferenceType.java
// Path: api/src/main/java/org/openmrs/module/dataimporttool/dmt/helper/ValidationStatuses.java // public enum ValidationStatuses { // RIGHT_TO_LEFT_DATATYPE_COMPATIBILITY, // RIGHT_TO_LEFT_DATATYPE_INCOMPATIBILITY, // LEFT_TO_RIGT_DATATYPE_COMPATIBILITY, // LEFT_TO_RIGT_DATATYPE_INCOMPATIBILITY, // LEFT_TO_RIGHT_SIZE_INCOMPATIBILITY // // }
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import org.openmrs.module.dataimporttool.dmt.helper.ValidationStatuses;
/** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.module.dataimporttool.matchingschema; /** * <p>Java class for referenceType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * */ @SuppressWarnings("restriction") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "referenceType", propOrder = { "referencee", "referenced", "nameDesc", "datatype", "size", "predecessor", "referencedValue" }) public class ReferenceType { @XmlElement(required = true) protected ReferenceSideType referencee; @XmlElement(required = true) protected ReferenceSideType referenced; @XmlElement(name = "name_desc") protected String nameDesc; @XmlElement(required = true) protected String datatype; @XmlElement(required = true) protected Integer size; @XmlElement(required = true) protected Integer predecessor; @XmlElement(required = true) protected Object referencedValue; @XmlAttribute(name = "id", required = true) protected Integer id;
// Path: api/src/main/java/org/openmrs/module/dataimporttool/dmt/helper/ValidationStatuses.java // public enum ValidationStatuses { // RIGHT_TO_LEFT_DATATYPE_COMPATIBILITY, // RIGHT_TO_LEFT_DATATYPE_INCOMPATIBILITY, // LEFT_TO_RIGT_DATATYPE_COMPATIBILITY, // LEFT_TO_RIGT_DATATYPE_INCOMPATIBILITY, // LEFT_TO_RIGHT_SIZE_INCOMPATIBILITY // // } // Path: api/src/main/java/org/openmrs/module/dataimporttool/matchingschema/ReferenceType.java import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import org.openmrs.module.dataimporttool.dmt.helper.ValidationStatuses; /** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.module.dataimporttool.matchingschema; /** * <p>Java class for referenceType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * */ @SuppressWarnings("restriction") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "referenceType", propOrder = { "referencee", "referenced", "nameDesc", "datatype", "size", "predecessor", "referencedValue" }) public class ReferenceType { @XmlElement(required = true) protected ReferenceSideType referencee; @XmlElement(required = true) protected ReferenceSideType referenced; @XmlElement(name = "name_desc") protected String nameDesc; @XmlElement(required = true) protected String datatype; @XmlElement(required = true) protected Integer size; @XmlElement(required = true) protected Integer predecessor; @XmlElement(required = true) protected Object referencedValue; @XmlAttribute(name = "id", required = true) protected Integer id;
private List<ValidationStatuses> validationStatuses;
openmrs/openmrs-module-dataimporttool
api/src/main/java/org/openmrs/module/dataimporttool/dmt/util/KeyPoolUtil.java
// Path: api/src/main/java/org/openmrs/module/dataimporttool/dmt/helper/SystemException.java // public class SystemException extends Exception { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public SystemException() { // super(); // } // // public SystemException(String msg) { // super(msg); // } // }
import java.util.HashMap; import java.util.Map; import org.openmrs.module.dataimporttool.dmt.helper.SystemException;
/** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.module.dataimporttool.dmt.util; /** * This class create pools of TOPs, it is used to access a TOP value from a * tuple that has no parenthood with the TOP that it wants to access the value * */ public class KeyPoolUtil { private static final Map<Integer/* Tuple */, Map<Object/* CURR */, Integer/* TOP */>> keyPools = new HashMap<Integer, Map<Object, Integer>>(); public KeyPoolUtil() { // TODO Auto-generated constructor stub } /** * Add a value to an existing pool. It creates the pool if doesn't exist * * @param tuple * @param curr * @param top */ public void putPool(Integer tuple, Object curr, Integer top) { Map<Object, Integer> keyPool = keyPools.get(tuple); if (keyPool == null) { keyPool = new HashMap<Object, Integer>(); keyPools.put(tuple, keyPool); } keyPool.put(curr, top); } /** * Retrieve a pooled TOP value * * @param tuple * @param curr * @return * @throws SystemException */ public Integer getPoolValues(Integer tuple, Object curr)
// Path: api/src/main/java/org/openmrs/module/dataimporttool/dmt/helper/SystemException.java // public class SystemException extends Exception { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public SystemException() { // super(); // } // // public SystemException(String msg) { // super(msg); // } // } // Path: api/src/main/java/org/openmrs/module/dataimporttool/dmt/util/KeyPoolUtil.java import java.util.HashMap; import java.util.Map; import org.openmrs.module.dataimporttool.dmt.helper.SystemException; /** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.module.dataimporttool.dmt.util; /** * This class create pools of TOPs, it is used to access a TOP value from a * tuple that has no parenthood with the TOP that it wants to access the value * */ public class KeyPoolUtil { private static final Map<Integer/* Tuple */, Map<Object/* CURR */, Integer/* TOP */>> keyPools = new HashMap<Integer, Map<Object, Integer>>(); public KeyPoolUtil() { // TODO Auto-generated constructor stub } /** * Add a value to an existing pool. It creates the pool if doesn't exist * * @param tuple * @param curr * @param top */ public void putPool(Integer tuple, Object curr, Integer top) { Map<Object, Integer> keyPool = keyPools.get(tuple); if (keyPool == null) { keyPool = new HashMap<Object, Integer>(); keyPools.put(tuple, keyPool); } keyPool.put(curr, top); } /** * Retrieve a pooled TOP value * * @param tuple * @param curr * @return * @throws SystemException */ public Integer getPoolValues(Integer tuple, Object curr)
throws SystemException {
OpenSourcePhysics/STP
src/org/opensourcephysics/stp/thermalcontact/ThermalContactApp.java
// Path: src/org/opensourcephysics/stp/util/DoubleArray.java // public class DoubleArray { // private int length; // private double[] data; // // /* // * Static methods // */ // // /** // * Concatenates two double[]s into one. // * // * @param a // * @param b // * @return a+b // */ // public static double[] concat(double[] a, double[] b) { // double[] ret = new double[a.length+b.length]; // System.arraycopy(a, 0, ret, 0, a.length); // System.arraycopy(b, 0, ret, a.length, b.length); // return ret; // } // // /** // * Finds the index i which maximizes a[i] // * // * @param a // * @return maximizing index // */ // public static int maxIndex(double[] a) { // // assert (a.length > 0); // int maxi = 0; // double max = a[0]; // for(int i = 1; i<a.length; i++) { // if(a[i]>max) { // max = a[i]; // maxi = i; // } // } // return maxi; // } // // /** // * Finds the index i which minimizes a[i] // * // * @param a // * @return minimizing index // */ // public static int minIndex(double[] a) { // // assert (a.length > 0); // int mini = 0; // double min = a[0]; // for(int i = 1; i<a.length; i++) { // if(a[i]<min) { // min = a[i]; // mini = i; // } // } // return mini; // } // // /** // * Finds the maximum value in a[] // * // * @param a // * @return max{a} // */ // public static double max(double[] a) { // return a[maxIndex(a)]; // } // // /** // * Finds the minimum value in a[] // * // * @param a // * @return min{a} // */ // public static double min(double[] a) { // return a[minIndex(a)]; // } // // /* // * Dynamic methods // */ // // /** // * Constructs a new DoubleArray // */ // public DoubleArray() { // data = new double[128]; // length = 0; // } // // /** // * Returns the length of the array // */ // public int length() { // return length; // } // // /** // * Appends a value // * // * @param x // */ // public void append(double x) { // if(length>=data.length) { // increaseCapacity(); // } // data[length++] = x; // } // // /** // * Gets an indexed value // * // * @param i // * @return array[i] // */ // public double get(int i) { // if(i>=length) { // throw new ArrayIndexOutOfBoundsException(); // } // return data[i]; // } // // private void increaseCapacity() { // double[] temp = new double[2*length]; // System.arraycopy(data, 0, temp, 0, length); // data = temp; // } // // }
import java.awt.Color; import java.text.NumberFormat; import org.opensourcephysics.controls.*; import org.opensourcephysics.frames.*; import org.opensourcephysics.stp.util.DoubleArray;
kinFrame.append(0, time, sim1.Ka/sim1.Na); kinFrame.append(1, time, sim2.Kb/sim2.Nb); potFrame.append(0, time, sim1.Va/sim1.Na); potFrame.append(1, time, sim2.Vb/sim2.Nb); energy = sim1.Ka+sim2.Kb+sim1.Va+sim2.Vb; } else { kinFrame.append(0, time, sim1.Ka/sim1.Na); kinFrame.append(1, time, sim1.Kb/sim1.Nb); potFrame.append(0, time, sim1.Va/sim1.Na); potFrame.append(1, time, sim1.Vb/sim1.Nb); energy = sim1.Ka+sim1.Kb+sim1.Va+sim1.Vb; } control.clearMessages(); control.println("Time = "+ControlUtils.f2(time)); control.println("Total energy = "+ControlUtils.f2(energy)); } public void connectBoxes() { if(sim2==null) { return; } double dt = control.getDouble("\u2206t"); double siga = 1; // control.getDouble("\u03C3 (red-red)"); double sigb = 1.2; // control.getDouble("\u03C3 (green-green)"); int Na = board1.Na; int Nb = board2.Nb; double Lx = board1.Lx+board2.Lx; double Ly = board1.Ly; // concatenate both boxes into one LJSimulation sim = new LJSimulation(Na, Nb, Lx, Ly, dt);
// Path: src/org/opensourcephysics/stp/util/DoubleArray.java // public class DoubleArray { // private int length; // private double[] data; // // /* // * Static methods // */ // // /** // * Concatenates two double[]s into one. // * // * @param a // * @param b // * @return a+b // */ // public static double[] concat(double[] a, double[] b) { // double[] ret = new double[a.length+b.length]; // System.arraycopy(a, 0, ret, 0, a.length); // System.arraycopy(b, 0, ret, a.length, b.length); // return ret; // } // // /** // * Finds the index i which maximizes a[i] // * // * @param a // * @return maximizing index // */ // public static int maxIndex(double[] a) { // // assert (a.length > 0); // int maxi = 0; // double max = a[0]; // for(int i = 1; i<a.length; i++) { // if(a[i]>max) { // max = a[i]; // maxi = i; // } // } // return maxi; // } // // /** // * Finds the index i which minimizes a[i] // * // * @param a // * @return minimizing index // */ // public static int minIndex(double[] a) { // // assert (a.length > 0); // int mini = 0; // double min = a[0]; // for(int i = 1; i<a.length; i++) { // if(a[i]<min) { // min = a[i]; // mini = i; // } // } // return mini; // } // // /** // * Finds the maximum value in a[] // * // * @param a // * @return max{a} // */ // public static double max(double[] a) { // return a[maxIndex(a)]; // } // // /** // * Finds the minimum value in a[] // * // * @param a // * @return min{a} // */ // public static double min(double[] a) { // return a[minIndex(a)]; // } // // /* // * Dynamic methods // */ // // /** // * Constructs a new DoubleArray // */ // public DoubleArray() { // data = new double[128]; // length = 0; // } // // /** // * Returns the length of the array // */ // public int length() { // return length; // } // // /** // * Appends a value // * // * @param x // */ // public void append(double x) { // if(length>=data.length) { // increaseCapacity(); // } // data[length++] = x; // } // // /** // * Gets an indexed value // * // * @param i // * @return array[i] // */ // public double get(int i) { // if(i>=length) { // throw new ArrayIndexOutOfBoundsException(); // } // return data[i]; // } // // private void increaseCapacity() { // double[] temp = new double[2*length]; // System.arraycopy(data, 0, temp, 0, length); // data = temp; // } // // } // Path: src/org/opensourcephysics/stp/thermalcontact/ThermalContactApp.java import java.awt.Color; import java.text.NumberFormat; import org.opensourcephysics.controls.*; import org.opensourcephysics.frames.*; import org.opensourcephysics.stp.util.DoubleArray; kinFrame.append(0, time, sim1.Ka/sim1.Na); kinFrame.append(1, time, sim2.Kb/sim2.Nb); potFrame.append(0, time, sim1.Va/sim1.Na); potFrame.append(1, time, sim2.Vb/sim2.Nb); energy = sim1.Ka+sim2.Kb+sim1.Va+sim2.Vb; } else { kinFrame.append(0, time, sim1.Ka/sim1.Na); kinFrame.append(1, time, sim1.Kb/sim1.Nb); potFrame.append(0, time, sim1.Va/sim1.Na); potFrame.append(1, time, sim1.Vb/sim1.Nb); energy = sim1.Ka+sim1.Kb+sim1.Va+sim1.Vb; } control.clearMessages(); control.println("Time = "+ControlUtils.f2(time)); control.println("Total energy = "+ControlUtils.f2(energy)); } public void connectBoxes() { if(sim2==null) { return; } double dt = control.getDouble("\u2206t"); double siga = 1; // control.getDouble("\u03C3 (red-red)"); double sigb = 1.2; // control.getDouble("\u03C3 (green-green)"); int Na = board1.Na; int Nb = board2.Nb; double Lx = board1.Lx+board2.Lx; double Ly = board1.Ly; // concatenate both boxes into one LJSimulation sim = new LJSimulation(Na, Nb, Lx, Ly, dt);
sim.x = DoubleArray.concat(sim1.x, sim2.x);
OpenSourcePhysics/STP
src/org/opensourcephysics/stp/lj/LJfluidApp.java
// Path: src/org/opensourcephysics/stp/util/Rdf.java // public class Rdf { // public double bin = 0.1; // public double[] x, y; // public double Lx, Ly; // public double rmax; // public int N, nbins; // public boolean pbc = true; // public int ncorr = 0; // double[] gr; // public double[] rx, ngr; // normalized gr // // /** // * Constructor Rdf // */ // public Rdf() {} // // /** // * Constructor Rdf // * @param lx // * @param ly // */ // public Rdf(double lx, double ly) { // initialize(lx, ly, 0.1); // } // // public void initialize(double lx, double ly, double _bin) { // Lx = lx; // Ly = ly; // rmax = (Lx>Ly) // ? 0.5*Lx // : 0.5*Ly; // bin = _bin; // nbins = (int) Math.ceil(rmax/bin); // gr = new double[nbins]; // ngr = new double[nbins]; // rx = new double[nbins]; // for(int i = 0; i<nbins; i++) { // rx[i] = i*bin; // gr[i] = 0.0; // } // } // // public void reset() { // for(int i = 0; i<nbins; i++) { // rx[i] = i*bin; // gr[i] = 0.0; // } // ncorr = 0; // } // // public void append(double[] x, double[] y) { // N = x.length; // ncorr++; // for(int i = 0; i<N; i++) { // for(int j = i+1; j<N; j++) { // double dx = x[i]-x[j]; // double dy = y[i]-y[j]; // if(pbc) { // dx = separation(dx, Lx); // dy = separation(dy, Ly); // } // double dr = dx*dx+dy*dy; // dr = Math.sqrt(dr); // int nbin = (int) ((dr+0.0000001)/bin); // if(nbin<nbins) { // //if(nbin == 9)System.out.println(dr); // gr[nbin]++; // } // } // } // } // // public void normalize() { // double area; // double pi = Math.PI; // int i = 0; // int imax = (int) (rmax/bin); // double rho = N/Lx/Ly; // double norm = 0.5*rho*ncorr*N; // while(i<imax) { // double r = i*bin; // area = pi*((r+bin)*(r+bin)-r*r); // area *= norm; // ngr[i] = gr[i]/area; // i++; // } // } // // public void setBinSize(double _bin) { // bin = _bin; // nbins = (int) (rmax/bin)+1; // } // // public void setPbc(boolean p) { // pbc = p; // } // // public double separation(double dx, double lx) { // if(dx>0.5*lx) { // return dx-lx; // } // if(dx<-0.5*lx) { // return dx+lx; // } // return dx; // } // // }
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuItem; import org.opensourcephysics.controls.*; import org.opensourcephysics.display.DrawingPanel; import org.opensourcephysics.display.GUIUtils; import org.opensourcephysics.display.OSPFrame; import org.opensourcephysics.display.OSPRuntime; import org.opensourcephysics.frames.*; import org.opensourcephysics.stp.util.Rdf;
/* * Open Source Physics software is free software as described near the bottom of this code file. * * For additional information and documentation on Open Source Physics please see: * <http://www.opensourcephysics.org/> */ package org.opensourcephysics.stp.lj; /** * LJfluidApp simulates a two-dimensional system of interacting particles * via the Lennard-Jones potential. * * @author Jan Tobochnik, Wolfgang Christian, Harvey Gould * @version 1.0 revised 03/28/05, 3/29/05, 8/14/08 */ public class LJfluidApp extends AbstractSimulation { LJfluid md = new LJfluid(); PlotFrame pressureData = new PlotFrame("time", "PA/NkT", "Mean pressure"); PlotFrame temperatureData = new PlotFrame("time", "temperature", "Temperature"); HistogramFrame xVelocityHistogram = new HistogramFrame("vx", "H(vx)", "Velocity histogram"); DisplayFrame displayFrame= new DisplayFrame("x", "y", "Lennard-Jones system"); DrawingPanel displayPanel; PlotFrame grFrame = new PlotFrame("r", "g(r)", "Radial distribution function");
// Path: src/org/opensourcephysics/stp/util/Rdf.java // public class Rdf { // public double bin = 0.1; // public double[] x, y; // public double Lx, Ly; // public double rmax; // public int N, nbins; // public boolean pbc = true; // public int ncorr = 0; // double[] gr; // public double[] rx, ngr; // normalized gr // // /** // * Constructor Rdf // */ // public Rdf() {} // // /** // * Constructor Rdf // * @param lx // * @param ly // */ // public Rdf(double lx, double ly) { // initialize(lx, ly, 0.1); // } // // public void initialize(double lx, double ly, double _bin) { // Lx = lx; // Ly = ly; // rmax = (Lx>Ly) // ? 0.5*Lx // : 0.5*Ly; // bin = _bin; // nbins = (int) Math.ceil(rmax/bin); // gr = new double[nbins]; // ngr = new double[nbins]; // rx = new double[nbins]; // for(int i = 0; i<nbins; i++) { // rx[i] = i*bin; // gr[i] = 0.0; // } // } // // public void reset() { // for(int i = 0; i<nbins; i++) { // rx[i] = i*bin; // gr[i] = 0.0; // } // ncorr = 0; // } // // public void append(double[] x, double[] y) { // N = x.length; // ncorr++; // for(int i = 0; i<N; i++) { // for(int j = i+1; j<N; j++) { // double dx = x[i]-x[j]; // double dy = y[i]-y[j]; // if(pbc) { // dx = separation(dx, Lx); // dy = separation(dy, Ly); // } // double dr = dx*dx+dy*dy; // dr = Math.sqrt(dr); // int nbin = (int) ((dr+0.0000001)/bin); // if(nbin<nbins) { // //if(nbin == 9)System.out.println(dr); // gr[nbin]++; // } // } // } // } // // public void normalize() { // double area; // double pi = Math.PI; // int i = 0; // int imax = (int) (rmax/bin); // double rho = N/Lx/Ly; // double norm = 0.5*rho*ncorr*N; // while(i<imax) { // double r = i*bin; // area = pi*((r+bin)*(r+bin)-r*r); // area *= norm; // ngr[i] = gr[i]/area; // i++; // } // } // // public void setBinSize(double _bin) { // bin = _bin; // nbins = (int) (rmax/bin)+1; // } // // public void setPbc(boolean p) { // pbc = p; // } // // public double separation(double dx, double lx) { // if(dx>0.5*lx) { // return dx-lx; // } // if(dx<-0.5*lx) { // return dx+lx; // } // return dx; // } // // } // Path: src/org/opensourcephysics/stp/lj/LJfluidApp.java import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuItem; import org.opensourcephysics.controls.*; import org.opensourcephysics.display.DrawingPanel; import org.opensourcephysics.display.GUIUtils; import org.opensourcephysics.display.OSPFrame; import org.opensourcephysics.display.OSPRuntime; import org.opensourcephysics.frames.*; import org.opensourcephysics.stp.util.Rdf; /* * Open Source Physics software is free software as described near the bottom of this code file. * * For additional information and documentation on Open Source Physics please see: * <http://www.opensourcephysics.org/> */ package org.opensourcephysics.stp.lj; /** * LJfluidApp simulates a two-dimensional system of interacting particles * via the Lennard-Jones potential. * * @author Jan Tobochnik, Wolfgang Christian, Harvey Gould * @version 1.0 revised 03/28/05, 3/29/05, 8/14/08 */ public class LJfluidApp extends AbstractSimulation { LJfluid md = new LJfluid(); PlotFrame pressureData = new PlotFrame("time", "PA/NkT", "Mean pressure"); PlotFrame temperatureData = new PlotFrame("time", "temperature", "Temperature"); HistogramFrame xVelocityHistogram = new HistogramFrame("vx", "H(vx)", "Velocity histogram"); DisplayFrame displayFrame= new DisplayFrame("x", "y", "Lennard-Jones system"); DrawingPanel displayPanel; PlotFrame grFrame = new PlotFrame("r", "g(r)", "Radial distribution function");
Rdf gr = new Rdf();
OpenSourcePhysics/STP
src/org/opensourcephysics/stp/binomial/BinomialApp.java
// Path: src/org/opensourcephysics/stp/util/MyMath.java // public class MyMath { // private MyMath() {} // don't allow users to instantiate this class // // public static double logBase10(double n) { // return Math.log(n)/Math.log(10); // } // // public static int factorial(int n) { // if(n<0) { // throw new IllegalArgumentException("Can't compute the factorial of a number less than 0"); // } // int total = 1; // for(int i = n; i>1; i--) { // total *= i; // } // return total; // } // // public static double factorial(double n) { // if(n<0) { // throw new IllegalArgumentException("Can't compute the factorial of a number less than 0"); // } // double total = 1; // for(double i = n; i>1; i--) { // total *= i; // } // return total; // } // // public static double stirling(int n) { // if(n==0) { // return 0; // } // double result = n*Math.log(n)-n+0.5*Math.log(2.0*Math.PI*n); // return result; // } // // }
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuItem; import org.opensourcephysics.controls.*; import org.opensourcephysics.frames.*; import org.opensourcephysics.stp.util.MyMath; import org.opensourcephysics.display.DatasetManager; import org.opensourcephysics.display.GUIUtils; import org.opensourcephysics.display.OSPFrame; import org.opensourcephysics.display.OSPRuntime;
/* * Open Source Physics software is free software as described near the bottom of this code file. * * For additional information and documentation on Open Source Physics please see: * <http://www.opensourcephysics.org/> */ package org.opensourcephysics.stp.binomial; /** * put your documentation comment here * * @author Hui Wang * @created Oct 18, 2006 */ public class BinomialApp extends AbstractCalculation { int N; double p; final static int MAXIMUM_NUMERATOR = 20; final static double tol = 1e-100; int counter = 0; double[] nbar = new double[100]; PlotFrame plotFrame = new PlotFrame("n", "P", "P(n) versus n"); PlotFrame plotFrameNorm = new PlotFrame("n/<n>", "P", "P(n) versus n/<n>"); DatasetManager data = new DatasetManager(); /** * Constructor BinomialApp */ public BinomialApp() { plotFrame.setAutoscaleY(true); plotFrame.setAutoscaleX(true); plotFrameNorm.setAutoscaleY(true); plotFrameNorm.setAutoscaleX(true); } public void addPoints() { double log_N = 0; double log_n1 = 0, log_n2 = 0; boolean stirling = false; stirling = N>MAXIMUM_NUMERATOR; for(int i = 0; i<=N; i++) { if(stirling) {
// Path: src/org/opensourcephysics/stp/util/MyMath.java // public class MyMath { // private MyMath() {} // don't allow users to instantiate this class // // public static double logBase10(double n) { // return Math.log(n)/Math.log(10); // } // // public static int factorial(int n) { // if(n<0) { // throw new IllegalArgumentException("Can't compute the factorial of a number less than 0"); // } // int total = 1; // for(int i = n; i>1; i--) { // total *= i; // } // return total; // } // // public static double factorial(double n) { // if(n<0) { // throw new IllegalArgumentException("Can't compute the factorial of a number less than 0"); // } // double total = 1; // for(double i = n; i>1; i--) { // total *= i; // } // return total; // } // // public static double stirling(int n) { // if(n==0) { // return 0; // } // double result = n*Math.log(n)-n+0.5*Math.log(2.0*Math.PI*n); // return result; // } // // } // Path: src/org/opensourcephysics/stp/binomial/BinomialApp.java import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuItem; import org.opensourcephysics.controls.*; import org.opensourcephysics.frames.*; import org.opensourcephysics.stp.util.MyMath; import org.opensourcephysics.display.DatasetManager; import org.opensourcephysics.display.GUIUtils; import org.opensourcephysics.display.OSPFrame; import org.opensourcephysics.display.OSPRuntime; /* * Open Source Physics software is free software as described near the bottom of this code file. * * For additional information and documentation on Open Source Physics please see: * <http://www.opensourcephysics.org/> */ package org.opensourcephysics.stp.binomial; /** * put your documentation comment here * * @author Hui Wang * @created Oct 18, 2006 */ public class BinomialApp extends AbstractCalculation { int N; double p; final static int MAXIMUM_NUMERATOR = 20; final static double tol = 1e-100; int counter = 0; double[] nbar = new double[100]; PlotFrame plotFrame = new PlotFrame("n", "P", "P(n) versus n"); PlotFrame plotFrameNorm = new PlotFrame("n/<n>", "P", "P(n) versus n/<n>"); DatasetManager data = new DatasetManager(); /** * Constructor BinomialApp */ public BinomialApp() { plotFrame.setAutoscaleY(true); plotFrame.setAutoscaleX(true); plotFrameNorm.setAutoscaleY(true); plotFrameNorm.setAutoscaleX(true); } public void addPoints() { double log_N = 0; double log_n1 = 0, log_n2 = 0; boolean stirling = false; stirling = N>MAXIMUM_NUMERATOR; for(int i = 0; i<=N; i++) { if(stirling) {
log_N = MyMath.stirling(N);
OpenSourcePhysics/STP
src/org/opensourcephysics/stp/entropy/EntropyApp.java
// Path: src/org/opensourcephysics/stp/util/MyMath.java // public class MyMath { // private MyMath() {} // don't allow users to instantiate this class // // public static double logBase10(double n) { // return Math.log(n)/Math.log(10); // } // // public static int factorial(int n) { // if(n<0) { // throw new IllegalArgumentException("Can't compute the factorial of a number less than 0"); // } // int total = 1; // for(int i = n; i>1; i--) { // total *= i; // } // return total; // } // // public static double factorial(double n) { // if(n<0) { // throw new IllegalArgumentException("Can't compute the factorial of a number less than 0"); // } // double total = 1; // for(double i = n; i>1; i--) { // total *= i; // } // return total; // } // // public static double stirling(int n) { // if(n==0) { // return 0; // } // double result = n*Math.log(n)-n+0.5*Math.log(2.0*Math.PI*n); // return result; // } // // }
import java.awt.Color; import java.awt.event.MouseEvent; import java.text.NumberFormat; import org.opensourcephysics.controls.*; import org.opensourcephysics.display.Dataset; import org.opensourcephysics.display.InteractiveMouseHandler; import org.opensourcephysics.display.InteractivePanel; import org.opensourcephysics.frames.*; import org.opensourcephysics.stp.util.MyMath;
/* * Open Source Physics software is free software as described near the bottom of this code file. * * For additional information and documentation on Open Source Physics please see: * <http://www.opensourcephysics.org/> */ package org.opensourcephysics.stp.entropy; /** * put your documentation comment here * @author Hui Wang * @author Joshua Gould * @author Peter Sibley * @created January 28, 2002 */ public class EntropyApp extends AbstractCalculation implements InteractiveMouseHandler { boolean showTable = false; int E, Na, Nb; int cid = 0; final static int MAXIMUM_NUMERATOR = 20; //TableFrame tableFrame = new TableFrame("table"); PlotFrame plotFrame = new PlotFrame("E_a", "Entropy", "Entropy"); /** * Constructor EntropyApp */ public EntropyApp() { plotFrame.setMarkerColor(0, Color.red); plotFrame.setMarkerColor(1, Color.blue); plotFrame.setMarkerColor(2, Color.GREEN); //tableFrame.setColumnNames(0, "S(E_a)"); //tableFrame.setColumnNames(0, "Ln of omega_a"); //tableFrame.setColumnNames(0, "Ln of omega_b"); } public void addPoints() { for(int i = 0; i<=E; i++) { int Ea = i; int Eb = E-Ea; double log_omegaA = 0; double log_omegaB = 0; if((Ea+Na-1)>MAXIMUM_NUMERATOR) {
// Path: src/org/opensourcephysics/stp/util/MyMath.java // public class MyMath { // private MyMath() {} // don't allow users to instantiate this class // // public static double logBase10(double n) { // return Math.log(n)/Math.log(10); // } // // public static int factorial(int n) { // if(n<0) { // throw new IllegalArgumentException("Can't compute the factorial of a number less than 0"); // } // int total = 1; // for(int i = n; i>1; i--) { // total *= i; // } // return total; // } // // public static double factorial(double n) { // if(n<0) { // throw new IllegalArgumentException("Can't compute the factorial of a number less than 0"); // } // double total = 1; // for(double i = n; i>1; i--) { // total *= i; // } // return total; // } // // public static double stirling(int n) { // if(n==0) { // return 0; // } // double result = n*Math.log(n)-n+0.5*Math.log(2.0*Math.PI*n); // return result; // } // // } // Path: src/org/opensourcephysics/stp/entropy/EntropyApp.java import java.awt.Color; import java.awt.event.MouseEvent; import java.text.NumberFormat; import org.opensourcephysics.controls.*; import org.opensourcephysics.display.Dataset; import org.opensourcephysics.display.InteractiveMouseHandler; import org.opensourcephysics.display.InteractivePanel; import org.opensourcephysics.frames.*; import org.opensourcephysics.stp.util.MyMath; /* * Open Source Physics software is free software as described near the bottom of this code file. * * For additional information and documentation on Open Source Physics please see: * <http://www.opensourcephysics.org/> */ package org.opensourcephysics.stp.entropy; /** * put your documentation comment here * @author Hui Wang * @author Joshua Gould * @author Peter Sibley * @created January 28, 2002 */ public class EntropyApp extends AbstractCalculation implements InteractiveMouseHandler { boolean showTable = false; int E, Na, Nb; int cid = 0; final static int MAXIMUM_NUMERATOR = 20; //TableFrame tableFrame = new TableFrame("table"); PlotFrame plotFrame = new PlotFrame("E_a", "Entropy", "Entropy"); /** * Constructor EntropyApp */ public EntropyApp() { plotFrame.setMarkerColor(0, Color.red); plotFrame.setMarkerColor(1, Color.blue); plotFrame.setMarkerColor(2, Color.GREEN); //tableFrame.setColumnNames(0, "S(E_a)"); //tableFrame.setColumnNames(0, "Ln of omega_a"); //tableFrame.setColumnNames(0, "Ln of omega_b"); } public void addPoints() { for(int i = 0; i<=E; i++) { int Ea = i; int Eb = E-Ea; double log_omegaA = 0; double log_omegaB = 0; if((Ea+Na-1)>MAXIMUM_NUMERATOR) {
log_omegaA = MyMath.stirling(Ea+Na-1)-MyMath.stirling(Ea)-MyMath.stirling(Na-1);
OpenSourcePhysics/STP
src/org/opensourcephysics/stp/hdmc/HDMCApp.java
// Path: src/org/opensourcephysics/stp/util/Rdf.java // public class Rdf { // public double bin = 0.1; // public double[] x, y; // public double Lx, Ly; // public double rmax; // public int N, nbins; // public boolean pbc = true; // public int ncorr = 0; // double[] gr; // public double[] rx, ngr; // normalized gr // // /** // * Constructor Rdf // */ // public Rdf() {} // // /** // * Constructor Rdf // * @param lx // * @param ly // */ // public Rdf(double lx, double ly) { // initialize(lx, ly, 0.1); // } // // public void initialize(double lx, double ly, double _bin) { // Lx = lx; // Ly = ly; // rmax = (Lx>Ly) // ? 0.5*Lx // : 0.5*Ly; // bin = _bin; // nbins = (int) Math.ceil(rmax/bin); // gr = new double[nbins]; // ngr = new double[nbins]; // rx = new double[nbins]; // for(int i = 0; i<nbins; i++) { // rx[i] = i*bin; // gr[i] = 0.0; // } // } // // public void reset() { // for(int i = 0; i<nbins; i++) { // rx[i] = i*bin; // gr[i] = 0.0; // } // ncorr = 0; // } // // public void append(double[] x, double[] y) { // N = x.length; // ncorr++; // for(int i = 0; i<N; i++) { // for(int j = i+1; j<N; j++) { // double dx = x[i]-x[j]; // double dy = y[i]-y[j]; // if(pbc) { // dx = separation(dx, Lx); // dy = separation(dy, Ly); // } // double dr = dx*dx+dy*dy; // dr = Math.sqrt(dr); // int nbin = (int) ((dr+0.0000001)/bin); // if(nbin<nbins) { // //if(nbin == 9)System.out.println(dr); // gr[nbin]++; // } // } // } // } // // public void normalize() { // double area; // double pi = Math.PI; // int i = 0; // int imax = (int) (rmax/bin); // double rho = N/Lx/Ly; // double norm = 0.5*rho*ncorr*N; // while(i<imax) { // double r = i*bin; // area = pi*((r+bin)*(r+bin)-r*r); // area *= norm; // ngr[i] = gr[i]/area; // i++; // } // } // // public void setBinSize(double _bin) { // bin = _bin; // nbins = (int) (rmax/bin)+1; // } // // public void setPbc(boolean p) { // pbc = p; // } // // public double separation(double dx, double lx) { // if(dx>0.5*lx) { // return dx-lx; // } // if(dx<-0.5*lx) { // return dx+lx; // } // return dx; // } // // }
import org.opensourcephysics.controls.*; import org.opensourcephysics.display.GUIUtils; import org.opensourcephysics.frames.DisplayFrame; import org.opensourcephysics.frames.PlotFrame; import org.opensourcephysics.stp.util.Rdf; import org.opensourcephysics.controls.ControlUtils;
/* * Open Source Physics software is free software as described near the bottom of this code file. * * For additional information and documentation on Open Source Physics please see: * <http://www.opensourcephysics.org/> */ package org.opensourcephysics.stp.hdmc; public class HDMCApp extends AbstractSimulation { HDMC mc = new HDMC(); DisplayFrame display = new DisplayFrame("Hard Disks"); PlotFrame grFrame = new PlotFrame("r", "g(r)", "Radial distribution function");
// Path: src/org/opensourcephysics/stp/util/Rdf.java // public class Rdf { // public double bin = 0.1; // public double[] x, y; // public double Lx, Ly; // public double rmax; // public int N, nbins; // public boolean pbc = true; // public int ncorr = 0; // double[] gr; // public double[] rx, ngr; // normalized gr // // /** // * Constructor Rdf // */ // public Rdf() {} // // /** // * Constructor Rdf // * @param lx // * @param ly // */ // public Rdf(double lx, double ly) { // initialize(lx, ly, 0.1); // } // // public void initialize(double lx, double ly, double _bin) { // Lx = lx; // Ly = ly; // rmax = (Lx>Ly) // ? 0.5*Lx // : 0.5*Ly; // bin = _bin; // nbins = (int) Math.ceil(rmax/bin); // gr = new double[nbins]; // ngr = new double[nbins]; // rx = new double[nbins]; // for(int i = 0; i<nbins; i++) { // rx[i] = i*bin; // gr[i] = 0.0; // } // } // // public void reset() { // for(int i = 0; i<nbins; i++) { // rx[i] = i*bin; // gr[i] = 0.0; // } // ncorr = 0; // } // // public void append(double[] x, double[] y) { // N = x.length; // ncorr++; // for(int i = 0; i<N; i++) { // for(int j = i+1; j<N; j++) { // double dx = x[i]-x[j]; // double dy = y[i]-y[j]; // if(pbc) { // dx = separation(dx, Lx); // dy = separation(dy, Ly); // } // double dr = dx*dx+dy*dy; // dr = Math.sqrt(dr); // int nbin = (int) ((dr+0.0000001)/bin); // if(nbin<nbins) { // //if(nbin == 9)System.out.println(dr); // gr[nbin]++; // } // } // } // } // // public void normalize() { // double area; // double pi = Math.PI; // int i = 0; // int imax = (int) (rmax/bin); // double rho = N/Lx/Ly; // double norm = 0.5*rho*ncorr*N; // while(i<imax) { // double r = i*bin; // area = pi*((r+bin)*(r+bin)-r*r); // area *= norm; // ngr[i] = gr[i]/area; // i++; // } // } // // public void setBinSize(double _bin) { // bin = _bin; // nbins = (int) (rmax/bin)+1; // } // // public void setPbc(boolean p) { // pbc = p; // } // // public double separation(double dx, double lx) { // if(dx>0.5*lx) { // return dx-lx; // } // if(dx<-0.5*lx) { // return dx+lx; // } // return dx; // } // // } // Path: src/org/opensourcephysics/stp/hdmc/HDMCApp.java import org.opensourcephysics.controls.*; import org.opensourcephysics.display.GUIUtils; import org.opensourcephysics.frames.DisplayFrame; import org.opensourcephysics.frames.PlotFrame; import org.opensourcephysics.stp.util.Rdf; import org.opensourcephysics.controls.ControlUtils; /* * Open Source Physics software is free software as described near the bottom of this code file. * * For additional information and documentation on Open Source Physics please see: * <http://www.opensourcephysics.org/> */ package org.opensourcephysics.stp.hdmc; public class HDMCApp extends AbstractSimulation { HDMC mc = new HDMC(); DisplayFrame display = new DisplayFrame("Hard Disks"); PlotFrame grFrame = new PlotFrame("r", "g(r)", "Radial distribution function");
Rdf gr = new Rdf();
OpenSourcePhysics/STP
src/org/opensourcephysics/stp/entropy/EntropyApp2.java
// Path: src/org/opensourcephysics/stp/util/MyMath.java // public class MyMath { // private MyMath() {} // don't allow users to instantiate this class // // public static double logBase10(double n) { // return Math.log(n)/Math.log(10); // } // // public static int factorial(int n) { // if(n<0) { // throw new IllegalArgumentException("Can't compute the factorial of a number less than 0"); // } // int total = 1; // for(int i = n; i>1; i--) { // total *= i; // } // return total; // } // // public static double factorial(double n) { // if(n<0) { // throw new IllegalArgumentException("Can't compute the factorial of a number less than 0"); // } // double total = 1; // for(double i = n; i>1; i--) { // total *= i; // } // return total; // } // // public static double stirling(int n) { // if(n==0) { // return 0; // } // double result = n*Math.log(n)-n+0.5*Math.log(2.0*Math.PI*n); // return result; // } // // }
import org.opensourcephysics.controls.*; import org.opensourcephysics.frames.*; import org.opensourcephysics.stp.util.MyMath;
/* * Open Source Physics software is free software as described near the bottom of this code file. * * For additional information and documentation on Open Source Physics please see: * <http://www.opensourcephysics.org/> */ package org.opensourcephysics.stp.entropy; /** * put your documentation comment here * * @author Joshua Gould * @author Peter Sibley * @created January 28, 2002 */ /** * @author nicholas * appears no different from first application. */ public class EntropyApp2 extends AbstractCalculation { boolean showTable = false; int E; // = Ea + Eb int Na; int Nb; final static int MAXIMUM_NUMERATOR = 20; TableFrame tableFrame = new TableFrame("table"); PlotFrame plotFrame = new PlotFrame("E", "S(E)", "Entropy"); /** * Constructor EntropyApp2 */ public EntropyApp2() { tableFrame.setColumnNames(0, "S"); tableFrame.setColumnNames(0, "Ln of omega_a"); tableFrame.setColumnNames(0, "Ln of omega_b"); } public void addPoints() { for(int i = 0; i<=E; i++) { int Ea = i; int Eb = E-Ea; double log_omegaA = 0; double log_omegaB = 0; if((Ea+Na-1)>MAXIMUM_NUMERATOR) {
// Path: src/org/opensourcephysics/stp/util/MyMath.java // public class MyMath { // private MyMath() {} // don't allow users to instantiate this class // // public static double logBase10(double n) { // return Math.log(n)/Math.log(10); // } // // public static int factorial(int n) { // if(n<0) { // throw new IllegalArgumentException("Can't compute the factorial of a number less than 0"); // } // int total = 1; // for(int i = n; i>1; i--) { // total *= i; // } // return total; // } // // public static double factorial(double n) { // if(n<0) { // throw new IllegalArgumentException("Can't compute the factorial of a number less than 0"); // } // double total = 1; // for(double i = n; i>1; i--) { // total *= i; // } // return total; // } // // public static double stirling(int n) { // if(n==0) { // return 0; // } // double result = n*Math.log(n)-n+0.5*Math.log(2.0*Math.PI*n); // return result; // } // // } // Path: src/org/opensourcephysics/stp/entropy/EntropyApp2.java import org.opensourcephysics.controls.*; import org.opensourcephysics.frames.*; import org.opensourcephysics.stp.util.MyMath; /* * Open Source Physics software is free software as described near the bottom of this code file. * * For additional information and documentation on Open Source Physics please see: * <http://www.opensourcephysics.org/> */ package org.opensourcephysics.stp.entropy; /** * put your documentation comment here * * @author Joshua Gould * @author Peter Sibley * @created January 28, 2002 */ /** * @author nicholas * appears no different from first application. */ public class EntropyApp2 extends AbstractCalculation { boolean showTable = false; int E; // = Ea + Eb int Na; int Nb; final static int MAXIMUM_NUMERATOR = 20; TableFrame tableFrame = new TableFrame("table"); PlotFrame plotFrame = new PlotFrame("E", "S(E)", "Entropy"); /** * Constructor EntropyApp2 */ public EntropyApp2() { tableFrame.setColumnNames(0, "S"); tableFrame.setColumnNames(0, "Ln of omega_a"); tableFrame.setColumnNames(0, "Ln of omega_b"); } public void addPoints() { for(int i = 0; i<=E; i++) { int Ea = i; int Eb = E-Ea; double log_omegaA = 0; double log_omegaB = 0; if((Ea+Na-1)>MAXIMUM_NUMERATOR) {
log_omegaA = MyMath.stirling(Ea+Na-1)-MyMath.stirling(Ea)-MyMath.stirling(Na-1);
OpenSourcePhysics/STP
src/org/opensourcephysics/stp/xymodel/XYModel.java
// Path: src/org/opensourcephysics/stp/util/Util.java // public class Util { // public static Color randomColor() { // return new Color((int) (Math.random()*255), (int) (Math.random()*255), (int) (Math.random()*255)); // } // // public static int pbc(int i, int L) { // if(i>=L) { // return i-L; // } else if(i<0) { // return L+i; // } else { // return i; // } // } // // public static void fill(Random random, int[][] site, double p, int up, int down) { // for(int i = 0; i<site.length; i++) { // for(int j = 0; j<site[0].length; j++) { // double d = random.nextDouble(); // if(d<p) { // site[i][j] = up; // } else { // site[i][j] = down; // } // } // } // } // // public static void fill(Random random, int[][] site, double p) { // for(int i = 0; i<site.length; i++) { // for(int j = 0; j<site[0].length; j++) { // double d = random.nextDouble(); // if(d<p) { // site[i][j] = 1; // } else { // site[i][j] = 0; // } // } // } // } // // public static Function computeLinearRegression(Dataset dataset) { // double xBar_yBar = 0; // double xBar = 0; // double yBar = 0; // double x2Bar = 0; // double x = 0; // double y = 0; // double[] xpoints = dataset.getXPoints(); // double[] ypoints = dataset.getYPoints(); // for(int i = 0; i<xpoints.length; i++) { // x = xpoints[i]; // y = ypoints[i]; // xBar_yBar += x*y; // xBar += x; // yBar += y; // x2Bar += x*x; // } // int n = xpoints.length; // xBar_yBar = xBar_yBar/n; // xBar = xBar/n; // yBar = yBar/n; // x2Bar = x2Bar/n; // double deltaX2 = x2Bar-xBar*xBar; // final double m = (xBar_yBar-xBar*yBar)/deltaX2; // final double b = yBar-m*xBar; // return new Function() { // public double evaluate(double x) { // return m*x+b; // } // // }; // } // // }
import java.awt.*; import java.awt.geom.*; import java.util.Random; import org.opensourcephysics.display.*; import org.opensourcephysics.stp.util.Util;
* @return The completed value */ public boolean isCompleted() { return(time>mcs); } /** * Set linear dimension of lattice, It also has the effect of clearing the * exisiting lattice. * * @param _L * The new linearDimension value */ public void setLinearDimension(int _L) { L = _L; spin = new double[L][L]; numberOfSpins = L*L; correlation = new double[L]; norm = new double[L]; } /** * compute total energy of system * * @return The totalEnergy value */ public double getTotalEnergy() { double sum = 0; for(int x = 0; x<L; x++) { for(int y = 0; y<L; y++) {
// Path: src/org/opensourcephysics/stp/util/Util.java // public class Util { // public static Color randomColor() { // return new Color((int) (Math.random()*255), (int) (Math.random()*255), (int) (Math.random()*255)); // } // // public static int pbc(int i, int L) { // if(i>=L) { // return i-L; // } else if(i<0) { // return L+i; // } else { // return i; // } // } // // public static void fill(Random random, int[][] site, double p, int up, int down) { // for(int i = 0; i<site.length; i++) { // for(int j = 0; j<site[0].length; j++) { // double d = random.nextDouble(); // if(d<p) { // site[i][j] = up; // } else { // site[i][j] = down; // } // } // } // } // // public static void fill(Random random, int[][] site, double p) { // for(int i = 0; i<site.length; i++) { // for(int j = 0; j<site[0].length; j++) { // double d = random.nextDouble(); // if(d<p) { // site[i][j] = 1; // } else { // site[i][j] = 0; // } // } // } // } // // public static Function computeLinearRegression(Dataset dataset) { // double xBar_yBar = 0; // double xBar = 0; // double yBar = 0; // double x2Bar = 0; // double x = 0; // double y = 0; // double[] xpoints = dataset.getXPoints(); // double[] ypoints = dataset.getYPoints(); // for(int i = 0; i<xpoints.length; i++) { // x = xpoints[i]; // y = ypoints[i]; // xBar_yBar += x*y; // xBar += x; // yBar += y; // x2Bar += x*x; // } // int n = xpoints.length; // xBar_yBar = xBar_yBar/n; // xBar = xBar/n; // yBar = yBar/n; // x2Bar = x2Bar/n; // double deltaX2 = x2Bar-xBar*xBar; // final double m = (xBar_yBar-xBar*yBar)/deltaX2; // final double b = yBar-m*xBar; // return new Function() { // public double evaluate(double x) { // return m*x+b; // } // // }; // } // // } // Path: src/org/opensourcephysics/stp/xymodel/XYModel.java import java.awt.*; import java.awt.geom.*; import java.util.Random; import org.opensourcephysics.display.*; import org.opensourcephysics.stp.util.Util; * @return The completed value */ public boolean isCompleted() { return(time>mcs); } /** * Set linear dimension of lattice, It also has the effect of clearing the * exisiting lattice. * * @param _L * The new linearDimension value */ public void setLinearDimension(int _L) { L = _L; spin = new double[L][L]; numberOfSpins = L*L; correlation = new double[L]; norm = new double[L]; } /** * compute total energy of system * * @return The totalEnergy value */ public double getTotalEnergy() { double sum = 0; for(int x = 0; x<L; x++) { for(int y = 0; y<L; y++) {
sum += Math.cos(spin[x][y]-spin[Util.pbc(x+1, L)][y]);
OpenSourcePhysics/STP
src/org/opensourcephysics/stp/ljmc/LJMCApp.java
// Path: src/org/opensourcephysics/stp/util/Rdf.java // public class Rdf { // public double bin = 0.1; // public double[] x, y; // public double Lx, Ly; // public double rmax; // public int N, nbins; // public boolean pbc = true; // public int ncorr = 0; // double[] gr; // public double[] rx, ngr; // normalized gr // // /** // * Constructor Rdf // */ // public Rdf() {} // // /** // * Constructor Rdf // * @param lx // * @param ly // */ // public Rdf(double lx, double ly) { // initialize(lx, ly, 0.1); // } // // public void initialize(double lx, double ly, double _bin) { // Lx = lx; // Ly = ly; // rmax = (Lx>Ly) // ? 0.5*Lx // : 0.5*Ly; // bin = _bin; // nbins = (int) Math.ceil(rmax/bin); // gr = new double[nbins]; // ngr = new double[nbins]; // rx = new double[nbins]; // for(int i = 0; i<nbins; i++) { // rx[i] = i*bin; // gr[i] = 0.0; // } // } // // public void reset() { // for(int i = 0; i<nbins; i++) { // rx[i] = i*bin; // gr[i] = 0.0; // } // ncorr = 0; // } // // public void append(double[] x, double[] y) { // N = x.length; // ncorr++; // for(int i = 0; i<N; i++) { // for(int j = i+1; j<N; j++) { // double dx = x[i]-x[j]; // double dy = y[i]-y[j]; // if(pbc) { // dx = separation(dx, Lx); // dy = separation(dy, Ly); // } // double dr = dx*dx+dy*dy; // dr = Math.sqrt(dr); // int nbin = (int) ((dr+0.0000001)/bin); // if(nbin<nbins) { // //if(nbin == 9)System.out.println(dr); // gr[nbin]++; // } // } // } // } // // public void normalize() { // double area; // double pi = Math.PI; // int i = 0; // int imax = (int) (rmax/bin); // double rho = N/Lx/Ly; // double norm = 0.5*rho*ncorr*N; // while(i<imax) { // double r = i*bin; // area = pi*((r+bin)*(r+bin)-r*r); // area *= norm; // ngr[i] = gr[i]/area; // i++; // } // } // // public void setBinSize(double _bin) { // bin = _bin; // nbins = (int) (rmax/bin)+1; // } // // public void setPbc(boolean p) { // pbc = p; // } // // public double separation(double dx, double lx) { // if(dx>0.5*lx) { // return dx-lx; // } // if(dx<-0.5*lx) { // return dx+lx; // } // return dx; // } // // }
import org.opensourcephysics.controls.AbstractSimulation; import org.opensourcephysics.controls.OSPCombo; import org.opensourcephysics.controls.SimulationControl; import org.opensourcephysics.display.GUIUtils; import org.opensourcephysics.frames.DisplayFrame; import org.opensourcephysics.frames.PlotFrame; import org.opensourcephysics.stp.util.Rdf;
/* * Open Source Physics software is free software as described near the bottom of this code file. * * For additional information and documentation on Open Source Physics please see: * <http://www.opensourcephysics.org/> */ package org.opensourcephysics.stp.ljmc; /** * LJParticlesApp simulates a two-dimensional system of interacting particles * via the Lennard-Jones potential. * * @author Jan Tobochnik, Wolfgang Christian, Harvey Gould * @version 1.0 revised 03/28/05, 3/29/05 */ public class LJMCApp extends AbstractSimulation { LJMC mc = new LJMC(); DisplayFrame display = new DisplayFrame("Lennard-Jones system"); PlotFrame grFrame = new PlotFrame("r", "g(r)", "Radial distribution function"); PlotFrame pressure = new PlotFrame("t", "PA/NkT", "Pressure");
// Path: src/org/opensourcephysics/stp/util/Rdf.java // public class Rdf { // public double bin = 0.1; // public double[] x, y; // public double Lx, Ly; // public double rmax; // public int N, nbins; // public boolean pbc = true; // public int ncorr = 0; // double[] gr; // public double[] rx, ngr; // normalized gr // // /** // * Constructor Rdf // */ // public Rdf() {} // // /** // * Constructor Rdf // * @param lx // * @param ly // */ // public Rdf(double lx, double ly) { // initialize(lx, ly, 0.1); // } // // public void initialize(double lx, double ly, double _bin) { // Lx = lx; // Ly = ly; // rmax = (Lx>Ly) // ? 0.5*Lx // : 0.5*Ly; // bin = _bin; // nbins = (int) Math.ceil(rmax/bin); // gr = new double[nbins]; // ngr = new double[nbins]; // rx = new double[nbins]; // for(int i = 0; i<nbins; i++) { // rx[i] = i*bin; // gr[i] = 0.0; // } // } // // public void reset() { // for(int i = 0; i<nbins; i++) { // rx[i] = i*bin; // gr[i] = 0.0; // } // ncorr = 0; // } // // public void append(double[] x, double[] y) { // N = x.length; // ncorr++; // for(int i = 0; i<N; i++) { // for(int j = i+1; j<N; j++) { // double dx = x[i]-x[j]; // double dy = y[i]-y[j]; // if(pbc) { // dx = separation(dx, Lx); // dy = separation(dy, Ly); // } // double dr = dx*dx+dy*dy; // dr = Math.sqrt(dr); // int nbin = (int) ((dr+0.0000001)/bin); // if(nbin<nbins) { // //if(nbin == 9)System.out.println(dr); // gr[nbin]++; // } // } // } // } // // public void normalize() { // double area; // double pi = Math.PI; // int i = 0; // int imax = (int) (rmax/bin); // double rho = N/Lx/Ly; // double norm = 0.5*rho*ncorr*N; // while(i<imax) { // double r = i*bin; // area = pi*((r+bin)*(r+bin)-r*r); // area *= norm; // ngr[i] = gr[i]/area; // i++; // } // } // // public void setBinSize(double _bin) { // bin = _bin; // nbins = (int) (rmax/bin)+1; // } // // public void setPbc(boolean p) { // pbc = p; // } // // public double separation(double dx, double lx) { // if(dx>0.5*lx) { // return dx-lx; // } // if(dx<-0.5*lx) { // return dx+lx; // } // return dx; // } // // } // Path: src/org/opensourcephysics/stp/ljmc/LJMCApp.java import org.opensourcephysics.controls.AbstractSimulation; import org.opensourcephysics.controls.OSPCombo; import org.opensourcephysics.controls.SimulationControl; import org.opensourcephysics.display.GUIUtils; import org.opensourcephysics.frames.DisplayFrame; import org.opensourcephysics.frames.PlotFrame; import org.opensourcephysics.stp.util.Rdf; /* * Open Source Physics software is free software as described near the bottom of this code file. * * For additional information and documentation on Open Source Physics please see: * <http://www.opensourcephysics.org/> */ package org.opensourcephysics.stp.ljmc; /** * LJParticlesApp simulates a two-dimensional system of interacting particles * via the Lennard-Jones potential. * * @author Jan Tobochnik, Wolfgang Christian, Harvey Gould * @version 1.0 revised 03/28/05, 3/29/05 */ public class LJMCApp extends AbstractSimulation { LJMC mc = new LJMC(); DisplayFrame display = new DisplayFrame("Lennard-Jones system"); PlotFrame grFrame = new PlotFrame("r", "g(r)", "Radial distribution function"); PlotFrame pressure = new PlotFrame("t", "PA/NkT", "Pressure");
Rdf gr = new Rdf();
OpenSourcePhysics/STP
src/org/opensourcephysics/stp/harddisk/HDApp.java
// Path: src/org/opensourcephysics/stp/util/Rdf.java // public class Rdf { // public double bin = 0.1; // public double[] x, y; // public double Lx, Ly; // public double rmax; // public int N, nbins; // public boolean pbc = true; // public int ncorr = 0; // double[] gr; // public double[] rx, ngr; // normalized gr // // /** // * Constructor Rdf // */ // public Rdf() {} // // /** // * Constructor Rdf // * @param lx // * @param ly // */ // public Rdf(double lx, double ly) { // initialize(lx, ly, 0.1); // } // // public void initialize(double lx, double ly, double _bin) { // Lx = lx; // Ly = ly; // rmax = (Lx>Ly) // ? 0.5*Lx // : 0.5*Ly; // bin = _bin; // nbins = (int) Math.ceil(rmax/bin); // gr = new double[nbins]; // ngr = new double[nbins]; // rx = new double[nbins]; // for(int i = 0; i<nbins; i++) { // rx[i] = i*bin; // gr[i] = 0.0; // } // } // // public void reset() { // for(int i = 0; i<nbins; i++) { // rx[i] = i*bin; // gr[i] = 0.0; // } // ncorr = 0; // } // // public void append(double[] x, double[] y) { // N = x.length; // ncorr++; // for(int i = 0; i<N; i++) { // for(int j = i+1; j<N; j++) { // double dx = x[i]-x[j]; // double dy = y[i]-y[j]; // if(pbc) { // dx = separation(dx, Lx); // dy = separation(dy, Ly); // } // double dr = dx*dx+dy*dy; // dr = Math.sqrt(dr); // int nbin = (int) ((dr+0.0000001)/bin); // if(nbin<nbins) { // //if(nbin == 9)System.out.println(dr); // gr[nbin]++; // } // } // } // } // // public void normalize() { // double area; // double pi = Math.PI; // int i = 0; // int imax = (int) (rmax/bin); // double rho = N/Lx/Ly; // double norm = 0.5*rho*ncorr*N; // while(i<imax) { // double r = i*bin; // area = pi*((r+bin)*(r+bin)-r*r); // area *= norm; // ngr[i] = gr[i]/area; // i++; // } // } // // public void setBinSize(double _bin) { // bin = _bin; // nbins = (int) (rmax/bin)+1; // } // // public void setPbc(boolean p) { // pbc = p; // } // // public double separation(double dx, double lx) { // if(dx>0.5*lx) { // return dx-lx; // } // if(dx<-0.5*lx) { // return dx+lx; // } // return dx; // } // // }
import java.text.NumberFormat; import org.opensourcephysics.controls.*; import org.opensourcephysics.frames.*; import org.opensourcephysics.stp.util.Rdf;;
/* * Open Source Physics software is free software as described near the bottom of this code file. * * For additional information and documentation on Open Source Physics please see: * <http://www.opensourcephysics.org/> */ package org.opensourcephysics.stp.harddisk; /** * Simulates hard disks. * * @author Jan Tobochnik * @author Joshua Gould * @author Peter Sibley * @created December 26, 2002 */ public class HDApp extends AbstractSimulation { PlotFrame temperatureFrame = new PlotFrame("time", "Temperature", "Temperature versus time"); PlotFrame pressureFrame = new PlotFrame("time", "pressure", "Pressure versus time"); DisplayFrame displayFrame = new DisplayFrame("HD Display"); HistogramFrame histogramFrame = new HistogramFrame("v_x", "H(v_x)", "H(v_x) versus v_x");
// Path: src/org/opensourcephysics/stp/util/Rdf.java // public class Rdf { // public double bin = 0.1; // public double[] x, y; // public double Lx, Ly; // public double rmax; // public int N, nbins; // public boolean pbc = true; // public int ncorr = 0; // double[] gr; // public double[] rx, ngr; // normalized gr // // /** // * Constructor Rdf // */ // public Rdf() {} // // /** // * Constructor Rdf // * @param lx // * @param ly // */ // public Rdf(double lx, double ly) { // initialize(lx, ly, 0.1); // } // // public void initialize(double lx, double ly, double _bin) { // Lx = lx; // Ly = ly; // rmax = (Lx>Ly) // ? 0.5*Lx // : 0.5*Ly; // bin = _bin; // nbins = (int) Math.ceil(rmax/bin); // gr = new double[nbins]; // ngr = new double[nbins]; // rx = new double[nbins]; // for(int i = 0; i<nbins; i++) { // rx[i] = i*bin; // gr[i] = 0.0; // } // } // // public void reset() { // for(int i = 0; i<nbins; i++) { // rx[i] = i*bin; // gr[i] = 0.0; // } // ncorr = 0; // } // // public void append(double[] x, double[] y) { // N = x.length; // ncorr++; // for(int i = 0; i<N; i++) { // for(int j = i+1; j<N; j++) { // double dx = x[i]-x[j]; // double dy = y[i]-y[j]; // if(pbc) { // dx = separation(dx, Lx); // dy = separation(dy, Ly); // } // double dr = dx*dx+dy*dy; // dr = Math.sqrt(dr); // int nbin = (int) ((dr+0.0000001)/bin); // if(nbin<nbins) { // //if(nbin == 9)System.out.println(dr); // gr[nbin]++; // } // } // } // } // // public void normalize() { // double area; // double pi = Math.PI; // int i = 0; // int imax = (int) (rmax/bin); // double rho = N/Lx/Ly; // double norm = 0.5*rho*ncorr*N; // while(i<imax) { // double r = i*bin; // area = pi*((r+bin)*(r+bin)-r*r); // area *= norm; // ngr[i] = gr[i]/area; // i++; // } // } // // public void setBinSize(double _bin) { // bin = _bin; // nbins = (int) (rmax/bin)+1; // } // // public void setPbc(boolean p) { // pbc = p; // } // // public double separation(double dx, double lx) { // if(dx>0.5*lx) { // return dx-lx; // } // if(dx<-0.5*lx) { // return dx+lx; // } // return dx; // } // // } // Path: src/org/opensourcephysics/stp/harddisk/HDApp.java import java.text.NumberFormat; import org.opensourcephysics.controls.*; import org.opensourcephysics.frames.*; import org.opensourcephysics.stp.util.Rdf;; /* * Open Source Physics software is free software as described near the bottom of this code file. * * For additional information and documentation on Open Source Physics please see: * <http://www.opensourcephysics.org/> */ package org.opensourcephysics.stp.harddisk; /** * Simulates hard disks. * * @author Jan Tobochnik * @author Joshua Gould * @author Peter Sibley * @created December 26, 2002 */ public class HDApp extends AbstractSimulation { PlotFrame temperatureFrame = new PlotFrame("time", "Temperature", "Temperature versus time"); PlotFrame pressureFrame = new PlotFrame("time", "pressure", "Pressure versus time"); DisplayFrame displayFrame = new DisplayFrame("HD Display"); HistogramFrame histogramFrame = new HistogramFrame("v_x", "H(v_x)", "H(v_x) versus v_x");
Rdf gr = new Rdf();
lastfm/lastcommons-kyoto
src/test/java/fm/last/commons/kyoto/factory/ErrorHandlerTest.java
// Path: src/main/java/fm/last/commons/kyoto/KyotoException.java // public class KyotoException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public KyotoException(String message) { // super(message); // } // // public KyotoException(Throwable error) { // super(error); // } // // public KyotoException(String message, Throwable throwable) { // super(message, throwable); // } // // } // // Path: src/main/java/fm/last/commons/kyoto/factory/ErrorHandler.java // interface ErrorSource { // Error getError(); // }
import org.mockito.runners.MockitoJUnitRunner; import fm.last.commons.kyoto.KyotoException; import fm.last.commons.kyoto.factory.ErrorHandler.ErrorSource; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; import java.io.IOException; import java.rmi.UnexpectedException; import kyotocabinet.Error; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock;
/* * Copyright 2012 Last.fm * * 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 fm.last.commons.kyoto.factory; @RunWith(MockitoJUnitRunner.class) public class ErrorHandlerTest { @Mock
// Path: src/main/java/fm/last/commons/kyoto/KyotoException.java // public class KyotoException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public KyotoException(String message) { // super(message); // } // // public KyotoException(Throwable error) { // super(error); // } // // public KyotoException(String message, Throwable throwable) { // super(message, throwable); // } // // } // // Path: src/main/java/fm/last/commons/kyoto/factory/ErrorHandler.java // interface ErrorSource { // Error getError(); // } // Path: src/test/java/fm/last/commons/kyoto/factory/ErrorHandlerTest.java import org.mockito.runners.MockitoJUnitRunner; import fm.last.commons.kyoto.KyotoException; import fm.last.commons.kyoto.factory.ErrorHandler.ErrorSource; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; import java.io.IOException; import java.rmi.UnexpectedException; import kyotocabinet.Error; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; /* * Copyright 2012 Last.fm * * 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 fm.last.commons.kyoto.factory; @RunWith(MockitoJUnitRunner.class) public class ErrorHandlerTest { @Mock
private ErrorSource mockErrorSource;
lastfm/lastcommons-kyoto
src/test/java/fm/last/commons/kyoto/factory/ErrorHandlerTest.java
// Path: src/main/java/fm/last/commons/kyoto/KyotoException.java // public class KyotoException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public KyotoException(String message) { // super(message); // } // // public KyotoException(Throwable error) { // super(error); // } // // public KyotoException(String message, Throwable throwable) { // super(message, throwable); // } // // } // // Path: src/main/java/fm/last/commons/kyoto/factory/ErrorHandler.java // interface ErrorSource { // Error getError(); // }
import org.mockito.runners.MockitoJUnitRunner; import fm.last.commons.kyoto.KyotoException; import fm.last.commons.kyoto.factory.ErrorHandler.ErrorSource; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; import java.io.IOException; import java.rmi.UnexpectedException; import kyotocabinet.Error; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock;
/* * Copyright 2012 Last.fm * * 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 fm.last.commons.kyoto.factory; @RunWith(MockitoJUnitRunner.class) public class ErrorHandlerTest { @Mock private ErrorSource mockErrorSource; private ErrorHandler errorHandler; @Before public void setup() { errorHandler = new ErrorHandler(mockErrorSource); when(mockErrorSource.getError()).thenReturn(new Error(Error.MISC, "misc")); } @Test public void wrapBooleanCallOk() { assertThat(errorHandler.wrapBooleanCall(true), is(true)); }
// Path: src/main/java/fm/last/commons/kyoto/KyotoException.java // public class KyotoException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public KyotoException(String message) { // super(message); // } // // public KyotoException(Throwable error) { // super(error); // } // // public KyotoException(String message, Throwable throwable) { // super(message, throwable); // } // // } // // Path: src/main/java/fm/last/commons/kyoto/factory/ErrorHandler.java // interface ErrorSource { // Error getError(); // } // Path: src/test/java/fm/last/commons/kyoto/factory/ErrorHandlerTest.java import org.mockito.runners.MockitoJUnitRunner; import fm.last.commons.kyoto.KyotoException; import fm.last.commons.kyoto.factory.ErrorHandler.ErrorSource; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; import java.io.IOException; import java.rmi.UnexpectedException; import kyotocabinet.Error; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; /* * Copyright 2012 Last.fm * * 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 fm.last.commons.kyoto.factory; @RunWith(MockitoJUnitRunner.class) public class ErrorHandlerTest { @Mock private ErrorSource mockErrorSource; private ErrorHandler errorHandler; @Before public void setup() { errorHandler = new ErrorHandler(mockErrorSource); when(mockErrorSource.getError()).thenReturn(new Error(Error.MISC, "misc")); } @Test public void wrapBooleanCallOk() { assertThat(errorHandler.wrapBooleanCall(true), is(true)); }
@Test(expected = KyotoException.class)
lastfm/lastcommons-kyoto
src/test/java/fm/last/commons/kyoto/factory/ReadOnlyVisitorAdapterTest.java
// Path: src/main/java/fm/last/commons/kyoto/ReadOnlyVisitor.java // public interface ReadOnlyVisitor { // // /** // * Visit a record. // * // * @param key the record key. // * @param value the record value. // * @see kyotocabinet.Visitor#visit_full(byte[], byte[]) // */ // void record(byte[] key, byte[] value); // // /** // * Visit an empty record. // * // * @param key the record key. // * @see kyotocabinet.Visitor#visit_empty(byte[]) // */ // void emptyRecord(byte[] key); // // } // // Path: src/main/java/fm/last/commons/kyoto/WritableVisitor.java // public interface WritableVisitor { // // /** No operation */ // public static final byte[] NOP = Visitor.NOP; // /** Remove record */ // public static final byte[] REMOVE = Visitor.REMOVE; // // /** // * Visit a record. // * // * @param key the record key. // * @param value the record value. // * @return {@link #REMOVE} to remove the record, {@link #NOP} to leave the record unchanged, or a {@code byte[]} // * value to replace the current record value. // * @see kyotocabinet.Visitor#visit_full(byte[], byte[]) // */ // byte[] record(byte[] key, byte[] value); // // /** // * Visit an empty record. // * // * @param key the record key. // * @return {@link #REMOVE} to remove the record, {@link #NOP} to leave the record unchanged, or a {@code byte[]} // * value to replace the current record value. // * @see kyotocabinet.Visitor#visit_empty(byte[]) // */ // byte[] emptyRecord(byte[] key); // // }
import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import kyotocabinet.Visitor; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import fm.last.commons.kyoto.ReadOnlyVisitor; import fm.last.commons.kyoto.WritableVisitor;
/* * Copyright 2012 Last.fm * * 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 fm.last.commons.kyoto.factory; @RunWith(MockitoJUnitRunner.class) public class ReadOnlyVisitorAdapterTest { private static final byte[] BYTE_ARRAY_VALUE = new byte[3]; @Mock
// Path: src/main/java/fm/last/commons/kyoto/ReadOnlyVisitor.java // public interface ReadOnlyVisitor { // // /** // * Visit a record. // * // * @param key the record key. // * @param value the record value. // * @see kyotocabinet.Visitor#visit_full(byte[], byte[]) // */ // void record(byte[] key, byte[] value); // // /** // * Visit an empty record. // * // * @param key the record key. // * @see kyotocabinet.Visitor#visit_empty(byte[]) // */ // void emptyRecord(byte[] key); // // } // // Path: src/main/java/fm/last/commons/kyoto/WritableVisitor.java // public interface WritableVisitor { // // /** No operation */ // public static final byte[] NOP = Visitor.NOP; // /** Remove record */ // public static final byte[] REMOVE = Visitor.REMOVE; // // /** // * Visit a record. // * // * @param key the record key. // * @param value the record value. // * @return {@link #REMOVE} to remove the record, {@link #NOP} to leave the record unchanged, or a {@code byte[]} // * value to replace the current record value. // * @see kyotocabinet.Visitor#visit_full(byte[], byte[]) // */ // byte[] record(byte[] key, byte[] value); // // /** // * Visit an empty record. // * // * @param key the record key. // * @return {@link #REMOVE} to remove the record, {@link #NOP} to leave the record unchanged, or a {@code byte[]} // * value to replace the current record value. // * @see kyotocabinet.Visitor#visit_empty(byte[]) // */ // byte[] emptyRecord(byte[] key); // // } // Path: src/test/java/fm/last/commons/kyoto/factory/ReadOnlyVisitorAdapterTest.java import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import kyotocabinet.Visitor; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import fm.last.commons.kyoto.ReadOnlyVisitor; import fm.last.commons.kyoto.WritableVisitor; /* * Copyright 2012 Last.fm * * 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 fm.last.commons.kyoto.factory; @RunWith(MockitoJUnitRunner.class) public class ReadOnlyVisitorAdapterTest { private static final byte[] BYTE_ARRAY_VALUE = new byte[3]; @Mock
private ReadOnlyVisitor mockVisitor;
lastfm/lastcommons-kyoto
src/test/java/fm/last/commons/kyoto/factory/ReadOnlyVisitorAdapterTest.java
// Path: src/main/java/fm/last/commons/kyoto/ReadOnlyVisitor.java // public interface ReadOnlyVisitor { // // /** // * Visit a record. // * // * @param key the record key. // * @param value the record value. // * @see kyotocabinet.Visitor#visit_full(byte[], byte[]) // */ // void record(byte[] key, byte[] value); // // /** // * Visit an empty record. // * // * @param key the record key. // * @see kyotocabinet.Visitor#visit_empty(byte[]) // */ // void emptyRecord(byte[] key); // // } // // Path: src/main/java/fm/last/commons/kyoto/WritableVisitor.java // public interface WritableVisitor { // // /** No operation */ // public static final byte[] NOP = Visitor.NOP; // /** Remove record */ // public static final byte[] REMOVE = Visitor.REMOVE; // // /** // * Visit a record. // * // * @param key the record key. // * @param value the record value. // * @return {@link #REMOVE} to remove the record, {@link #NOP} to leave the record unchanged, or a {@code byte[]} // * value to replace the current record value. // * @see kyotocabinet.Visitor#visit_full(byte[], byte[]) // */ // byte[] record(byte[] key, byte[] value); // // /** // * Visit an empty record. // * // * @param key the record key. // * @return {@link #REMOVE} to remove the record, {@link #NOP} to leave the record unchanged, or a {@code byte[]} // * value to replace the current record value. // * @see kyotocabinet.Visitor#visit_empty(byte[]) // */ // byte[] emptyRecord(byte[] key); // // }
import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import kyotocabinet.Visitor; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import fm.last.commons.kyoto.ReadOnlyVisitor; import fm.last.commons.kyoto.WritableVisitor;
/* * Copyright 2012 Last.fm * * 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 fm.last.commons.kyoto.factory; @RunWith(MockitoJUnitRunner.class) public class ReadOnlyVisitorAdapterTest { private static final byte[] BYTE_ARRAY_VALUE = new byte[3]; @Mock private ReadOnlyVisitor mockVisitor; private Visitor adapter; @Before public void setup() { adapter = new ReadOnlyVisitorAdapter(mockVisitor); } @Test public void visitFull() { byte[] value = adapter.visit_full(BYTE_ARRAY_VALUE, BYTE_ARRAY_VALUE); verify(mockVisitor).record(BYTE_ARRAY_VALUE, BYTE_ARRAY_VALUE);
// Path: src/main/java/fm/last/commons/kyoto/ReadOnlyVisitor.java // public interface ReadOnlyVisitor { // // /** // * Visit a record. // * // * @param key the record key. // * @param value the record value. // * @see kyotocabinet.Visitor#visit_full(byte[], byte[]) // */ // void record(byte[] key, byte[] value); // // /** // * Visit an empty record. // * // * @param key the record key. // * @see kyotocabinet.Visitor#visit_empty(byte[]) // */ // void emptyRecord(byte[] key); // // } // // Path: src/main/java/fm/last/commons/kyoto/WritableVisitor.java // public interface WritableVisitor { // // /** No operation */ // public static final byte[] NOP = Visitor.NOP; // /** Remove record */ // public static final byte[] REMOVE = Visitor.REMOVE; // // /** // * Visit a record. // * // * @param key the record key. // * @param value the record value. // * @return {@link #REMOVE} to remove the record, {@link #NOP} to leave the record unchanged, or a {@code byte[]} // * value to replace the current record value. // * @see kyotocabinet.Visitor#visit_full(byte[], byte[]) // */ // byte[] record(byte[] key, byte[] value); // // /** // * Visit an empty record. // * // * @param key the record key. // * @return {@link #REMOVE} to remove the record, {@link #NOP} to leave the record unchanged, or a {@code byte[]} // * value to replace the current record value. // * @see kyotocabinet.Visitor#visit_empty(byte[]) // */ // byte[] emptyRecord(byte[] key); // // } // Path: src/test/java/fm/last/commons/kyoto/factory/ReadOnlyVisitorAdapterTest.java import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import kyotocabinet.Visitor; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import fm.last.commons.kyoto.ReadOnlyVisitor; import fm.last.commons.kyoto.WritableVisitor; /* * Copyright 2012 Last.fm * * 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 fm.last.commons.kyoto.factory; @RunWith(MockitoJUnitRunner.class) public class ReadOnlyVisitorAdapterTest { private static final byte[] BYTE_ARRAY_VALUE = new byte[3]; @Mock private ReadOnlyVisitor mockVisitor; private Visitor adapter; @Before public void setup() { adapter = new ReadOnlyVisitorAdapter(mockVisitor); } @Test public void visitFull() { byte[] value = adapter.visit_full(BYTE_ARRAY_VALUE, BYTE_ARRAY_VALUE); verify(mockVisitor).record(BYTE_ARRAY_VALUE, BYTE_ARRAY_VALUE);
assertThat(value, is(WritableVisitor.NOP));
lastfm/lastcommons-kyoto
src/main/java/fm/last/commons/kyoto/factory/ErrorHandler.java
// Path: src/main/java/fm/last/commons/kyoto/KyotoException.java // public class KyotoException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public KyotoException(String message) { // super(message); // } // // public KyotoException(Throwable error) { // super(error); // } // // public KyotoException(String message, Throwable throwable) { // super(message, throwable); // } // // }
import java.io.IOException; import java.rmi.UnexpectedException; import kyotocabinet.Error; import fm.last.commons.kyoto.KyotoException;
} void wrapVoidCall(boolean success) { if (!success) { processError(); } } void wrapVoidCall(boolean success, String message) { if (!success) { processError(message); } } void wrapVoidIoCall(boolean success, String message) throws IOException { if (!success) { processIoError(message); } } <T> T wrapObjectCall(T result) { if (result == null) { processError(); } return result; } void processError() { Error error = source.getError(); if (error == null) {
// Path: src/main/java/fm/last/commons/kyoto/KyotoException.java // public class KyotoException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public KyotoException(String message) { // super(message); // } // // public KyotoException(Throwable error) { // super(error); // } // // public KyotoException(String message, Throwable throwable) { // super(message, throwable); // } // // } // Path: src/main/java/fm/last/commons/kyoto/factory/ErrorHandler.java import java.io.IOException; import java.rmi.UnexpectedException; import kyotocabinet.Error; import fm.last.commons.kyoto.KyotoException; } void wrapVoidCall(boolean success) { if (!success) { processError(); } } void wrapVoidCall(boolean success, String message) { if (!success) { processError(message); } } void wrapVoidIoCall(boolean success, String message) throws IOException { if (!success) { processIoError(message); } } <T> T wrapObjectCall(T result) { if (result == null) { processError(); } return result; } void processError() { Error error = source.getError(); if (error == null) {
throw new KyotoException(new UnexpectedException("Could not read error code."));
lastfm/lastcommons-kyoto
src/main/java/fm/last/commons/kyoto/factory/FileProcessorAdapter.java
// Path: src/main/java/fm/last/commons/kyoto/KyotoFileProcessor.java // public interface KyotoFileProcessor { // // /** // * Process the database file. // * // * @param dbFile the underlying database file. // * @param recordCount the number of records in the file. // * @param availableRegionSize the size of the available region. // * @see kyotocabinet.FileProcessor#process(String, long, long) // * @throws KyotoException on failure // */ // void process(File dbFile, long recordCount, long availableRegionSize); // // }
import java.io.File; import kyotocabinet.FileProcessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import fm.last.commons.kyoto.KyotoFileProcessor;
/* * Copyright 2012 Last.fm * * 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 fm.last.commons.kyoto.factory; class FileProcessorAdapter implements FileProcessor { private final Logger log = LoggerFactory.getLogger(getClass());
// Path: src/main/java/fm/last/commons/kyoto/KyotoFileProcessor.java // public interface KyotoFileProcessor { // // /** // * Process the database file. // * // * @param dbFile the underlying database file. // * @param recordCount the number of records in the file. // * @param availableRegionSize the size of the available region. // * @see kyotocabinet.FileProcessor#process(String, long, long) // * @throws KyotoException on failure // */ // void process(File dbFile, long recordCount, long availableRegionSize); // // } // Path: src/main/java/fm/last/commons/kyoto/factory/FileProcessorAdapter.java import java.io.File; import kyotocabinet.FileProcessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import fm.last.commons.kyoto.KyotoFileProcessor; /* * Copyright 2012 Last.fm * * 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 fm.last.commons.kyoto.factory; class FileProcessorAdapter implements FileProcessor { private final Logger log = LoggerFactory.getLogger(getClass());
private final KyotoFileProcessor delegate;
lastfm/lastcommons-kyoto
src/test/java/fm/last/commons/kyoto/CodecToDoubleTest.java
// Path: src/test/java/fm/last/commons/kyoto/test/IsConsideredToBe.java // public static Matcher<Double> isConsideredToBe(final Double expected, final double errorMargin) { // return new IsConsideredToBe(expected, errorMargin); // }
import static fm.last.commons.kyoto.test.IsConsideredToBe.isConsideredToBe; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters;
package fm.last.commons.kyoto; @RunWith(Parameterized.class) public class CodecToDoubleTest { private static final double ERROR_MARGIN = 0.000000000000001d; // 10.0001 private static final byte[] _10_0001 = new byte[] { 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 23, 72, 118, -25, -1 }; // -1.0 private static final byte[] __1 = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0 }; // -1.1 private static final byte[] __1_1 = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -91, 12, -17, -123, -64, 0 }; // 1.1 private static final byte[] _1_1 = new byte[] { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 90, -13, 16, 122, 64, 0 }; private final byte[] bytes; private final double expected; @Parameters public static Collection<Object[]> data() { List<Object[]> data = new ArrayList<Object[]>(); data.add(new Object[] { 10.0001d, _10_0001 }); data.add(new Object[] { -1.0d, __1 }); data.add(new Object[] { -1.1d, __1_1 }); data.add(new Object[] { 1.1d, _1_1 }); return data; } public CodecToDoubleTest(double expected, byte[] bytes) { this.expected = expected; this.bytes = bytes; } @Test public void testFixedPointToDouble() { double decodedValue = Codec.toDouble(bytes);
// Path: src/test/java/fm/last/commons/kyoto/test/IsConsideredToBe.java // public static Matcher<Double> isConsideredToBe(final Double expected, final double errorMargin) { // return new IsConsideredToBe(expected, errorMargin); // } // Path: src/test/java/fm/last/commons/kyoto/CodecToDoubleTest.java import static fm.last.commons.kyoto.test.IsConsideredToBe.isConsideredToBe; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; package fm.last.commons.kyoto; @RunWith(Parameterized.class) public class CodecToDoubleTest { private static final double ERROR_MARGIN = 0.000000000000001d; // 10.0001 private static final byte[] _10_0001 = new byte[] { 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 23, 72, 118, -25, -1 }; // -1.0 private static final byte[] __1 = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0 }; // -1.1 private static final byte[] __1_1 = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -91, 12, -17, -123, -64, 0 }; // 1.1 private static final byte[] _1_1 = new byte[] { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 90, -13, 16, 122, 64, 0 }; private final byte[] bytes; private final double expected; @Parameters public static Collection<Object[]> data() { List<Object[]> data = new ArrayList<Object[]>(); data.add(new Object[] { 10.0001d, _10_0001 }); data.add(new Object[] { -1.0d, __1 }); data.add(new Object[] { -1.1d, __1_1 }); data.add(new Object[] { 1.1d, _1_1 }); return data; } public CodecToDoubleTest(double expected, byte[] bytes) { this.expected = expected; this.bytes = bytes; } @Test public void testFixedPointToDouble() { double decodedValue = Codec.toDouble(bytes);
assertThat(decodedValue, isConsideredToBe(expected, ERROR_MARGIN));
lastfm/lastcommons-kyoto
src/test/java/fm/last/commons/kyoto/factory/FileProcessorAdapterTest.java
// Path: src/main/java/fm/last/commons/kyoto/KyotoFileProcessor.java // public interface KyotoFileProcessor { // // /** // * Process the database file. // * // * @param dbFile the underlying database file. // * @param recordCount the number of records in the file. // * @param availableRegionSize the size of the available region. // * @see kyotocabinet.FileProcessor#process(String, long, long) // * @throws KyotoException on failure // */ // void process(File dbFile, long recordCount, long availableRegionSize); // // }
import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import fm.last.commons.kyoto.KyotoFileProcessor; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import java.io.File; import kyotocabinet.FileProcessor; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith;
/* * Copyright 2012 Last.fm * * 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 fm.last.commons.kyoto.factory; @RunWith(MockitoJUnitRunner.class) public class FileProcessorAdapterTest { @Mock
// Path: src/main/java/fm/last/commons/kyoto/KyotoFileProcessor.java // public interface KyotoFileProcessor { // // /** // * Process the database file. // * // * @param dbFile the underlying database file. // * @param recordCount the number of records in the file. // * @param availableRegionSize the size of the available region. // * @see kyotocabinet.FileProcessor#process(String, long, long) // * @throws KyotoException on failure // */ // void process(File dbFile, long recordCount, long availableRegionSize); // // } // Path: src/test/java/fm/last/commons/kyoto/factory/FileProcessorAdapterTest.java import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import fm.last.commons.kyoto.KyotoFileProcessor; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import java.io.File; import kyotocabinet.FileProcessor; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /* * Copyright 2012 Last.fm * * 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 fm.last.commons.kyoto.factory; @RunWith(MockitoJUnitRunner.class) public class FileProcessorAdapterTest { @Mock
private KyotoFileProcessor mockDelegate;
lastfm/lastcommons-kyoto
src/test/java/fm/last/commons/kyoto/factory/WritableVisitorAdapterTest.java
// Path: src/main/java/fm/last/commons/kyoto/WritableVisitor.java // public interface WritableVisitor { // // /** No operation */ // public static final byte[] NOP = Visitor.NOP; // /** Remove record */ // public static final byte[] REMOVE = Visitor.REMOVE; // // /** // * Visit a record. // * // * @param key the record key. // * @param value the record value. // * @return {@link #REMOVE} to remove the record, {@link #NOP} to leave the record unchanged, or a {@code byte[]} // * value to replace the current record value. // * @see kyotocabinet.Visitor#visit_full(byte[], byte[]) // */ // byte[] record(byte[] key, byte[] value); // // /** // * Visit an empty record. // * // * @param key the record key. // * @return {@link #REMOVE} to remove the record, {@link #NOP} to leave the record unchanged, or a {@code byte[]} // * value to replace the current record value. // * @see kyotocabinet.Visitor#visit_empty(byte[]) // */ // byte[] emptyRecord(byte[] key); // // }
import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import kyotocabinet.Visitor; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import fm.last.commons.kyoto.WritableVisitor;
/* * Copyright 2012 Last.fm * * 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 fm.last.commons.kyoto.factory; @RunWith(MockitoJUnitRunner.class) public class WritableVisitorAdapterTest { private static final byte[] BYTE_ARRAY_VALUE = new byte[3]; @Mock
// Path: src/main/java/fm/last/commons/kyoto/WritableVisitor.java // public interface WritableVisitor { // // /** No operation */ // public static final byte[] NOP = Visitor.NOP; // /** Remove record */ // public static final byte[] REMOVE = Visitor.REMOVE; // // /** // * Visit a record. // * // * @param key the record key. // * @param value the record value. // * @return {@link #REMOVE} to remove the record, {@link #NOP} to leave the record unchanged, or a {@code byte[]} // * value to replace the current record value. // * @see kyotocabinet.Visitor#visit_full(byte[], byte[]) // */ // byte[] record(byte[] key, byte[] value); // // /** // * Visit an empty record. // * // * @param key the record key. // * @return {@link #REMOVE} to remove the record, {@link #NOP} to leave the record unchanged, or a {@code byte[]} // * value to replace the current record value. // * @see kyotocabinet.Visitor#visit_empty(byte[]) // */ // byte[] emptyRecord(byte[] key); // // } // Path: src/test/java/fm/last/commons/kyoto/factory/WritableVisitorAdapterTest.java import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import kyotocabinet.Visitor; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import fm.last.commons.kyoto.WritableVisitor; /* * Copyright 2012 Last.fm * * 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 fm.last.commons.kyoto.factory; @RunWith(MockitoJUnitRunner.class) public class WritableVisitorAdapterTest { private static final byte[] BYTE_ARRAY_VALUE = new byte[3]; @Mock
private WritableVisitor mockVisitor;
awslabs/aws-codepipeline-plugin-for-jenkins
src/test/java/com/amazonaws/codepipeline/jenkinsplugin/PublisherCallableTest.java
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.AWSSessionCredentials; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.ArtifactLocation; import com.amazonaws.services.codepipeline.model.GetJobDetailsRequest; import com.amazonaws.services.codepipeline.model.GetJobDetailsResult; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData; import com.amazonaws.services.codepipeline.model.JobDetails; import com.amazonaws.services.codepipeline.model.S3ArtifactLocation; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadResult; import com.amazonaws.services.s3.model.PartETag; import com.amazonaws.services.s3.model.UploadPartRequest; import com.amazonaws.services.s3.model.UploadPartResult;
private S3ArtifactLocation s3ArtifactLocation1 = new S3ArtifactLocation() .withBucketName(S3_BUCKET_NAME + "1").withObjectKey(S3_OBJECT_KEY + "1"); private S3ArtifactLocation s3ArtifactLocation2 = new S3ArtifactLocation() .withBucketName(S3_BUCKET_NAME + "2").withObjectKey(S3_OBJECT_KEY + "2"); private ArtifactLocation artifactLocation = new ArtifactLocation().withS3Location(s3ArtifactLocation); private ArtifactLocation artifactLocation1 = new ArtifactLocation().withS3Location(s3ArtifactLocation1); private ArtifactLocation artifactLocation2 = new ArtifactLocation().withS3Location(s3ArtifactLocation2); private Artifact outputArtifact = new Artifact().withName("dummyArtifact").withLocation(artifactLocation); private Artifact outputArtifact1 = new Artifact().withName("dummyArtifact1").withLocation(artifactLocation1); private Artifact outputArtifact2 = new Artifact().withName("dummyArtifact2").withLocation(artifactLocation2); private File workspace; private PublisherCallable publisher; @Before public void setUp() throws IOException { MockitoAnnotations.initMocks(this); TestUtils.initializeTestingFolders(); workspace = Paths.get(TestUtils.TEST_DIR).toFile(); outContent = TestUtils.setOutputStream(); try (final PrintWriter writer = new PrintWriter(new File(workspace, TEST_FILE))) { writer.println("Some content"); } model = new CodePipelineStateModel(); model.setJob(job);
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/PublisherCallableTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.AWSSessionCredentials; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.ArtifactLocation; import com.amazonaws.services.codepipeline.model.GetJobDetailsRequest; import com.amazonaws.services.codepipeline.model.GetJobDetailsResult; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData; import com.amazonaws.services.codepipeline.model.JobDetails; import com.amazonaws.services.codepipeline.model.S3ArtifactLocation; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadResult; import com.amazonaws.services.s3.model.PartETag; import com.amazonaws.services.s3.model.UploadPartRequest; import com.amazonaws.services.s3.model.UploadPartResult; private S3ArtifactLocation s3ArtifactLocation1 = new S3ArtifactLocation() .withBucketName(S3_BUCKET_NAME + "1").withObjectKey(S3_OBJECT_KEY + "1"); private S3ArtifactLocation s3ArtifactLocation2 = new S3ArtifactLocation() .withBucketName(S3_BUCKET_NAME + "2").withObjectKey(S3_OBJECT_KEY + "2"); private ArtifactLocation artifactLocation = new ArtifactLocation().withS3Location(s3ArtifactLocation); private ArtifactLocation artifactLocation1 = new ArtifactLocation().withS3Location(s3ArtifactLocation1); private ArtifactLocation artifactLocation2 = new ArtifactLocation().withS3Location(s3ArtifactLocation2); private Artifact outputArtifact = new Artifact().withName("dummyArtifact").withLocation(artifactLocation); private Artifact outputArtifact1 = new Artifact().withName("dummyArtifact1").withLocation(artifactLocation1); private Artifact outputArtifact2 = new Artifact().withName("dummyArtifact2").withLocation(artifactLocation2); private File workspace; private PublisherCallable publisher; @Before public void setUp() throws IOException { MockitoAnnotations.initMocks(this); TestUtils.initializeTestingFolders(); workspace = Paths.get(TestUtils.TEST_DIR).toFile(); outContent = TestUtils.setOutputStream(); try (final PrintWriter writer = new PrintWriter(new File(workspace, TEST_FILE))) { writer.println("Some content"); } model = new CodePipelineStateModel(); model.setJob(job);
model.setCompressionType(CompressionType.Zip);
awslabs/aws-codepipeline-plugin-for-jenkins
src/test/java/com/amazonaws/codepipeline/jenkinsplugin/PublisherCallableTest.java
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.AWSSessionCredentials; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.ArtifactLocation; import com.amazonaws.services.codepipeline.model.GetJobDetailsRequest; import com.amazonaws.services.codepipeline.model.GetJobDetailsResult; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData; import com.amazonaws.services.codepipeline.model.JobDetails; import com.amazonaws.services.codepipeline.model.S3ArtifactLocation; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadResult; import com.amazonaws.services.s3.model.PartETag; import com.amazonaws.services.s3.model.UploadPartRequest; import com.amazonaws.services.s3.model.UploadPartResult;
public void uploadsArtifactToS3() throws IOException { // when publisher.invoke(workspace, null); // then final InOrder inOrder = inOrder(clientFactory, awsClients, s3Client); inOrder.verify(clientFactory).getAwsClient(ACCESS_KEY, SECRET_KEY, PROXY_HOST, PROXY_PORT, REGION, PLUGIN_VERSION); inOrder.verify(awsClients).getCodePipelineClient(); inOrder.verify(awsClients).getS3Client(credentialsProviderCaptor.capture()); inOrder.verify(s3Client).initiateMultipartUpload(initiateMultipartUploadRequestCaptor.capture()); inOrder.verify(s3Client).uploadPart(uploadPartRequestCaptor.capture()); final com.amazonaws.auth.AWSSessionCredentials credentials = (com.amazonaws.auth.AWSSessionCredentials) credentialsProviderCaptor.getValue().getCredentials(); assertEquals(JOB_ACCESS_KEY, credentials.getAWSAccessKeyId()); assertEquals(JOB_SECRET_KEY, credentials.getAWSSecretKey()); assertEquals(JOB_SESSION_TOKEN, credentials.getSessionToken()); verify(codePipelineClient).getJobDetails(getJobDetailsRequestCaptor.capture()); assertEquals(JOB_ID, getJobDetailsRequestCaptor.getValue().getJobId()); final InitiateMultipartUploadRequest initRequest = initiateMultipartUploadRequestCaptor.getValue(); assertEquals(S3_BUCKET_NAME, initRequest.getBucketName()); assertEquals(S3_OBJECT_KEY, initRequest.getKey()); final UploadPartRequest uploadRequest = uploadPartRequestCaptor.getValue(); assertEquals(S3_BUCKET_NAME, uploadRequest.getBucketName()); assertEquals(S3_OBJECT_KEY, uploadRequest.getKey()); assertEquals(UPLOAD_ID, uploadRequest.getUploadId());
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/PublisherCallableTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.AWSSessionCredentials; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.ArtifactLocation; import com.amazonaws.services.codepipeline.model.GetJobDetailsRequest; import com.amazonaws.services.codepipeline.model.GetJobDetailsResult; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData; import com.amazonaws.services.codepipeline.model.JobDetails; import com.amazonaws.services.codepipeline.model.S3ArtifactLocation; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadResult; import com.amazonaws.services.s3.model.PartETag; import com.amazonaws.services.s3.model.UploadPartRequest; import com.amazonaws.services.s3.model.UploadPartResult; public void uploadsArtifactToS3() throws IOException { // when publisher.invoke(workspace, null); // then final InOrder inOrder = inOrder(clientFactory, awsClients, s3Client); inOrder.verify(clientFactory).getAwsClient(ACCESS_KEY, SECRET_KEY, PROXY_HOST, PROXY_PORT, REGION, PLUGIN_VERSION); inOrder.verify(awsClients).getCodePipelineClient(); inOrder.verify(awsClients).getS3Client(credentialsProviderCaptor.capture()); inOrder.verify(s3Client).initiateMultipartUpload(initiateMultipartUploadRequestCaptor.capture()); inOrder.verify(s3Client).uploadPart(uploadPartRequestCaptor.capture()); final com.amazonaws.auth.AWSSessionCredentials credentials = (com.amazonaws.auth.AWSSessionCredentials) credentialsProviderCaptor.getValue().getCredentials(); assertEquals(JOB_ACCESS_KEY, credentials.getAWSAccessKeyId()); assertEquals(JOB_SECRET_KEY, credentials.getAWSSecretKey()); assertEquals(JOB_SESSION_TOKEN, credentials.getSessionToken()); verify(codePipelineClient).getJobDetails(getJobDetailsRequestCaptor.capture()); assertEquals(JOB_ID, getJobDetailsRequestCaptor.getValue().getJobId()); final InitiateMultipartUploadRequest initRequest = initiateMultipartUploadRequestCaptor.getValue(); assertEquals(S3_BUCKET_NAME, initRequest.getBucketName()); assertEquals(S3_OBJECT_KEY, initRequest.getKey()); final UploadPartRequest uploadRequest = uploadPartRequestCaptor.getValue(); assertEquals(S3_BUCKET_NAME, uploadRequest.getBucketName()); assertEquals(S3_OBJECT_KEY, uploadRequest.getKey()); assertEquals(UPLOAD_ID, uploadRequest.getUploadId());
assertContainsIgnoreCase("[AWS CodePipeline Plugin] Uploading artifact:", outContent.toString());
awslabs/aws-codepipeline-plugin-for-jenkins
src/test/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModelTests.java
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CategoryType { // PleaseChooseACategory("Please Choose A Category"), // Build("Build"), // Test("Test"); // // private final String name; // // CategoryType(final String name) { // this.name = name; // } // // public String getName() { // return this.name; // } // // public static CategoryType fromName(final String name) { // for (final CategoryType category : values()) { // if (name.equals(category.getName())) { // return category; // } // } // // throw new IllegalArgumentException("Cannot create enum from " + name + " value!"); // } // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CategoryType; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.model.EncryptionKey; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData;
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.codepipeline.jenkinsplugin; public class CodePipelineStateModelTests { private CodePipelineStateModel model; @Mock private Job mockJob; @Mock private JobData mockJobData; @Mock private EncryptionKey mockEncryptionKey; @Before public void setUp() { MockitoAnnotations.initMocks(this); model = new CodePipelineStateModel(); } @Test public void testConstructorSetsDefaultValues() {
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CategoryType { // PleaseChooseACategory("Please Choose A Category"), // Build("Build"), // Test("Test"); // // private final String name; // // CategoryType(final String name) { // this.name = name; // } // // public String getName() { // return this.name; // } // // public static CategoryType fromName(final String name) { // for (final CategoryType category : values()) { // if (name.equals(category.getName())) { // return category; // } // } // // throw new IllegalArgumentException("Cannot create enum from " + name + " value!"); // } // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModelTests.java import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CategoryType; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.model.EncryptionKey; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData; /* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.codepipeline.jenkinsplugin; public class CodePipelineStateModelTests { private CodePipelineStateModel model; @Mock private Job mockJob; @Mock private JobData mockJobData; @Mock private EncryptionKey mockEncryptionKey; @Before public void setUp() { MockitoAnnotations.initMocks(this); model = new CodePipelineStateModel(); } @Test public void testConstructorSetsDefaultValues() {
assertEquals(CompressionType.None, model.getCompressionType());
awslabs/aws-codepipeline-plugin-for-jenkins
src/test/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModelTests.java
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CategoryType { // PleaseChooseACategory("Please Choose A Category"), // Build("Build"), // Test("Test"); // // private final String name; // // CategoryType(final String name) { // this.name = name; // } // // public String getName() { // return this.name; // } // // public static CategoryType fromName(final String name) { // for (final CategoryType category : values()) { // if (name.equals(category.getName())) { // return category; // } // } // // throw new IllegalArgumentException("Cannot create enum from " + name + " value!"); // } // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CategoryType; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.model.EncryptionKey; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData;
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.codepipeline.jenkinsplugin; public class CodePipelineStateModelTests { private CodePipelineStateModel model; @Mock private Job mockJob; @Mock private JobData mockJobData; @Mock private EncryptionKey mockEncryptionKey; @Before public void setUp() { MockitoAnnotations.initMocks(this); model = new CodePipelineStateModel(); } @Test public void testConstructorSetsDefaultValues() { assertEquals(CompressionType.None, model.getCompressionType());
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CategoryType { // PleaseChooseACategory("Please Choose A Category"), // Build("Build"), // Test("Test"); // // private final String name; // // CategoryType(final String name) { // this.name = name; // } // // public String getName() { // return this.name; // } // // public static CategoryType fromName(final String name) { // for (final CategoryType category : values()) { // if (name.equals(category.getName())) { // return category; // } // } // // throw new IllegalArgumentException("Cannot create enum from " + name + " value!"); // } // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModelTests.java import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CategoryType; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.model.EncryptionKey; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData; /* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.codepipeline.jenkinsplugin; public class CodePipelineStateModelTests { private CodePipelineStateModel model; @Mock private Job mockJob; @Mock private JobData mockJobData; @Mock private EncryptionKey mockEncryptionKey; @Before public void setUp() { MockitoAnnotations.initMocks(this); model = new CodePipelineStateModel(); } @Test public void testConstructorSetsDefaultValues() { assertEquals(CompressionType.None, model.getCompressionType());
assertEquals(CategoryType.PleaseChooseACategory, model.getActionTypeCategory());
awslabs/aws-codepipeline-plugin-for-jenkins
src/main/java/com/amazonaws/codepipeline/jenkinsplugin/ExtractionTools.java
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import hudson.model.TaskListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.Enumeration; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.io.FileUtils; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.s3.model.S3Object;
} } } entry = archiveInputStream.getNextEntry(); } } private static File getDestinationFile(final File basedir, final String file) throws IOException { final File destination = new File(basedir, file); final String canonicalDestination = destination.getCanonicalPath(); final String canonicalBasedir = basedir.getCanonicalPath(); if (canonicalDestination.startsWith(canonicalBasedir + File.separator) || canonicalDestination.equals(canonicalBasedir)) { return destination; } throw new IOException("The compressed input file contains files targeting an invalid destination: " + file); } public static void deleteTemporaryCompressedFile(final File fileToDelete) throws IOException { if (fileToDelete.isDirectory()) { FileUtils.deleteDirectory(fileToDelete); } else { if (!fileToDelete.delete()) { fileToDelete.deleteOnExit(); } } }
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/ExtractionTools.java import hudson.model.TaskListener; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.Enumeration; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.io.FileUtils; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.s3.model.S3Object; } } } entry = archiveInputStream.getNextEntry(); } } private static File getDestinationFile(final File basedir, final String file) throws IOException { final File destination = new File(basedir, file); final String canonicalDestination = destination.getCanonicalPath(); final String canonicalBasedir = basedir.getCanonicalPath(); if (canonicalDestination.startsWith(canonicalBasedir + File.separator) || canonicalDestination.equals(canonicalBasedir)) { return destination; } throw new IOException("The compressed input file contains files targeting an invalid destination: " + file); } public static void deleteTemporaryCompressedFile(final File fileToDelete) throws IOException { if (fileToDelete.isDirectory()) { FileUtils.deleteDirectory(fileToDelete); } else { if (!fileToDelete.delete()) { fileToDelete.deleteOnExit(); } } }
public static CompressionType getCompressionType(final S3Object sessionObject, final TaskListener l) {
awslabs/aws-codepipeline-plugin-for-jenkins
src/test/java/com/amazonaws/codepipeline/jenkinsplugin/AWSCodePipelinePublisherTest.java
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.when; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.ActionContext; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.FailureType; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData; import com.amazonaws.services.codepipeline.model.PipelineContext; import com.amazonaws.services.codepipeline.model.PutJobFailureResultRequest; import com.amazonaws.services.codepipeline.model.PutJobSuccessResultRequest; import com.amazonaws.services.codepipeline.model.StageContext; import com.amazonaws.services.s3.model.AmazonS3Exception; import hudson.EnvVars; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Result; import hudson.model.TaskListener; import jenkins.model.Jenkins; import net.sf.json.JSONArray; import net.sf.json.JSONObject;
when(mockBuild.getId()).thenReturn(BUILD_ID); when(mockBuild.getResult()).thenReturn(Result.SUCCESS); when(mockBuild.getProject()).thenReturn(mockProject); when(mockBuild.getEnvironment(any(TaskListener.class))).thenReturn(vars); when(vars.get(any(String.class))).thenReturn("Project"); when(mockProject.getName()).thenReturn("Project"); } @Test public void putsJobSuccessWhenBuildSucceeds() { // given when(mockBuild.getResult()).thenReturn(Result.SUCCESS); when(mockJobData.getOutputArtifacts()).thenReturn(generateOutputArtifactsWithNames(Arrays.asList("artifact_1", "artifact_2"))); // when assertTrue(publisher.perform(mockBuild, null, null)); // then final InOrder inOrder = inOrder(mockFactory, mockAWS, mockCodePipelineClient); inOrder.verify(mockFactory).getAwsClient(ACCESS_KEY, SECRET_KEY, PROXY_HOST, PROXY_PORT, REGION, PLUGIN_VERSION); inOrder.verify(mockAWS).getCodePipelineClient(); inOrder.verify(mockCodePipelineClient).putJobSuccessResult(putJobSuccessResultRequest.capture()); final PutJobSuccessResultRequest request = putJobSuccessResultRequest.getValue(); assertEquals(jobId, request.getJobId()); assertEquals(BUILD_ID, request.getExecutionDetails().getExternalExecutionId()); assertEquals("Finished", request.getExecutionDetails().getSummary());
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/AWSCodePipelinePublisherTest.java import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.when; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.ActionContext; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.FailureType; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData; import com.amazonaws.services.codepipeline.model.PipelineContext; import com.amazonaws.services.codepipeline.model.PutJobFailureResultRequest; import com.amazonaws.services.codepipeline.model.PutJobSuccessResultRequest; import com.amazonaws.services.codepipeline.model.StageContext; import com.amazonaws.services.s3.model.AmazonS3Exception; import hudson.EnvVars; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Result; import hudson.model.TaskListener; import jenkins.model.Jenkins; import net.sf.json.JSONArray; import net.sf.json.JSONObject; when(mockBuild.getId()).thenReturn(BUILD_ID); when(mockBuild.getResult()).thenReturn(Result.SUCCESS); when(mockBuild.getProject()).thenReturn(mockProject); when(mockBuild.getEnvironment(any(TaskListener.class))).thenReturn(vars); when(vars.get(any(String.class))).thenReturn("Project"); when(mockProject.getName()).thenReturn("Project"); } @Test public void putsJobSuccessWhenBuildSucceeds() { // given when(mockBuild.getResult()).thenReturn(Result.SUCCESS); when(mockJobData.getOutputArtifacts()).thenReturn(generateOutputArtifactsWithNames(Arrays.asList("artifact_1", "artifact_2"))); // when assertTrue(publisher.perform(mockBuild, null, null)); // then final InOrder inOrder = inOrder(mockFactory, mockAWS, mockCodePipelineClient); inOrder.verify(mockFactory).getAwsClient(ACCESS_KEY, SECRET_KEY, PROXY_HOST, PROXY_PORT, REGION, PLUGIN_VERSION); inOrder.verify(mockAWS).getCodePipelineClient(); inOrder.verify(mockCodePipelineClient).putJobSuccessResult(putJobSuccessResultRequest.capture()); final PutJobSuccessResultRequest request = putJobSuccessResultRequest.getValue(); assertEquals(jobId, request.getJobId()); assertEquals(BUILD_ID, request.getExecutionDetails().getExternalExecutionId()); assertEquals("Finished", request.getExecutionDetails().getSummary());
assertContainsIgnoreCase(PUBLISHING_ARTIFACTS_MESSAGE, outContent.toString());
awslabs/aws-codepipeline-plugin-for-jenkins
src/test/java/com/amazonaws/codepipeline/jenkinsplugin/AWSCodePipelinePublisherTest.java
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.when; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.ActionContext; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.FailureType; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData; import com.amazonaws.services.codepipeline.model.PipelineContext; import com.amazonaws.services.codepipeline.model.PutJobFailureResultRequest; import com.amazonaws.services.codepipeline.model.PutJobSuccessResultRequest; import com.amazonaws.services.codepipeline.model.StageContext; import com.amazonaws.services.s3.model.AmazonS3Exception; import hudson.EnvVars; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Result; import hudson.model.TaskListener; import jenkins.model.Jenkins; import net.sf.json.JSONArray; import net.sf.json.JSONObject;
final AWSCodePipelinePublisher uploadFailurePublisher = new AWSCodePipelinePublisherMockError(outputLocations, mockFactory); // when try { assertFalse(uploadFailurePublisher.perform(mockBuild, null, null)); fail("Expected MockError not thrown"); } catch (final TestError e) { // empty } // then final InOrder inOrder = inOrder(mockFactory, mockAWS, mockCodePipelineClient); inOrder.verify(mockFactory).getAwsClient(ACCESS_KEY, SECRET_KEY, PROXY_HOST, PROXY_PORT, REGION, PLUGIN_VERSION); inOrder.verify(mockAWS).getCodePipelineClient(); inOrder.verify(mockCodePipelineClient).putJobFailureResult(putJobFailureResultRequest.capture()); final PutJobFailureResultRequest request = putJobFailureResultRequest.getValue(); assertEquals(jobId, request.getJobId()); assertEquals(BUILD_ID, request.getFailureDetails().getExternalExecutionId()); assertEquals("Failed to upload output artifact(s): Error", request.getFailureDetails().getMessage()); assertEquals(FailureType.JobFailed.toString(), request.getFailureDetails().getType()); assertContainsIgnoreCase(PUBLISHING_ARTIFACTS_MESSAGE, outContent.toString()); assertContainsIgnoreCase(PUT_JOB_FAILURE_MESSAGE, outContent.toString()); } @Test public void cleanUpSuccess() { // given
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/AWSCodePipelinePublisherTest.java import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.when; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.ActionContext; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.FailureType; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData; import com.amazonaws.services.codepipeline.model.PipelineContext; import com.amazonaws.services.codepipeline.model.PutJobFailureResultRequest; import com.amazonaws.services.codepipeline.model.PutJobSuccessResultRequest; import com.amazonaws.services.codepipeline.model.StageContext; import com.amazonaws.services.s3.model.AmazonS3Exception; import hudson.EnvVars; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Result; import hudson.model.TaskListener; import jenkins.model.Jenkins; import net.sf.json.JSONArray; import net.sf.json.JSONObject; final AWSCodePipelinePublisher uploadFailurePublisher = new AWSCodePipelinePublisherMockError(outputLocations, mockFactory); // when try { assertFalse(uploadFailurePublisher.perform(mockBuild, null, null)); fail("Expected MockError not thrown"); } catch (final TestError e) { // empty } // then final InOrder inOrder = inOrder(mockFactory, mockAWS, mockCodePipelineClient); inOrder.verify(mockFactory).getAwsClient(ACCESS_KEY, SECRET_KEY, PROXY_HOST, PROXY_PORT, REGION, PLUGIN_VERSION); inOrder.verify(mockAWS).getCodePipelineClient(); inOrder.verify(mockCodePipelineClient).putJobFailureResult(putJobFailureResultRequest.capture()); final PutJobFailureResultRequest request = putJobFailureResultRequest.getValue(); assertEquals(jobId, request.getJobId()); assertEquals(BUILD_ID, request.getFailureDetails().getExternalExecutionId()); assertEquals("Failed to upload output artifact(s): Error", request.getFailureDetails().getMessage()); assertEquals(FailureType.JobFailed.toString(), request.getFailureDetails().getType()); assertContainsIgnoreCase(PUBLISHING_ARTIFACTS_MESSAGE, outContent.toString()); assertContainsIgnoreCase(PUT_JOB_FAILURE_MESSAGE, outContent.toString()); } @Test public void cleanUpSuccess() { // given
model.setCompressionType(CompressionType.Zip);
awslabs/aws-codepipeline-plugin-for-jenkins
src/test/java/com/amazonaws/codepipeline/jenkinsplugin/ExtractionToolsTest.java
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; import hudson.model.AbstractBuild; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.zip.CRC32; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.io.FileUtils; import org.apache.tools.zip.ZipOutputStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.S3Object;
throws InitializationError { super(klass, builder); } private static class TestBase { public void setUp() throws IOException { MockitoAnnotations.initMocks(this); TestUtils.initializeTestingFolders(); } public void tearDown() throws IOException { TestUtils.cleanUpTestingFolders(); } } public static class GetCompressionTypeTest extends TestBase { private CodePipelineStateModel model; @Mock private S3Object obj; @Mock private AbstractBuild<?, ?> mockBuild; @Mock private ObjectMetadata metadata; @Before public void setUp() throws IOException { super.setUp(); model = new CodePipelineStateModel();
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/ExtractionToolsTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; import hudson.model.AbstractBuild; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.zip.CRC32; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.io.FileUtils; import org.apache.tools.zip.ZipOutputStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.S3Object; throws InitializationError { super(klass, builder); } private static class TestBase { public void setUp() throws IOException { MockitoAnnotations.initMocks(this); TestUtils.initializeTestingFolders(); } public void tearDown() throws IOException { TestUtils.cleanUpTestingFolders(); } } public static class GetCompressionTypeTest extends TestBase { private CodePipelineStateModel model; @Mock private S3Object obj; @Mock private AbstractBuild<?, ?> mockBuild; @Mock private ObjectMetadata metadata; @Before public void setUp() throws IOException { super.setUp(); model = new CodePipelineStateModel();
model.setCompressionType(CompressionType.None);
awslabs/aws-codepipeline-plugin-for-jenkins
src/test/java/com/amazonaws/codepipeline/jenkinsplugin/AWSCodePipelineSCMTest.java
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CategoryType { // PleaseChooseACategory("Please Choose A Category"), // Build("Build"), // Test("Test"); // // private final String name; // // CategoryType(final String name) { // this.name = name; // } // // public String getName() { // return this.name; // } // // public static CategoryType fromName(final String name) { // for (final CategoryType category : values()) { // if (name.equals(category.getName())) { // return category; // } // } // // throw new IllegalArgumentException("Cannot create enum from " + name + " value!"); // } // }
import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import hudson.AbortException; import hudson.EnvVars; import hudson.FilePath; import hudson.model.FreeStyleProject; import hudson.model.Project; import hudson.model.TaskListener; import hudson.model.AbstractBuild; import hudson.scm.PollingResult; import hudson.scm.SCM; import hudson.util.FormValidation; import hudson.util.Secret; import jenkins.model.Jenkins; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.UUID; import org.apache.commons.lang.RandomStringUtils; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; import org.jvnet.hudson.test.JenkinsRule; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CategoryType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.AcknowledgeJobRequest; import com.amazonaws.services.codepipeline.model.AcknowledgeJobResult; import com.amazonaws.services.codepipeline.model.ActionOwner; import com.amazonaws.services.codepipeline.model.ActionTypeId; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.InvalidNonceException; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData; import com.amazonaws.services.codepipeline.model.PollForJobsRequest; import com.amazonaws.services.codepipeline.model.PollForJobsResult;
SECRET_KEY, PROXY_HOST, String.valueOf(PROXY_PORT), ACTION_TYPE.getCategory(), ACTION_TYPE.getProvider(), ACTION_TYPE.getVersion(), mockFactory); outContent = TestUtils.setOutputStream(); when(codePipelineClient.pollForJobs(any(PollForJobsRequest.class))).thenReturn(pollForJobsResult); when(pollForJobsResult.getJobs()).thenReturn(Collections.singletonList(job)); } } public static class PollForJobsTests extends PollingTestBase { @Before public void setUp() throws IOException, InterruptedException, ReflectiveOperationException { super.setUp(); } @Test public void returnsBuildNowWhenThereIsAJob() throws InterruptedException, IOException { // when assertEquals(PollingResult.BUILD_NOW, scm.pollForJobs(PROJECT_NAME, ACTION_TYPE, null)); // then final String expectedMessage = String.format("[AWS CodePipeline Plugin] Received job with ID: %1$s", jobId);
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CategoryType { // PleaseChooseACategory("Please Choose A Category"), // Build("Build"), // Test("Test"); // // private final String name; // // CategoryType(final String name) { // this.name = name; // } // // public String getName() { // return this.name; // } // // public static CategoryType fromName(final String name) { // for (final CategoryType category : values()) { // if (name.equals(category.getName())) { // return category; // } // } // // throw new IllegalArgumentException("Cannot create enum from " + name + " value!"); // } // } // Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/AWSCodePipelineSCMTest.java import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import hudson.AbortException; import hudson.EnvVars; import hudson.FilePath; import hudson.model.FreeStyleProject; import hudson.model.Project; import hudson.model.TaskListener; import hudson.model.AbstractBuild; import hudson.scm.PollingResult; import hudson.scm.SCM; import hudson.util.FormValidation; import hudson.util.Secret; import jenkins.model.Jenkins; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.UUID; import org.apache.commons.lang.RandomStringUtils; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; import org.jvnet.hudson.test.JenkinsRule; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CategoryType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.AcknowledgeJobRequest; import com.amazonaws.services.codepipeline.model.AcknowledgeJobResult; import com.amazonaws.services.codepipeline.model.ActionOwner; import com.amazonaws.services.codepipeline.model.ActionTypeId; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.InvalidNonceException; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData; import com.amazonaws.services.codepipeline.model.PollForJobsRequest; import com.amazonaws.services.codepipeline.model.PollForJobsResult; SECRET_KEY, PROXY_HOST, String.valueOf(PROXY_PORT), ACTION_TYPE.getCategory(), ACTION_TYPE.getProvider(), ACTION_TYPE.getVersion(), mockFactory); outContent = TestUtils.setOutputStream(); when(codePipelineClient.pollForJobs(any(PollForJobsRequest.class))).thenReturn(pollForJobsResult); when(pollForJobsResult.getJobs()).thenReturn(Collections.singletonList(job)); } } public static class PollForJobsTests extends PollingTestBase { @Before public void setUp() throws IOException, InterruptedException, ReflectiveOperationException { super.setUp(); } @Test public void returnsBuildNowWhenThereIsAJob() throws InterruptedException, IOException { // when assertEquals(PollingResult.BUILD_NOW, scm.pollForJobs(PROJECT_NAME, ACTION_TYPE, null)); // then final String expectedMessage = String.format("[AWS CodePipeline Plugin] Received job with ID: %1$s", jobId);
assertContainsIgnoreCase(expectedMessage, outContent.toString());
awslabs/aws-codepipeline-plugin-for-jenkins
src/test/java/com/amazonaws/codepipeline/jenkinsplugin/AWSCodePipelineSCMTest.java
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CategoryType { // PleaseChooseACategory("Please Choose A Category"), // Build("Build"), // Test("Test"); // // private final String name; // // CategoryType(final String name) { // this.name = name; // } // // public String getName() { // return this.name; // } // // public static CategoryType fromName(final String name) { // for (final CategoryType category : values()) { // if (name.equals(category.getName())) { // return category; // } // } // // throw new IllegalArgumentException("Cannot create enum from " + name + " value!"); // } // }
import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import hudson.AbortException; import hudson.EnvVars; import hudson.FilePath; import hudson.model.FreeStyleProject; import hudson.model.Project; import hudson.model.TaskListener; import hudson.model.AbstractBuild; import hudson.scm.PollingResult; import hudson.scm.SCM; import hudson.util.FormValidation; import hudson.util.Secret; import jenkins.model.Jenkins; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.UUID; import org.apache.commons.lang.RandomStringUtils; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; import org.jvnet.hudson.test.JenkinsRule; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CategoryType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.AcknowledgeJobRequest; import com.amazonaws.services.codepipeline.model.AcknowledgeJobResult; import com.amazonaws.services.codepipeline.model.ActionOwner; import com.amazonaws.services.codepipeline.model.ActionTypeId; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.InvalidNonceException; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData; import com.amazonaws.services.codepipeline.model.PollForJobsRequest; import com.amazonaws.services.codepipeline.model.PollForJobsResult;
@Mock private EnvVars envVars; @Mock private CodePipelineStateModel model; @Mock private Job mockJob; private AWSCodePipelineSCM.DescriptorImpl descriptor; @Before public void setUp() throws IOException, InterruptedException, ReflectiveOperationException { super.setUp(); descriptor = new AWSCodePipelineSCM.DescriptorImpl(false); when(mockBuild.getEnvironment(any(TaskListener.class))).thenReturn(envVars); when(envVars.get(any(String.class))).thenReturn("Project"); when(model.getJob()).thenReturn(mockJob); when(mockJob.getId()).thenReturn(jobId); CodePipelineStateService.setModel(model); } @After public void tearDown() { CodePipelineStateService.removeModel(); } @Test public void doCheckCategorySucceedsWithBuildCategory() {
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CategoryType { // PleaseChooseACategory("Please Choose A Category"), // Build("Build"), // Test("Test"); // // private final String name; // // CategoryType(final String name) { // this.name = name; // } // // public String getName() { // return this.name; // } // // public static CategoryType fromName(final String name) { // for (final CategoryType category : values()) { // if (name.equals(category.getName())) { // return category; // } // } // // throw new IllegalArgumentException("Cannot create enum from " + name + " value!"); // } // } // Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/AWSCodePipelineSCMTest.java import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import hudson.AbortException; import hudson.EnvVars; import hudson.FilePath; import hudson.model.FreeStyleProject; import hudson.model.Project; import hudson.model.TaskListener; import hudson.model.AbstractBuild; import hudson.scm.PollingResult; import hudson.scm.SCM; import hudson.util.FormValidation; import hudson.util.Secret; import jenkins.model.Jenkins; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.UUID; import org.apache.commons.lang.RandomStringUtils; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; import org.jvnet.hudson.test.JenkinsRule; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CategoryType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.AcknowledgeJobRequest; import com.amazonaws.services.codepipeline.model.AcknowledgeJobResult; import com.amazonaws.services.codepipeline.model.ActionOwner; import com.amazonaws.services.codepipeline.model.ActionTypeId; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.InvalidNonceException; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData; import com.amazonaws.services.codepipeline.model.PollForJobsRequest; import com.amazonaws.services.codepipeline.model.PollForJobsResult; @Mock private EnvVars envVars; @Mock private CodePipelineStateModel model; @Mock private Job mockJob; private AWSCodePipelineSCM.DescriptorImpl descriptor; @Before public void setUp() throws IOException, InterruptedException, ReflectiveOperationException { super.setUp(); descriptor = new AWSCodePipelineSCM.DescriptorImpl(false); when(mockBuild.getEnvironment(any(TaskListener.class))).thenReturn(envVars); when(envVars.get(any(String.class))).thenReturn("Project"); when(model.getJob()).thenReturn(mockJob); when(mockJob.getId()).thenReturn(jobId); CodePipelineStateService.setModel(model); } @After public void tearDown() { CodePipelineStateService.removeModel(); } @Test public void doCheckCategorySucceedsWithBuildCategory() {
assertEquals(FormValidation.ok(), descriptor.doCheckCategory(CategoryType.Build.name()));
awslabs/aws-codepipeline-plugin-for-jenkins
src/main/java/com/amazonaws/codepipeline/jenkinsplugin/AWSCodePipelineSCM.java
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CategoryType { // PleaseChooseACategory("Please Choose A Category"), // Build("Build"), // Test("Test"); // // private final String name; // // CategoryType(final String name) { // this.name = name; // } // // public String getName() { // return this.name; // } // // public static CategoryType fromName(final String name) { // for (final CategoryType category : values()) { // if (name.equals(category.getName())) { // return category; // } // } // // throw new IllegalArgumentException("Cannot create enum from " + name + " value!"); // } // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.Random; import org.apache.commons.lang.StringUtils; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CategoryType; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.regions.Regions; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.AcknowledgeJobRequest; import com.amazonaws.services.codepipeline.model.AcknowledgeJobResult; import com.amazonaws.services.codepipeline.model.ActionOwner; import com.amazonaws.services.codepipeline.model.ActionTypeId; import com.amazonaws.services.codepipeline.model.InvalidNonceException; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobStatus; import com.amazonaws.services.codepipeline.model.PollForJobsRequest; import com.amazonaws.services.codepipeline.model.PollForJobsResult; import hudson.AbortException; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.TaskListener; import hudson.scm.ChangeLogParser; import hudson.scm.NullChangeLogParser; import hudson.scm.PollingResult; import hudson.scm.SCM; import hudson.scm.SCMDescriptor; import hudson.scm.SCMRevisionState; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import hudson.util.Secret; import net.sf.json.JSONObject;
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.codepipeline.jenkinsplugin; public class AWSCodePipelineSCM extends hudson.scm.SCM { public static final Regions[] AVAILABLE_REGIONS = { Regions.US_EAST_1, Regions.US_EAST_2, Regions.US_WEST_1, Regions.US_WEST_2, Regions.AP_EAST_1, Regions.AP_SOUTH_1, Regions.AP_NORTHEAST_2, Regions.AP_SOUTHEAST_1, Regions.AP_SOUTHEAST_2, Regions.AP_NORTHEAST_1, Regions.CA_CENTRAL_1, Regions.EU_CENTRAL_1, Regions.EU_WEST_1, Regions.EU_WEST_2, Regions.EU_SOUTH_1, Regions.EU_WEST_3, Regions.EU_NORTH_1, Regions.SA_EAST_1, Regions.GovCloud, Regions.CN_NORTH_1, Regions.CN_NORTHWEST_1 };
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CategoryType { // PleaseChooseACategory("Please Choose A Category"), // Build("Build"), // Test("Test"); // // private final String name; // // CategoryType(final String name) { // this.name = name; // } // // public String getName() { // return this.name; // } // // public static CategoryType fromName(final String name) { // for (final CategoryType category : values()) { // if (name.equals(category.getName())) { // return category; // } // } // // throw new IllegalArgumentException("Cannot create enum from " + name + " value!"); // } // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/AWSCodePipelineSCM.java import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.Random; import org.apache.commons.lang.StringUtils; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CategoryType; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.regions.Regions; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.AcknowledgeJobRequest; import com.amazonaws.services.codepipeline.model.AcknowledgeJobResult; import com.amazonaws.services.codepipeline.model.ActionOwner; import com.amazonaws.services.codepipeline.model.ActionTypeId; import com.amazonaws.services.codepipeline.model.InvalidNonceException; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobStatus; import com.amazonaws.services.codepipeline.model.PollForJobsRequest; import com.amazonaws.services.codepipeline.model.PollForJobsResult; import hudson.AbortException; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.TaskListener; import hudson.scm.ChangeLogParser; import hudson.scm.NullChangeLogParser; import hudson.scm.PollingResult; import hudson.scm.SCM; import hudson.scm.SCMDescriptor; import hudson.scm.SCMRevisionState; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import hudson.util.Secret; import net.sf.json.JSONObject; /* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.codepipeline.jenkinsplugin; public class AWSCodePipelineSCM extends hudson.scm.SCM { public static final Regions[] AVAILABLE_REGIONS = { Regions.US_EAST_1, Regions.US_EAST_2, Regions.US_WEST_1, Regions.US_WEST_2, Regions.AP_EAST_1, Regions.AP_SOUTH_1, Regions.AP_NORTHEAST_2, Regions.AP_SOUTHEAST_1, Regions.AP_SOUTHEAST_2, Regions.AP_NORTHEAST_1, Regions.CA_CENTRAL_1, Regions.EU_CENTRAL_1, Regions.EU_WEST_1, Regions.EU_WEST_2, Regions.EU_SOUTH_1, Regions.EU_WEST_3, Regions.EU_NORTH_1, Regions.SA_EAST_1, Regions.GovCloud, Regions.CN_NORTH_1, Regions.CN_NORTHWEST_1 };
public static final CategoryType[] ACTION_TYPE = {
awslabs/aws-codepipeline-plugin-for-jenkins
src/main/java/com/amazonaws/codepipeline/jenkinsplugin/AWSCodePipelineSCM.java
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CategoryType { // PleaseChooseACategory("Please Choose A Category"), // Build("Build"), // Test("Test"); // // private final String name; // // CategoryType(final String name) { // this.name = name; // } // // public String getName() { // return this.name; // } // // public static CategoryType fromName(final String name) { // for (final CategoryType category : values()) { // if (name.equals(category.getName())) { // return category; // } // } // // throw new IllegalArgumentException("Cannot create enum from " + name + " value!"); // } // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.Random; import org.apache.commons.lang.StringUtils; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CategoryType; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.regions.Regions; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.AcknowledgeJobRequest; import com.amazonaws.services.codepipeline.model.AcknowledgeJobResult; import com.amazonaws.services.codepipeline.model.ActionOwner; import com.amazonaws.services.codepipeline.model.ActionTypeId; import com.amazonaws.services.codepipeline.model.InvalidNonceException; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobStatus; import com.amazonaws.services.codepipeline.model.PollForJobsRequest; import com.amazonaws.services.codepipeline.model.PollForJobsResult; import hudson.AbortException; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.TaskListener; import hudson.scm.ChangeLogParser; import hudson.scm.NullChangeLogParser; import hudson.scm.PollingResult; import hudson.scm.SCM; import hudson.scm.SCMDescriptor; import hudson.scm.SCMRevisionState; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import hudson.util.Secret; import net.sf.json.JSONObject;
public String getProxyHost() { return proxyHost; } public int getProxyPort() { return proxyPort; } public String getCategory() { return actionTypeCategory; } public String getProvider() { return actionTypeProvider; } public String getVersion() { return actionTypeVersion; } // this is required so we can use JenkinsRule.assertEqualDataBoundBeans in unit tests public String getName() { return null; } public void initializeModel() { final CodePipelineStateModel model = new CodePipelineStateModel(); model.setActionTypeCategory(actionTypeCategory); model.setAwsAccessKey(awsAccessKey); model.setAwsSecretKey(Secret.toString(awsSecretKey));
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CategoryType { // PleaseChooseACategory("Please Choose A Category"), // Build("Build"), // Test("Test"); // // private final String name; // // CategoryType(final String name) { // this.name = name; // } // // public String getName() { // return this.name; // } // // public static CategoryType fromName(final String name) { // for (final CategoryType category : values()) { // if (name.equals(category.getName())) { // return category; // } // } // // throw new IllegalArgumentException("Cannot create enum from " + name + " value!"); // } // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/AWSCodePipelineSCM.java import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.Random; import org.apache.commons.lang.StringUtils; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CategoryType; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.regions.Regions; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.AcknowledgeJobRequest; import com.amazonaws.services.codepipeline.model.AcknowledgeJobResult; import com.amazonaws.services.codepipeline.model.ActionOwner; import com.amazonaws.services.codepipeline.model.ActionTypeId; import com.amazonaws.services.codepipeline.model.InvalidNonceException; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobStatus; import com.amazonaws.services.codepipeline.model.PollForJobsRequest; import com.amazonaws.services.codepipeline.model.PollForJobsResult; import hudson.AbortException; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.TaskListener; import hudson.scm.ChangeLogParser; import hudson.scm.NullChangeLogParser; import hudson.scm.PollingResult; import hudson.scm.SCM; import hudson.scm.SCMDescriptor; import hudson.scm.SCMRevisionState; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import hudson.util.Secret; import net.sf.json.JSONObject; public String getProxyHost() { return proxyHost; } public int getProxyPort() { return proxyPort; } public String getCategory() { return actionTypeCategory; } public String getProvider() { return actionTypeProvider; } public String getVersion() { return actionTypeVersion; } // this is required so we can use JenkinsRule.assertEqualDataBoundBeans in unit tests public String getName() { return null; } public void initializeModel() { final CodePipelineStateModel model = new CodePipelineStateModel(); model.setActionTypeCategory(actionTypeCategory); model.setAwsAccessKey(awsAccessKey); model.setAwsSecretKey(Secret.toString(awsSecretKey));
model.setCompressionType(CompressionType.None);
awslabs/aws-codepipeline-plugin-for-jenkins
src/test/java/com/amazonaws/codepipeline/jenkinsplugin/PublisherToolsTest.java
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.Matchers.any; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.ArtifactLocation; import com.amazonaws.services.codepipeline.model.EncryptionKey; import com.amazonaws.services.codepipeline.model.EncryptionKeyType; import com.amazonaws.services.codepipeline.model.PutJobFailureResultRequest; import com.amazonaws.services.codepipeline.model.PutJobSuccessResultRequest; import com.amazonaws.services.codepipeline.model.S3ArtifactLocation; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.CompleteMultipartUploadRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadResult; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.SSEAwsKeyManagementParams; import com.amazonaws.services.s3.model.UploadPartRequest; import com.amazonaws.services.s3.model.UploadPartResult;
assertEquals(outContent.toString().toLowerCase(), message.toLowerCase()); } @Test public void putJobResultBuildFailureSuccess() { final String message = "[AWS CodePipeline Plugin] Build failed, calling PutJobFailureResult" + System.lineSeparator(); PublisherTools.putJobResult( false, // Build Succeeded "Generic Error", // Error Message "0", // ActionID "1", // Job ID mockCodePipelineClient, null); // Listener final ArgumentCaptor<PutJobFailureResultRequest> failureRequest = ArgumentCaptor.forClass(PutJobFailureResultRequest.class); verify(mockCodePipelineClient, times(1)).putJobFailureResult(failureRequest.capture()); assertEquals("Generic Error".toLowerCase(), failureRequest.getValue().getFailureDetails().getMessage().toLowerCase()); assertEquals(outContent.toString().toLowerCase(), message.toLowerCase()); } @Test public void uploadFileSuccess() throws IOException { TestUtils.initializeTestingFolders(); final File compressedFile = CompressionTools.compressFile( "ZipProject", PATH_TO_COMPRESS,
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/PublisherToolsTest.java import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.Matchers.any; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.ArtifactLocation; import com.amazonaws.services.codepipeline.model.EncryptionKey; import com.amazonaws.services.codepipeline.model.EncryptionKeyType; import com.amazonaws.services.codepipeline.model.PutJobFailureResultRequest; import com.amazonaws.services.codepipeline.model.PutJobSuccessResultRequest; import com.amazonaws.services.codepipeline.model.S3ArtifactLocation; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.CompleteMultipartUploadRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadResult; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.SSEAwsKeyManagementParams; import com.amazonaws.services.s3.model.UploadPartRequest; import com.amazonaws.services.s3.model.UploadPartResult; assertEquals(outContent.toString().toLowerCase(), message.toLowerCase()); } @Test public void putJobResultBuildFailureSuccess() { final String message = "[AWS CodePipeline Plugin] Build failed, calling PutJobFailureResult" + System.lineSeparator(); PublisherTools.putJobResult( false, // Build Succeeded "Generic Error", // Error Message "0", // ActionID "1", // Job ID mockCodePipelineClient, null); // Listener final ArgumentCaptor<PutJobFailureResultRequest> failureRequest = ArgumentCaptor.forClass(PutJobFailureResultRequest.class); verify(mockCodePipelineClient, times(1)).putJobFailureResult(failureRequest.capture()); assertEquals("Generic Error".toLowerCase(), failureRequest.getValue().getFailureDetails().getMessage().toLowerCase()); assertEquals(outContent.toString().toLowerCase(), message.toLowerCase()); } @Test public void uploadFileSuccess() throws IOException { TestUtils.initializeTestingFolders(); final File compressedFile = CompressionTools.compressFile( "ZipProject", PATH_TO_COMPRESS,
CompressionType.Zip,
awslabs/aws-codepipeline-plugin-for-jenkins
src/test/java/com/amazonaws/codepipeline/jenkinsplugin/PublisherToolsTest.java
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.Matchers.any; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.ArtifactLocation; import com.amazonaws.services.codepipeline.model.EncryptionKey; import com.amazonaws.services.codepipeline.model.EncryptionKeyType; import com.amazonaws.services.codepipeline.model.PutJobFailureResultRequest; import com.amazonaws.services.codepipeline.model.PutJobSuccessResultRequest; import com.amazonaws.services.codepipeline.model.S3ArtifactLocation; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.CompleteMultipartUploadRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadResult; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.SSEAwsKeyManagementParams; import com.amazonaws.services.s3.model.UploadPartRequest; import com.amazonaws.services.s3.model.UploadPartResult;
verify(mockCodePipelineClient, times(1)).putJobFailureResult(failureRequest.capture()); assertEquals("Generic Error".toLowerCase(), failureRequest.getValue().getFailureDetails().getMessage().toLowerCase()); assertEquals(outContent.toString().toLowerCase(), message.toLowerCase()); } @Test public void uploadFileSuccess() throws IOException { TestUtils.initializeTestingFolders(); final File compressedFile = CompressionTools.compressFile( "ZipProject", PATH_TO_COMPRESS, CompressionType.Zip, null); PublisherTools.uploadFile( compressedFile, mockArtifact, CompressionType.Zip, null, // No custom encryption key mockS3Client, null); // Listener final InOrder inOrder = inOrder(mockS3Client); inOrder.verify(mockS3Client, times(1)).initiateMultipartUpload(initiateCaptor.capture()); // Total size is less than 5MB, should only be one upload inOrder.verify(mockS3Client, times(1)).uploadPart(any(UploadPartRequest.class)); inOrder.verify(mockS3Client, times(1)).completeMultipartUpload(any(CompleteMultipartUploadRequest.class));
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/PublisherToolsTest.java import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.Matchers.any; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.ArtifactLocation; import com.amazonaws.services.codepipeline.model.EncryptionKey; import com.amazonaws.services.codepipeline.model.EncryptionKeyType; import com.amazonaws.services.codepipeline.model.PutJobFailureResultRequest; import com.amazonaws.services.codepipeline.model.PutJobSuccessResultRequest; import com.amazonaws.services.codepipeline.model.S3ArtifactLocation; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.CompleteMultipartUploadRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadResult; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.SSEAwsKeyManagementParams; import com.amazonaws.services.s3.model.UploadPartRequest; import com.amazonaws.services.s3.model.UploadPartResult; verify(mockCodePipelineClient, times(1)).putJobFailureResult(failureRequest.capture()); assertEquals("Generic Error".toLowerCase(), failureRequest.getValue().getFailureDetails().getMessage().toLowerCase()); assertEquals(outContent.toString().toLowerCase(), message.toLowerCase()); } @Test public void uploadFileSuccess() throws IOException { TestUtils.initializeTestingFolders(); final File compressedFile = CompressionTools.compressFile( "ZipProject", PATH_TO_COMPRESS, CompressionType.Zip, null); PublisherTools.uploadFile( compressedFile, mockArtifact, CompressionType.Zip, null, // No custom encryption key mockS3Client, null); // Listener final InOrder inOrder = inOrder(mockS3Client); inOrder.verify(mockS3Client, times(1)).initiateMultipartUpload(initiateCaptor.capture()); // Total size is less than 5MB, should only be one upload inOrder.verify(mockS3Client, times(1)).uploadPart(any(UploadPartRequest.class)); inOrder.verify(mockS3Client, times(1)).completeMultipartUpload(any(CompleteMultipartUploadRequest.class));
assertContainsIgnoreCase("[AWS CodePipeline Plugin] Uploading artifact:", outContent.toString());
awslabs/aws-codepipeline-plugin-for-jenkins
src/main/java/com/amazonaws/codepipeline/jenkinsplugin/AWSCodePipelinePublisher.java
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CategoryType { // PleaseChooseACategory("Please Choose A Category"), // Build("Build"), // Test("Test"); // // private final String name; // // CategoryType(final String name) { // this.name = name; // } // // public String getName() { // return this.name; // } // // public static CategoryType fromName(final String name) { // for (final CategoryType category : values()) { // if (name.equals(category.getName())) { // return category; // } // } // // throw new IllegalArgumentException("Cannot create enum from " + name + " value!"); // } // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import com.amazonaws.AmazonServiceException; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CategoryType; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.model.Artifact; import hudson.Extension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Result; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import net.sf.json.JSONArray; import net.sf.json.JSONObject;
final AbstractBuild<?,?> action, final Launcher launcher, final BuildListener listener) { final CodePipelineStateModel model = CodePipelineStateService.getModel(); final boolean actionSucceeded = action.getResult() == Result.SUCCESS; boolean awsStatus = actionSucceeded; String error = "Failed"; if (model == null) { LoggingHelper.log(listener, "Error with Model Thread Handling"); return false; } if (model.isSkipPutJobResult()) { LoggingHelper.log( listener, String.format("Skipping PutJobFailureResult call for the job with ID %s", model.getJob().getId())); return false; } final AWSClients awsClients = awsClientFactory.getAwsClient( model.getAwsAccessKey(), model.getAwsSecretKey(), model.getProxyHost(), model.getProxyPort(), model.getRegion(), JenkinsMetadata.getPluginUserAgentPrefix()); if (!actionSucceeded) {
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CategoryType { // PleaseChooseACategory("Please Choose A Category"), // Build("Build"), // Test("Test"); // // private final String name; // // CategoryType(final String name) { // this.name = name; // } // // public String getName() { // return this.name; // } // // public static CategoryType fromName(final String name) { // for (final CategoryType category : values()) { // if (name.equals(category.getName())) { // return category; // } // } // // throw new IllegalArgumentException("Cannot create enum from " + name + " value!"); // } // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/AWSCodePipelinePublisher.java import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import com.amazonaws.AmazonServiceException; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CategoryType; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.model.Artifact; import hudson.Extension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Result; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import net.sf.json.JSONArray; import net.sf.json.JSONObject; final AbstractBuild<?,?> action, final Launcher launcher, final BuildListener listener) { final CodePipelineStateModel model = CodePipelineStateService.getModel(); final boolean actionSucceeded = action.getResult() == Result.SUCCESS; boolean awsStatus = actionSucceeded; String error = "Failed"; if (model == null) { LoggingHelper.log(listener, "Error with Model Thread Handling"); return false; } if (model.isSkipPutJobResult()) { LoggingHelper.log( listener, String.format("Skipping PutJobFailureResult call for the job with ID %s", model.getJob().getId())); return false; } final AWSClients awsClients = awsClientFactory.getAwsClient( model.getAwsAccessKey(), model.getAwsSecretKey(), model.getProxyHost(), model.getProxyPort(), model.getRegion(), JenkinsMetadata.getPluginUserAgentPrefix()); if (!actionSucceeded) {
if (model.getActionTypeCategory() == CategoryType.Build) {
awslabs/aws-codepipeline-plugin-for-jenkins
src/main/java/com/amazonaws/codepipeline/jenkinsplugin/AWSCodePipelinePublisher.java
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CategoryType { // PleaseChooseACategory("Please Choose A Category"), // Build("Build"), // Test("Test"); // // private final String name; // // CategoryType(final String name) { // this.name = name; // } // // public String getName() { // return this.name; // } // // public static CategoryType fromName(final String name) { // for (final CategoryType category : values()) { // if (name.equals(category.getName())) { // return category; // } // } // // throw new IllegalArgumentException("Cannot create enum from " + name + " value!"); // } // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import com.amazonaws.AmazonServiceException; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CategoryType; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.model.Artifact; import hudson.Extension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Result; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import net.sf.json.JSONArray; import net.sf.json.JSONObject;
} catch (final AmazonServiceException ex) { error = "Failed to upload output artifact(s): " + ex.getErrorMessage(); LoggingHelper.log(listener, ex.getMessage()); LoggingHelper.log(listener, ex); awsStatus = false; } catch (final RuntimeException | InterruptedException | IOException ex) { error = "Failed to upload output artifact(s): " + ex.getMessage(); LoggingHelper.log(listener, ex.getMessage()); LoggingHelper.log(listener, ex); awsStatus = false; } catch (final Throwable ex) { error = "Failed to upload output artifact(s): " + ex.getMessage(); awsStatus = false; throw ex; } finally { PublisherTools.putJobResult( awsStatus, error, action.getId(), model.getJob().getId(), awsClients.getCodePipelineClient(), listener); cleanUp(model); } return awsStatus; } public void cleanUp(final CodePipelineStateModel model) { model.clearJob();
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CategoryType { // PleaseChooseACategory("Please Choose A Category"), // Build("Build"), // Test("Test"); // // private final String name; // // CategoryType(final String name) { // this.name = name; // } // // public String getName() { // return this.name; // } // // public static CategoryType fromName(final String name) { // for (final CategoryType category : values()) { // if (name.equals(category.getName())) { // return category; // } // } // // throw new IllegalArgumentException("Cannot create enum from " + name + " value!"); // } // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/AWSCodePipelinePublisher.java import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import com.amazonaws.AmazonServiceException; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CategoryType; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.model.Artifact; import hudson.Extension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Result; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import net.sf.json.JSONArray; import net.sf.json.JSONObject; } catch (final AmazonServiceException ex) { error = "Failed to upload output artifact(s): " + ex.getErrorMessage(); LoggingHelper.log(listener, ex.getMessage()); LoggingHelper.log(listener, ex); awsStatus = false; } catch (final RuntimeException | InterruptedException | IOException ex) { error = "Failed to upload output artifact(s): " + ex.getMessage(); LoggingHelper.log(listener, ex.getMessage()); LoggingHelper.log(listener, ex); awsStatus = false; } catch (final Throwable ex) { error = "Failed to upload output artifact(s): " + ex.getMessage(); awsStatus = false; throw ex; } finally { PublisherTools.putJobResult( awsStatus, error, action.getId(), model.getJob().getId(), awsClients.getCodePipelineClient(), listener); cleanUp(model); } return awsStatus; } public void cleanUp(final CodePipelineStateModel model) { model.clearJob();
model.setCompressionType(CompressionType.None);
awslabs/aws-codepipeline-plugin-for-jenkins
src/main/java/com/amazonaws/codepipeline/jenkinsplugin/PublisherCallable.java
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import hudson.FilePath.FileCallable; import hudson.model.BuildListener; import hudson.remoting.VirtualChannel; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.s3.AmazonS3;
final Set<String> artifactNames = getArtifactNamesFromProject(outputs); if (!artifactNames.isEmpty() && artifactNames.size() != outputs.size()) { final String message = "Not all locations have artifact name. " + "Either enter an artifact name for each location, " + "or leave the field blank."; LoggingHelper.log(listener, message); throw new IllegalArgumentException(message); } if (artifactNames.size() == outputs.size()) { for (final OutputArtifact outputArtifact : outputs) { artifactLocations.put(outputArtifact.getArtifactName(), outputArtifact.getLocation()); } } else { Iterator<Artifact> artifactIterator = model.getJob().getData().getOutputArtifacts().iterator(); for (final OutputArtifact outputArtifact : outputs) { final Artifact artifact = artifactIterator.next(); artifactLocations.put(artifact.getName(), outputArtifact.getLocation()); } } for (final Artifact artifact : model.getJob().getData().getOutputArtifacts()) { final String artifactLocation = artifactLocations.get(artifact.getName()); if (artifactLocation != null) { final Path pathToUpload = CompressionTools.resolveWorkspacePath(workspace, artifactLocation); if (Files.isDirectory(pathToUpload.toRealPath())) { uploadDirectory(pathToUpload, artifact, amazonS3); } else {
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/PublisherCallable.java import hudson.FilePath.FileCallable; import hudson.model.BuildListener; import hudson.remoting.VirtualChannel; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.s3.AmazonS3; final Set<String> artifactNames = getArtifactNamesFromProject(outputs); if (!artifactNames.isEmpty() && artifactNames.size() != outputs.size()) { final String message = "Not all locations have artifact name. " + "Either enter an artifact name for each location, " + "or leave the field blank."; LoggingHelper.log(listener, message); throw new IllegalArgumentException(message); } if (artifactNames.size() == outputs.size()) { for (final OutputArtifact outputArtifact : outputs) { artifactLocations.put(outputArtifact.getArtifactName(), outputArtifact.getLocation()); } } else { Iterator<Artifact> artifactIterator = model.getJob().getData().getOutputArtifacts().iterator(); for (final OutputArtifact outputArtifact : outputs) { final Artifact artifact = artifactIterator.next(); artifactLocations.put(artifact.getName(), outputArtifact.getLocation()); } } for (final Artifact artifact : model.getJob().getData().getOutputArtifacts()) { final String artifactLocation = artifactLocations.get(artifact.getName()); if (artifactLocation != null) { final Path pathToUpload = CompressionTools.resolveWorkspacePath(workspace, artifactLocation); if (Files.isDirectory(pathToUpload.toRealPath())) { uploadDirectory(pathToUpload, artifact, amazonS3); } else {
uploadFile(pathToUpload.toFile(), artifact, CompressionType.None, amazonS3);
awslabs/aws-codepipeline-plugin-for-jenkins
src/test/java/com/amazonaws/codepipeline/jenkinsplugin/ValidationTest.java
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CategoryType { // PleaseChooseACategory("Please Choose A Category"), // Build("Build"), // Test("Test"); // // private final String name; // // CategoryType(final String name) { // this.name = name; // } // // public String getName() { // return this.name; // } // // public static CategoryType fromName(final String name) { // for (final CategoryType category : values()) { // if (name.equals(category.getName())) { // return category; // } // } // // throw new IllegalArgumentException("Cannot create enum from " + name + " value!"); // } // }
import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.RandomStringUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CategoryType; import com.amazonaws.services.codepipeline.model.Artifact; import hudson.model.Failure;
} } @Test public void numberOfOutputsSuccess() { final List<Artifact> artifacts = new ArrayList<>(); for (int i = 0; i < Validation.MAX_ARTIFACTS; i++) { artifacts.add(new Artifact()); } Validation.numberOfOutPutsIsValid(artifacts); } @Test(expected=Exception.class) public void numberOfOutputsFailure() { final List<Artifact> artifacts = new ArrayList<>(); while (artifacts.size() <= Validation.MAX_ARTIFACTS) { artifacts.add(new Artifact()); } Validation.numberOfOutPutsIsValid(artifacts); } @Test public void validatePluginAllFieldsCorrectEmptyCredentialsSuccess() { Validation.validatePlugin( "", "", "us-east-1",
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CategoryType { // PleaseChooseACategory("Please Choose A Category"), // Build("Build"), // Test("Test"); // // private final String name; // // CategoryType(final String name) { // this.name = name; // } // // public String getName() { // return this.name; // } // // public static CategoryType fromName(final String name) { // for (final CategoryType category : values()) { // if (name.equals(category.getName())) { // return category; // } // } // // throw new IllegalArgumentException("Cannot create enum from " + name + " value!"); // } // } // Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/ValidationTest.java import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.RandomStringUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CategoryType; import com.amazonaws.services.codepipeline.model.Artifact; import hudson.model.Failure; } } @Test public void numberOfOutputsSuccess() { final List<Artifact> artifacts = new ArrayList<>(); for (int i = 0; i < Validation.MAX_ARTIFACTS; i++) { artifacts.add(new Artifact()); } Validation.numberOfOutPutsIsValid(artifacts); } @Test(expected=Exception.class) public void numberOfOutputsFailure() { final List<Artifact> artifacts = new ArrayList<>(); while (artifacts.size() <= Validation.MAX_ARTIFACTS) { artifacts.add(new Artifact()); } Validation.numberOfOutPutsIsValid(artifacts); } @Test public void validatePluginAllFieldsCorrectEmptyCredentialsSuccess() { Validation.validatePlugin( "", "", "us-east-1",
CategoryType.Build.getName(),
awslabs/aws-codepipeline-plugin-for-jenkins
src/main/java/com/amazonaws/codepipeline/jenkinsplugin/PublisherTools.java
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import hudson.model.BuildListener; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.EncryptionKey; import com.amazonaws.services.codepipeline.model.EncryptionKeyType; import com.amazonaws.services.codepipeline.model.ExecutionDetails; import com.amazonaws.services.codepipeline.model.FailureDetails; import com.amazonaws.services.codepipeline.model.FailureType; import com.amazonaws.services.codepipeline.model.PutJobFailureResultRequest; import com.amazonaws.services.codepipeline.model.PutJobSuccessResultRequest; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.CompleteMultipartUploadRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadResult; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PartETag; import com.amazonaws.services.s3.model.SSEAwsKeyManagementParams; import com.amazonaws.services.s3.model.UploadPartRequest;
if (buildSucceeded) { LoggingHelper.log(listener, "Build succeeded, calling PutJobSuccessResult"); final ExecutionDetails executionDetails = new ExecutionDetails(); executionDetails.setExternalExecutionId(actionID); executionDetails.setSummary("Finished"); final PutJobSuccessResultRequest request = new PutJobSuccessResultRequest(); request.setJobId(jobID); request.setExecutionDetails(executionDetails); codePipelineClient.putJobSuccessResult(request); } else { LoggingHelper.log(listener, "Build failed, calling PutJobFailureResult"); final FailureDetails executionDetails = new FailureDetails(); executionDetails.setExternalExecutionId(actionID); executionDetails.setMessage(errorMessage); executionDetails.setType(FailureType.JobFailed); final PutJobFailureResultRequest request = new PutJobFailureResultRequest(); request.setJobId(jobID); request.setFailureDetails(executionDetails); codePipelineClient.putJobFailureResult(request); } } public static void uploadFile( final File file, final Artifact artifact,
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/PublisherTools.java import hudson.model.BuildListener; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.EncryptionKey; import com.amazonaws.services.codepipeline.model.EncryptionKeyType; import com.amazonaws.services.codepipeline.model.ExecutionDetails; import com.amazonaws.services.codepipeline.model.FailureDetails; import com.amazonaws.services.codepipeline.model.FailureType; import com.amazonaws.services.codepipeline.model.PutJobFailureResultRequest; import com.amazonaws.services.codepipeline.model.PutJobSuccessResultRequest; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.CompleteMultipartUploadRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadResult; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PartETag; import com.amazonaws.services.s3.model.SSEAwsKeyManagementParams; import com.amazonaws.services.s3.model.UploadPartRequest; if (buildSucceeded) { LoggingHelper.log(listener, "Build succeeded, calling PutJobSuccessResult"); final ExecutionDetails executionDetails = new ExecutionDetails(); executionDetails.setExternalExecutionId(actionID); executionDetails.setSummary("Finished"); final PutJobSuccessResultRequest request = new PutJobSuccessResultRequest(); request.setJobId(jobID); request.setExecutionDetails(executionDetails); codePipelineClient.putJobSuccessResult(request); } else { LoggingHelper.log(listener, "Build failed, calling PutJobFailureResult"); final FailureDetails executionDetails = new FailureDetails(); executionDetails.setExternalExecutionId(actionID); executionDetails.setMessage(errorMessage); executionDetails.setType(FailureType.JobFailed); final PutJobFailureResultRequest request = new PutJobFailureResultRequest(); request.setJobId(jobID); request.setFailureDetails(executionDetails); codePipelineClient.putJobFailureResult(request); } } public static void uploadFile( final File file, final Artifact artifact,
final CompressionType compressionType,
awslabs/aws-codepipeline-plugin-for-jenkins
src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CompressionTools.java
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import hudson.model.BuildListener; import hudson.util.IOUtils; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType;
/* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.codepipeline.jenkinsplugin; public final class CompressionTools { private CompressionTools() {} // Compressing the file to upload to S3 should use the same type of compression as the customer // used for the input artifact. public static File compressFile( final String projectName, final Path pathToCompress,
// Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CompressionTools.java import hudson.model.BuildListener; import hudson.util.IOUtils; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; /* * Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.codepipeline.jenkinsplugin; public final class CompressionTools { private CompressionTools() {} // Compressing the file to upload to S3 should use the same type of compression as the customer // used for the input artifact. public static File compressFile( final String projectName, final Path pathToCompress,
final CompressionType compressionType,
awslabs/aws-codepipeline-plugin-for-jenkins
src/test/java/com/amazonaws/codepipeline/jenkinsplugin/DownloadCallableTest.java
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.AWSSessionCredentials; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.ArtifactLocation; import com.amazonaws.services.codepipeline.model.GetJobDetailsRequest; import com.amazonaws.services.codepipeline.model.GetJobDetailsResult; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData; import com.amazonaws.services.codepipeline.model.JobDetails; import com.amazonaws.services.codepipeline.model.S3ArtifactLocation; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectInputStream;
MockitoAnnotations.initMocks(this); TestUtils.initializeTestingFolders(); workspace = Paths.get(TestUtils.TEST_DIR).toFile(); outContent = TestUtils.setOutputStream(); inputArtifacts = new ArrayList<>(); inputArtifacts.add(inputArtifact); s3ArtifactLocation = new S3ArtifactLocation(); s3ArtifactLocation.setBucketName(S3_BUCKET_NAME); s3ArtifactLocation.setObjectKey(S3_OBJECT_KEY); s3ObjectInputStream = new S3ObjectInputStream( new FileInputStream(getClass().getClassLoader().getResource("aws-codedeploy-demo.zip").getFile()), null, false); when(clientFactory.getAwsClient(anyString(), anyString(), anyString(), anyInt(), anyString(), anyString())).thenReturn(awsClients); when(awsClients.getCodePipelineClient()).thenReturn(codePipelineClient); when(awsClients.getS3Client(any(AWSCredentialsProvider.class))).thenReturn(s3Client); when(s3Client.getObject(anyString(), anyString())).thenReturn(s3Object); when(s3Object.getKey()).thenReturn(S3_OBJECT_KEY); when(s3Object.getObjectContent()).thenReturn(s3ObjectInputStream); when(model.getAwsAccessKey()).thenReturn(ACCESS_KEY); when(model.getAwsSecretKey()).thenReturn(SECRET_KEY); when(model.getProxyHost()).thenReturn(PROXY_HOST); when(model.getProxyPort()).thenReturn(PROXY_PORT); when(model.getRegion()).thenReturn(REGION);
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/DownloadCallableTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.AWSSessionCredentials; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.ArtifactLocation; import com.amazonaws.services.codepipeline.model.GetJobDetailsRequest; import com.amazonaws.services.codepipeline.model.GetJobDetailsResult; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData; import com.amazonaws.services.codepipeline.model.JobDetails; import com.amazonaws.services.codepipeline.model.S3ArtifactLocation; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectInputStream; MockitoAnnotations.initMocks(this); TestUtils.initializeTestingFolders(); workspace = Paths.get(TestUtils.TEST_DIR).toFile(); outContent = TestUtils.setOutputStream(); inputArtifacts = new ArrayList<>(); inputArtifacts.add(inputArtifact); s3ArtifactLocation = new S3ArtifactLocation(); s3ArtifactLocation.setBucketName(S3_BUCKET_NAME); s3ArtifactLocation.setObjectKey(S3_OBJECT_KEY); s3ObjectInputStream = new S3ObjectInputStream( new FileInputStream(getClass().getClassLoader().getResource("aws-codedeploy-demo.zip").getFile()), null, false); when(clientFactory.getAwsClient(anyString(), anyString(), anyString(), anyInt(), anyString(), anyString())).thenReturn(awsClients); when(awsClients.getCodePipelineClient()).thenReturn(codePipelineClient); when(awsClients.getS3Client(any(AWSCredentialsProvider.class))).thenReturn(s3Client); when(s3Client.getObject(anyString(), anyString())).thenReturn(s3Object); when(s3Object.getKey()).thenReturn(S3_OBJECT_KEY); when(s3Object.getObjectContent()).thenReturn(s3ObjectInputStream); when(model.getAwsAccessKey()).thenReturn(ACCESS_KEY); when(model.getAwsSecretKey()).thenReturn(SECRET_KEY); when(model.getProxyHost()).thenReturn(PROXY_HOST); when(model.getProxyPort()).thenReturn(PROXY_PORT); when(model.getRegion()).thenReturn(REGION);
when(model.getCompressionType()).thenReturn(CompressionType.Zip);
awslabs/aws-codepipeline-plugin-for-jenkins
src/test/java/com/amazonaws/codepipeline/jenkinsplugin/DownloadCallableTest.java
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.AWSSessionCredentials; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.ArtifactLocation; import com.amazonaws.services.codepipeline.model.GetJobDetailsRequest; import com.amazonaws.services.codepipeline.model.GetJobDetailsResult; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData; import com.amazonaws.services.codepipeline.model.JobDetails; import com.amazonaws.services.codepipeline.model.S3ArtifactLocation; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectInputStream;
// then final InOrder inOrder = inOrder(clientFactory, awsClients, s3Client, model); inOrder.verify(clientFactory).getAwsClient(ACCESS_KEY, SECRET_KEY, PROXY_HOST, PROXY_PORT, REGION, PLUGIN_VERSION); inOrder.verify(awsClients).getCodePipelineClient(); inOrder.verify(awsClients).getS3Client(credentialsProviderCaptor.capture()); inOrder.verify(s3Client).getObject(S3_BUCKET_NAME, S3_OBJECT_KEY); inOrder.verify(model).setCompressionType(CompressionType.Zip); final com.amazonaws.auth.AWSSessionCredentials credentials = (com.amazonaws.auth.AWSSessionCredentials) credentialsProviderCaptor.getValue().getCredentials(); assertEquals(JOB_ACCESS_KEY, credentials.getAWSAccessKeyId()); assertEquals(JOB_SECRET_KEY, credentials.getAWSSecretKey()); assertEquals(JOB_SESSION_TOKEN, credentials.getSessionToken()); verify(codePipelineClient).getJobDetails(getJobDetailsRequestCaptor.capture()); assertEquals(JOB_ID, getJobDetailsRequestCaptor.getValue().getJobId()); } @Test public void clearsWorkspace() throws InterruptedException { // given downloader = new DownloadCallable(true, job, model, clientFactory, PLUGIN_VERSION, null); // when downloader.invoke(workspace, null); // then assertFalse(doesWorkspaceFileExist("Dir1")); assertFalse(doesWorkspaceFileExist("bbb.txt"));
// Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/TestUtils.java // public static void assertContainsIgnoreCase(final String strToMatch, final String strToCheck) { // final String strToMatchLower = strToMatch.toLowerCase(); // final String strToCheckLower = strToCheck.toLowerCase(); // assertTrue(strToCheckLower.contains(strToMatchLower)); // } // // Path: src/main/java/com/amazonaws/codepipeline/jenkinsplugin/CodePipelineStateModel.java // public enum CompressionType { // None, // Zip, // Tar, // TarGz // } // Path: src/test/java/com/amazonaws/codepipeline/jenkinsplugin/DownloadCallableTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static com.amazonaws.codepipeline.jenkinsplugin.TestUtils.assertContainsIgnoreCase; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.codepipeline.jenkinsplugin.CodePipelineStateModel.CompressionType; import com.amazonaws.services.codepipeline.AWSCodePipeline; import com.amazonaws.services.codepipeline.model.AWSSessionCredentials; import com.amazonaws.services.codepipeline.model.Artifact; import com.amazonaws.services.codepipeline.model.ArtifactLocation; import com.amazonaws.services.codepipeline.model.GetJobDetailsRequest; import com.amazonaws.services.codepipeline.model.GetJobDetailsResult; import com.amazonaws.services.codepipeline.model.Job; import com.amazonaws.services.codepipeline.model.JobData; import com.amazonaws.services.codepipeline.model.JobDetails; import com.amazonaws.services.codepipeline.model.S3ArtifactLocation; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectInputStream; // then final InOrder inOrder = inOrder(clientFactory, awsClients, s3Client, model); inOrder.verify(clientFactory).getAwsClient(ACCESS_KEY, SECRET_KEY, PROXY_HOST, PROXY_PORT, REGION, PLUGIN_VERSION); inOrder.verify(awsClients).getCodePipelineClient(); inOrder.verify(awsClients).getS3Client(credentialsProviderCaptor.capture()); inOrder.verify(s3Client).getObject(S3_BUCKET_NAME, S3_OBJECT_KEY); inOrder.verify(model).setCompressionType(CompressionType.Zip); final com.amazonaws.auth.AWSSessionCredentials credentials = (com.amazonaws.auth.AWSSessionCredentials) credentialsProviderCaptor.getValue().getCredentials(); assertEquals(JOB_ACCESS_KEY, credentials.getAWSAccessKeyId()); assertEquals(JOB_SECRET_KEY, credentials.getAWSSecretKey()); assertEquals(JOB_SESSION_TOKEN, credentials.getSessionToken()); verify(codePipelineClient).getJobDetails(getJobDetailsRequestCaptor.capture()); assertEquals(JOB_ID, getJobDetailsRequestCaptor.getValue().getJobId()); } @Test public void clearsWorkspace() throws InterruptedException { // given downloader = new DownloadCallable(true, job, model, clientFactory, PLUGIN_VERSION, null); // when downloader.invoke(workspace, null); // then assertFalse(doesWorkspaceFileExist("Dir1")); assertFalse(doesWorkspaceFileExist("bbb.txt"));
assertContainsIgnoreCase("[AWS CodePipeline Plugin] Clearing workspace", outContent.toString());