answer
stringlengths
17
10.2M
package com.akiban.sql.server; import com.akiban.ais.model.AkibanInformationSchema; import com.akiban.qp.operator.StoreAdapter; import com.akiban.server.error.AkibanInternalException; import com.akiban.server.error.NoTransactionInProgressException; import com.akiban.server.error.TransactionInProgressException; import com.akiban.server.expression.EnvironmentExpressionSetting; import com.akiban.server.service.dxl.DXLService; import com.akiban.server.service.functions.FunctionsRegistry; import com.akiban.server.service.instrumentation.SessionTracer; import com.akiban.server.service.session.Session; import com.akiban.server.service.tree.TreeService; import com.akiban.sql.parser.SQLParser; import com.akiban.sql.optimizer.rule.IndexEstimator; import com.akiban.ais.model.Index; import com.akiban.server.store.statistics.IndexStatistics; import com.akiban.server.store.statistics.IndexStatisticsService; import org.joda.time.DateTime; import java.util.*; public abstract class ServerSessionBase implements ServerSession { protected final ServerServiceRequirements reqs; protected Properties properties; protected Map<String,Object> attributes = new HashMap<String,Object>(); protected Session session; protected long aisTimestamp = -1; protected AkibanInformationSchema ais; protected StoreAdapter adapter; protected String defaultSchemaName; protected SQLParser parser; protected ServerTransaction transaction; protected boolean transactionDefaultReadOnly = false; protected ServerSessionTracer sessionTracer; public ServerSessionBase(ServerServiceRequirements reqs) { this.reqs = reqs; } @Override public Properties getProperties() { return properties; } @Override public String getProperty(String key) { return properties.getProperty(key); } @Override public String getProperty(String key, String defval) { return properties.getProperty(key, defval); } @Override public void setProperty(String key, String value) { properties.setProperty(key, value); sessionChanged(); } @Override public Map<String,Object> getAttributes() { return attributes; } @Override public Object getAttribute(String key) { return attributes.get(key); } @Override public void setAttribute(String key, Object attr) { attributes.put(key, attr); sessionChanged(); } protected abstract void sessionChanged(); @Override public DXLService getDXL() { return reqs.dxl(); } @Override public Session getSession() { return session; } @Override public String getDefaultSchemaName() { return defaultSchemaName; } @Override public void setDefaultSchemaName(String defaultSchemaName) { this.defaultSchemaName = defaultSchemaName; sessionChanged(); } @Override public AkibanInformationSchema getAIS() { return ais; } @Override public SQLParser getParser() { return parser; } @Override public SessionTracer getSessionTracer() { return sessionTracer; } @Override public StoreAdapter getStore() { return adapter; } @Override public TreeService getTreeService() { return reqs.treeService(); } @Override public void beginTransaction() { if (transaction != null) throw new TransactionInProgressException(); transaction = new ServerTransaction(this, transactionDefaultReadOnly); } @Override public void commitTransaction() { if (transaction == null) throw new NoTransactionInProgressException(); try { transaction.commit(); } finally { transaction = null; } } @Override public void rollbackTransaction() { if (transaction == null) throw new NoTransactionInProgressException(); try { transaction.rollback(); } finally { transaction = null; } } @Override public void setTransactionReadOnly(boolean readOnly) { if (transaction == null) throw new NoTransactionInProgressException(); transaction.setReadOnly(readOnly); } @Override public void setTransactionDefaultReadOnly(boolean readOnly) { this.transactionDefaultReadOnly = readOnly; } @Override public FunctionsRegistry functionsRegistry() { return reqs.functionsRegistry(); } @Override public Date currentTime() { return new Date(); } @Override public Object getEnvironmentValue(EnvironmentExpressionSetting setting) { switch (setting) { case CURRENT_DATETIME: return new DateTime((transaction != null) ? transaction.getTime(this) : currentTime()); case CURRENT_USER: return defaultSchemaName; case SESSION_USER: return properties.getProperty("user"); case SYSTEM_USER: return System.getProperty("user.name"); default: throw new AkibanInternalException("Unknown environment value: " + setting); } } // TODO: Maybe move this someplace else. Right now this is where things meet. public static class ServiceIndexEstimator extends IndexEstimator { private IndexStatisticsService indexStatistics; private Session session; public ServiceIndexEstimator(IndexStatisticsService indexStatistics, Session session) { this.indexStatistics = indexStatistics; this.session = session; } @Override public IndexStatistics getIndexStatistics(Index index) { return indexStatistics.getIndexStatistics(session, index); } } @Override public IndexEstimator indexEstimator() { return new ServiceIndexEstimator(reqs.indexStatistics(), session); } }
package com.batix.rundeck.core; import java.util.HashMap; import java.util.Map; public class AnsibleInventory { public class AnsibleInventoryHosts { protected Map<String, Map<String, String>> hosts = new HashMap<String, Map<String, String>>(); protected Map<String, AnsibleInventoryHosts> children = new HashMap<String, AnsibleInventoryHosts>(); public AnsibleInventoryHosts addHost(String nodeName) { hosts.put(nodeName, new HashMap<String, String>()); return this; } public AnsibleInventoryHosts addHost(String nodeName, String host, Map<String, String> attributes) { attributes.put("ansible_host", host); hosts.put(nodeName, attributes); return this; } public AnsibleInventoryHosts getOrAddChildHostGroup(String groupName) { children.putIfAbsent(groupName, new AnsibleInventoryHosts()); return children.get(groupName); } } protected AnsibleInventoryHosts all = new AnsibleInventoryHosts(); public AnsibleInventory addHost(String nodeName, String host, Map<String, String> attributes) { // Remove attributes that are reserved in Ansible String[] reserved = { "hostvars", "group_names", "groups", "environment" }; for (String r: reserved){ attributes.remove(r); } all.addHost(nodeName, host, attributes); // Create Ansible groups by attribute // Group by osFamily is needed for windows hosts setup String[] attributeGroups = { "osFamily", "tags" }; for (String g: attributeGroups) { if (attributes.containsKey(g)) { String[] groupNames = attributes.get(g).toLowerCase().split(","); for (String groupName: groupNames) { all.getOrAddChildHostGroup(groupName.trim()).addHost(nodeName); } } } return this; } }
package com.casad.weatherwatcher; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amphibian.weather.request.Feature; import com.amphibian.weather.request.WeatherRequest; import com.amphibian.weather.response.WeatherResponse; import com.casad.weatherwatcher.controller.RampController; import com.lodenrogue.JMaker.JMaker; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; public class WeatherWatcher { private static final Logger logger = LoggerFactory.getLogger(WeatherWatcher.class); protected static GpioController gpio = null; protected static GpioPinDigitalOutput readyPin = null; protected static GpioPinDigitalOutput activePin = null; protected static GpioPinDigitalOutput relay3 = null; protected static GpioPinDigitalOutput onlinePin = null; protected static JMaker ifttt = null; private static final long HOURS_TO_MILLISECONDS = 3_600_000; public static void main(String[] args) throws Exception { // preflight checks logger.info("Waking up!"); // Get configuration settings final Configuration config = Configuration.getConfig(); final String jMakerIFTTTKey = config.getIFTTTApiKey(); assertSet("A JMaker API key must be specified. See README.md for more information.", jMakerIFTTTKey); ifttt = new JMaker("GarageStatusUpdate", jMakerIFTTTKey); gpio = GpioFactory.getInstance(); readyPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "Relay 1", PinState.HIGH); activePin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_02, "Relay 2", PinState.HIGH); onlinePin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04, "Relay 4", PinState.HIGH); onlinePin.pulse(500); // These are unused, configure as OFF to prevent unexpected conditions. relay3 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_03, "Relay 3", PinState.HIGH); relay3.high(); // Diagnostic startup readyPin.high(); activePin.high(); Thread.sleep(1000); readyPin.low(); Thread.sleep(1000); activePin.low(); Thread.sleep(1000); readyPin.high(); activePin.high(); Thread.sleep(1000); Runnable makeIdle = () -> { // Make IDLE / OFF readyPin.high(); activePin.high(); }; Runnable makeReady = () -> { // Make READY readyPin.low(); activePin.high(); }; Runnable makeActive = () -> { // Make ACTIVE readyPin.low(); activePin.low(); }; // Create RampController instance with pin details RampController controller = new RampController(makeIdle, makeReady, makeActive); final String weatherAPIKey = config.getWundergroundApiKey(); assertSet("A weather API key must be specified. See README.md for more information.", weatherAPIKey); final String zipCode = config.getZipCode(); assertSet("A weather zip key must be specified. See README.md for more information.", zipCode); // Prepare the weather event engine WeatherEventEngine eng = new WeatherEventEngine(); eng.setPeriodLength(60, TimeUnit.MINUTES); eng.setDeactivationDelay(24 * HOURS_TO_MILLISECONDS); eng.setRampController(controller); eng.setWeatherService(new WeatherService() { @Override public WeatherResponse getWeatherReport() { WeatherRequest req = new WeatherRequest(); req.setApiKey(weatherAPIKey); req.addFeature(Feature.CONDITIONS); req.addFeature(Feature.FORECAST); return req.query(zipCode); } }); eng.setNotificationService(new NotificationService() { @Override public void sendMessage(String message) { triggerIftt(message); } }); eng.start(); onlinePin.high(); while(true) { Thread.sleep(3600000); } } private static void triggerIftt(String message) { if (ifttt == null) { logger.info(message); return; } logger.info("Notifying: " + message); List<String> values = new ArrayList<String>(); values.add(message); values.add(""); values.add(""); try { ifttt.trigger(values); } catch (IOException e) { logger.error("There was a problem connecting to the IFTT maker channel"); e.printStackTrace(); } } private static void assertSet(String message, String value) { if (value == null || "".equals(value)) { logger.error(message); System.exit(0); } } }
package com.clxcommunications.xms; import java.io.Closeable; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.nio.CharBuffer; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.concurrent.FutureCallback; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.apache.http.nio.IOControl; import org.apache.http.nio.client.methods.AsyncCharConsumer; import org.apache.http.nio.protocol.BasicAsyncRequestProducer; import org.apache.http.nio.protocol.HttpAsyncRequestProducer; import org.apache.http.nio.protocol.HttpAsyncResponseConsumer; import org.apache.http.protocol.HttpContext; import org.immutables.value.Value; import org.immutables.value.Value.Style.ImplementationVisibility; import com.clxcommunications.xms.api.ApiError; import com.clxcommunications.xms.api.BatchId; import com.clxcommunications.xms.api.MtBatchBinarySmsCreate; import com.clxcommunications.xms.api.MtBatchBinarySmsResult; import com.clxcommunications.xms.api.MtBatchBinarySmsUpdate; import com.clxcommunications.xms.api.MtBatchSmsResult; import com.clxcommunications.xms.api.MtBatchTextSmsCreate; import com.clxcommunications.xms.api.MtBatchTextSmsResult; import com.clxcommunications.xms.api.MtBatchTextSmsUpdate; import com.clxcommunications.xms.api.Page; import com.clxcommunications.xms.api.PagedBatchResult; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; @Value.Immutable(copy = false) @Value.Style(depluralize = true, jdkOnly = true, from = "using", build = "start", visibility = ImplementationVisibility.PACKAGE) public abstract class ApiConnection implements Closeable { public static class Builder extends ImmutableApiConnection.Builder { public Builder endpointHost(String hostname, int port, String scheme) { this.endpointHost(new HttpHost(hostname, port, scheme)); return this; } @Override public ImmutableApiConnection start() { ImmutableApiConnection conn = super.start(); conn.httpClient().start(); return conn; } } private abstract class JsonApiAsyncConsumer<T> extends AsyncCharConsumer<T> { private HttpResponse response; private StringBuilder sb; @Override protected void onCharReceived(CharBuffer buf, IOControl ioctrl) throws IOException { sb.append(buf.toString()); } @Override protected void onResponseReceived(HttpResponse response) throws HttpException, IOException { this.response = response; this.sb = new StringBuilder(); } @Nonnull protected abstract T buildSuccessResult(String str, HttpContext context) throws JsonParseException, JsonMappingException, IOException; @Override protected T buildResult(HttpContext context) throws Exception { int code = response.getStatusLine().getStatusCode(); switch (code) { case HttpStatus.SC_OK: case HttpStatus.SC_CREATED: return buildSuccessResult(sb.toString(), context); case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_FORBIDDEN: ApiError error = json.readValue(sb.toString(), ApiError.class); throw new ApiException(error); default: // TODO: Good idea to buffer the response in this case? ContentType contentType = ContentType.getLenient(response.getEntity()); response.setEntity( new StringEntity(sb.toString(), contentType)); throw new UnexpectedResponseException(response); } } } private final class BatchSmsResultAsyncConsumer extends JsonApiAsyncConsumer<MtBatchSmsResult> { @Override protected MtBatchSmsResult buildSuccessResult(String str, HttpContext context) throws JsonParseException, JsonMappingException, IOException { return json.readValue(str, MtBatchSmsResult.class); } } private final class BatchTextSmsResultAsyncConsumer extends JsonApiAsyncConsumer<MtBatchTextSmsResult> { @Override protected MtBatchTextSmsResult buildSuccessResult(String str, HttpContext context) throws JsonParseException, JsonMappingException, IOException { return json.readValue(str, MtBatchTextSmsResult.class); } } private final class BatchBinarySmsResultAsyncConsumer extends JsonApiAsyncConsumer<MtBatchBinarySmsResult> { @Override protected MtBatchBinarySmsResult buildSuccessResult(String str, HttpContext context) throws JsonParseException, JsonMappingException, IOException { return json.readValue(str, MtBatchBinarySmsResult.class); } } private final class PagedResultAsyncConsumer<P extends Page<T>, T> extends JsonApiAsyncConsumer<Page<T>> { final private Class<P> clazz; private PagedResultAsyncConsumer(Class<P> clazz) { this.clazz = clazz; } @Override protected Page<T> buildSuccessResult(String str, HttpContext context) throws JsonParseException, JsonMappingException, IOException { return json.readValue(str, clazz); } } /** * A Jackson object mapper. */ private final ApiObjectMapper json; /** * Package visibility because one implementation should be enough. */ ApiConnection() { json = new ApiObjectMapper(); } @Nonnull public static Builder builder() { return new Builder(); } @Override public void close() throws IOException { httpClient().close(); } /** * Authorization token. * * @return a non-null string */ public abstract String token(); /** * Service username. * * @return a non-null string */ public abstract String username(); /** * Whether the JSON sent to the server should be printed with indentation. * Default is to <i>not</i> pretty print. * * @return true if pretty printing is enabled; false otherwise */ @Value.Default public boolean prettyPrintJson() { return false; } /** * The HTTP client used by this connection. The default client is a minimal * one that does not support, for example, authentication or redirects. * Note, this HTTP client is closed when this API connection is closed. * * @return a non-null HTTP client */ @Value.Default public CloseableHttpAsyncClient httpClient() { return HttpAsyncClients.createMinimal(); } /** * The future callback wrapper to use in all API calls. By default this is * {@link CallbackWrapper.ExceptionDropper}, that is, any exception thrown * in a given callback is logged and dropped. * * @return a non-null callback wrapper */ @Value.Default public CallbackWrapper callbackWrapper() { return CallbackWrapper.exceptionDropper; } public abstract HttpHost endpointHost(); /** * The endpoint base path. The default value is * <code>/xms/v1/{username}</code>. * * @return the endpoint base path */ @Value.Default public String endpointBasePath() { try { return "/xms/v1/" + URLEncoder.encode(username(), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } @Value.Check protected void check() { if (!endpointBasePath().startsWith("/")) { throw new IllegalStateException( "endpoint base path does not start with '/'"); } if (endpointBasePath().contains("?")) { throw new IllegalStateException("endpoint base path contains '?'"); } /* * Attempt to create a plain endpoint URL. If it fails then something is * very wrong with the host or the endpoint base path. If it succeeds * then all endpoints generated in normal use of this class should * succeed since we validate the user input. * * Note, this does not mean that the generated URL makes sense, it only * means that the code will not throw exceptions. For example, if the * user sets the endpoint base path, "/hello?world" then all bets are * off. */ endpoint("", null); } /** * Helper returning an endpoint URL for the given sub-path and query. * * @param subPath * path fragment to place after the base path * @param query * the query string, may be null * @return a non-null endpoint URL */ @Nonnull private URI endpoint(@Nonnull String subPath, @Nullable String query) { StringBuilder sb = new StringBuilder(); sb.append(endpointHost().toURI()); sb.append(endpointBasePath()); sb.append(subPath); if (query != null) { sb.append('?').append(query); } return URI.create(sb.toString()); } private URI endpoint(String subPath) { return endpoint(subPath, null); } @Nonnull private URI batchesEndpoint() { return endpoint("/batches", null); } @Nonnull private URI batchEndpoint(BatchId batchId) { return endpoint("/batches/" + batchId.id()); } @Nonnull private URI batchDeliveryReportEndpoint(BatchId batchId, String type) { return endpoint( "/batches/" + batchId.id() + "/delivery_report", "type=" + type); } @Nonnull private URI batchDryRunEndpoint() { return endpoint("/batches/dry_run"); } @Nonnull private URI batchRecipientDeliveryReportEndpoint(BatchId batchId, String recipient) { return endpoint( "/batches/" + batchId.id() + "/delivery_report/" + recipient); } /** * Posts a JSON serialization of the given object to the given endpoint. * * @param endpoint * the target endpoint * @param object * the object whose JSON representation is sent * @return a HTTP post request. */ private <T> HttpPost post(URI endpoint, T object) { final byte[] content; /* * Attempt to serialize the given object into JSON. Note, we swallow the * JsonProcessingException since we control which objects will be * serialized and can guarantee that they all should be serializable. * Thus, if the exception still is thrown it indicates a severe bug in * internal state management. */ try { content = json.writeValueAsBytes(object); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } ByteArrayEntity entity = new ByteArrayEntity(content, ContentType.APPLICATION_JSON); HttpPost req = new HttpPost(endpoint); req.setHeader("Authorization", "Bearer " + token()); req.setHeader("Accept", ContentType.APPLICATION_JSON.toString()); req.setEntity(entity); return req; } private HttpGet get(URI endpoint) { HttpGet req = new HttpGet(endpoint); req.setHeader("Authorization", "Bearer " + token()); req.setHeader("Accept", ContentType.APPLICATION_JSON.toString()); return req; } private HttpDelete delete(URI endpoint) { HttpDelete req = new HttpDelete(endpoint); req.setHeader("Authorization", "Bearer " + token()); req.setHeader("Accept", ContentType.APPLICATION_JSON.toString()); return req; } /** * Unwrap exceptions for synchronous send methods. This helper will examine * an {@link ExecutionException} object and unwrap and throw it's cause if * it makes sense for a synchronous call. * * @param e * the exception to examine * @return returns <code>e</code> * @throws ApiException * @throws UnexpectedResponseException * @throws JsonProcessingException * @throws ExecutionException */ private ExecutionException maybeUnwrapExecutionException( ExecutionException e) throws ApiException, UnexpectedResponseException, JsonProcessingException, ExecutionException { if (e.getCause() instanceof ApiException) { throw (ApiException) e.getCause(); } else if (e.getCause() instanceof UnexpectedResponseException) { throw (UnexpectedResponseException) e.getCause(); } else if (e.getCause() instanceof JsonProcessingException) { throw (JsonProcessingException) e.getCause(); } return e; } /** * Attempts to send the given batch synchronously. Internally this uses an * asynchronous call and blocks until it completes. * * @param sms * the batch to send * @return a batch submission result * @throws InterruptedException * if the current thread was interrupted while waiting * @throws ExecutionException * if the send threw an unknown exception * @throws ApiException * if the server response indicated an error * @throws UnexpectedResponseException * if the server gave an unexpected response * @throws JsonProcessingException * if JSON deserialization failed */ public MtBatchTextSmsResult sendBatch(MtBatchTextSmsCreate sms) throws InterruptedException, ExecutionException, ApiException, JsonProcessingException, UnexpectedResponseException { try { return sendBatchAsync(sms, null).get(); } catch (ExecutionException e) { throw maybeUnwrapExecutionException(e); } } /** * Attempts to send the given batch synchronously. Internally this uses an * asynchronous call and blocks until it completes. * * @param sms * the batch to send * @return a batch submission result * @throws InterruptedException * if the current thread was interrupted while waiting * @throws ExecutionException * if the send threw an unknown exception * @throws ApiException * if the server response indicated an error * @throws UnexpectedResponseException * if the server gave an unexpected response * @throws JsonProcessingException * if JSON deserialization failed */ public MtBatchBinarySmsResult sendBatch(MtBatchBinarySmsCreate sms) throws InterruptedException, ExecutionException, ApiException, JsonProcessingException, UnexpectedResponseException { try { return sendBatchAsync(sms, null).get(); } catch (ExecutionException e) { throw maybeUnwrapExecutionException(e); } } public Future<MtBatchTextSmsResult> sendBatchAsync(MtBatchTextSmsCreate sms, FutureCallback<MtBatchTextSmsResult> callback) { HttpPost httpPost = post(batchesEndpoint(), sms); HttpAsyncRequestProducer requestProducer = new BasicAsyncRequestProducer(endpointHost(), httpPost); HttpAsyncResponseConsumer<MtBatchTextSmsResult> responseConsumer = new BatchTextSmsResultAsyncConsumer(); return httpClient().execute(requestProducer, responseConsumer, callbackWrapper().wrap(callback)); } public Future<MtBatchBinarySmsResult> sendBatchAsync( MtBatchBinarySmsCreate sms, FutureCallback<MtBatchBinarySmsResult> callback) { HttpPost httpPost = post(batchesEndpoint(), sms); HttpAsyncRequestProducer requestProducer = new BasicAsyncRequestProducer(endpointHost(), httpPost); HttpAsyncResponseConsumer<MtBatchBinarySmsResult> responseConsumer = new BatchBinarySmsResultAsyncConsumer(); return httpClient().execute(requestProducer, responseConsumer, callbackWrapper().wrap(callback)); } /** * Asynchronously updates the text batch with the given batch ID. The batch * is updated to match the given update object. * * @param batchId * the batch that should be updated * @param sms * description of the desired update * @param callback * called at call success, failure, or cancellation * @return a future containing the updated batch */ public Future<MtBatchTextSmsResult> updateBatchAsync(BatchId batchId, MtBatchTextSmsUpdate sms, FutureCallback<MtBatchTextSmsResult> callback) { HttpPost httpPost = post(batchEndpoint(batchId), sms); HttpAsyncRequestProducer producer = new BasicAsyncRequestProducer(endpointHost(), httpPost); HttpAsyncResponseConsumer<MtBatchTextSmsResult> consumer = new BatchTextSmsResultAsyncConsumer(); return httpClient().execute(producer, consumer, callbackWrapper().wrap(callback)); } /** * Asynchronously updates the binary batch with the given batch ID. The * batch is updated to match the given update object. * * @param batchId * the batch that should be updated * @param sms * description of the desired update * @param callback * called at call success, failure, or cancellation * @return a future containing the updated batch */ public Future<MtBatchBinarySmsResult> updateBatchAsync(BatchId batchId, MtBatchBinarySmsUpdate sms, FutureCallback<MtBatchBinarySmsResult> callback) { HttpPost httpPost = post(batchEndpoint(batchId), sms); HttpAsyncRequestProducer producer = new BasicAsyncRequestProducer(endpointHost(), httpPost); HttpAsyncResponseConsumer<MtBatchBinarySmsResult> consumer = new BatchBinarySmsResultAsyncConsumer(); return httpClient().execute(producer, consumer, callbackWrapper().wrap(callback)); } /** * Fetches a batch with the given batch ID. * * @param batchId * ID of the batch to fetch * @param callback * a callback that is activated at call completion * @return a future yielding the updated status of the batch */ public Future<MtBatchSmsResult> fetchBatch(BatchId batchId, FutureCallback<MtBatchSmsResult> callback) { HttpGet req = get(batchEndpoint(batchId)); HttpAsyncRequestProducer producer = new BasicAsyncRequestProducer(endpointHost(), req); HttpAsyncResponseConsumer<MtBatchSmsResult> consumer = new BatchSmsResultAsyncConsumer(); return httpClient().execute(producer, consumer, callbackWrapper().wrap(callback)); } public PagedFetcher<MtBatchSmsResult> fetchBatches(final BatchFilter filter, final FutureCallback<Page<MtBatchSmsResult>> callback) { return new PagedFetcher<MtBatchSmsResult>() { @Override Future<Page<MtBatchSmsResult>> fetchAsync(int page, FutureCallback<Page<MtBatchSmsResult>> callback) { return fetchBatches(page, filter, callbackWrapper().wrap(callback)); } }; } private Future<Page<MtBatchSmsResult>> fetchBatches(int page, BatchFilter filter, FutureCallback<Page<MtBatchSmsResult>> callback) { String query = filter.toUrlEncodedQuery(page); URI url = endpoint("/batches", query); HttpGet req = get(url); HttpAsyncRequestProducer producer = new BasicAsyncRequestProducer(endpointHost(), req); HttpAsyncResponseConsumer<Page<MtBatchSmsResult>> consumer = new PagedResultAsyncConsumer<PagedBatchResult, MtBatchSmsResult>( PagedBatchResult.class); return httpClient().execute(producer, consumer, callbackWrapper().wrap(callback)); } public Future<MtBatchTextSmsResult> cancelBatch(BatchId batchId) { return cancelBatch(batchId, null); } public Future<MtBatchTextSmsResult> cancelBatch(BatchId batchId, FutureCallback<MtBatchTextSmsResult> callback) { HttpDelete req = delete(batchEndpoint(batchId)); HttpAsyncRequestProducer producer = new BasicAsyncRequestProducer(endpointHost(), req); HttpAsyncResponseConsumer<MtBatchTextSmsResult> consumer = new BatchTextSmsResultAsyncConsumer(); return httpClient().execute(producer, consumer, callbackWrapper().wrap(callback)); } }
package ch.unizh.ini.jaer.projects.minliu; import java.util.Arrays; import java.util.Observable; import java.util.Observer; import com.jogamp.opengl.util.awt.TextRenderer; import ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlow; import com.jogamp.opengl.GL; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GLAutoDrawable; import java.awt.Dimension; import java.awt.Font; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.font.FontRenderContext; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeEvent; import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Level; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JPanel; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.ApsDvsEvent; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import net.sf.jaer.eventio.AEInputStream; import static net.sf.jaer.eventprocessing.EventFilter.log; import net.sf.jaer.eventprocessing.FilterChain; import net.sf.jaer.eventprocessing.TimeLimiter; import net.sf.jaer.eventprocessing.filter.Steadicam; import net.sf.jaer.graphics.AEViewer; import net.sf.jaer.graphics.FrameAnnotater; import net.sf.jaer.graphics.ImageDisplay; import net.sf.jaer.util.DrawGL; import net.sf.jaer.util.EngineeringFormat; import net.sf.jaer.util.filter.LowpassFilter; /** * Uses patch matching to measureTT local optical flow. <b>Not</b> gradient * based, but rather matches local features backwards in time. * * @author Tobi and Min, Jan 2016 */ @Description("Computes optical flow with vector direction using binary block matching") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class PatchMatchFlow extends AbstractMotionFlow implements Observer, FrameAnnotater { /* LDSP is Large Diamond Search Pattern, and SDSP mens Small Diamond Search Pattern. LDSP has 9 points and SDSP consists of 5 points. */ private static final int LDSP[][] = {{0, -2}, {-1, -1}, {1, -1}, {-2, 0}, {0, 0}, {2, 0}, {-1, 1}, {1, 1}, {0, 2}}; private static final int SDSP[][] = {{0, -1}, {-1, 0}, {0, 0}, {1, 0}, {0, 1}}; // private int[][][] histograms = null; private static final int NUM_SLICES = 3; // private int sx, sy; private int currentSliceIdx = 0; // private int tMinus2SliceIdx = 0, tMinus1SliceIdx = 1, currentSliceIdx = 2; // private int[][] currentSlice = null, tMinus1Slice = null, tMinus2Slice = null; // private int[][] currentSlice = null; // private ArrayList<Integer[]>[][] spikeTrains = null; // Spike trains for one block // private ArrayList<int[][]>[] histogramsAL = null; // private ArrayList<int[][]> currentAL = null, previousAL = null, previousMinus1AL = null; // One is for current, the second is for previous, the third is for the one before previous one // private BitSet[] histogramsBitSet = null; // private BitSet currentSli = null, tMinus1Sli = null, tMinus2Sli = null; private boolean[][][] bitmaps = null; private boolean[][] currentBitmap; private final SADResult tmpSadResult = new SADResult(0, 0, 0); // used to pass data back from min distance computation private SADResult lastGoodSadResult = new SADResult(0, 0, 0); // used for consistency check private int patchDimension = getInt("patchDimension", 9); // private int eventPatchDimension = getInt("eventPatchDimension", 3); // private int forwardEventNum = getInt("forwardEventNum", 10); private float cost = getFloat("cost", 0.001f); private float confidenceThreshold = getFloat("confidenceThreshold", .5f); private float validPixOccupancy = getFloat("validPixOccupancy", 0.01f); // threshold for valid pixel percent for one block private float weightDistance = getFloat("weightDistance", 0.95f); // confidence value consists of the distance and the dispersion, this value set the distance value // private int thresholdTime = getInt("thresholdTime", 1000000); // private int[][] lastFireIndex = null; // Events are numbered in time order for every block. This variable is for storing the last event index fired on all blocks. // private int[][] eventSeqStartTs = null; // private boolean preProcessEnable = false; private static final int MAX_SKIP_COUNT = 300; private int skipProcessingEventsCount = getInt("skipProcessingEventsCount", 0); // skip this many events for processing (but not for accumulating to bitmaps) private int skipCounter = 0; private boolean adaptiveEventSkipping = getBoolean("adaptiveEventSkipping", false); private float skipChangeFactor = (float) Math.sqrt(2); // by what factor to change the skip count if too slow or too fast private boolean outputSearchErrorInfo = false; // make user choose this slow down every time private boolean adapativeSliceDuration = getBoolean("adapativeSliceDuration", false); private boolean showSliceBitMap = getBoolean("showSliceBitMap", false); // Display the bitmaps private float adapativeSliceDurationProportionalErrorGain = 0.01f; // factor by which an error signal on match distance changes slice duration private int processingTimeLimitMs = getInt("processingTimeLimitMs", 100); // time limit for processing packet in ms to process OF events (events still accumulate). Overrides the system EventPacket timelimiter, which cannot be used here because we still need to accumulate and render the events. private TimeLimiter timeLimiter = new TimeLimiter(); // results histogram for each packet private int[][] resultHistogram = null; private int resultHistogramCount; private float avgMatchDistance = 0; // stores average match distance for rendering it private float histStdDev = 0, lastHistStdDev = 0; private float FSCnt = 0, DSCorrectCnt = 0; float DSAverageNum = 0, DSAveError[] = {0, 0}; // Evaluate DS cost average number and the error. // private float lastErrSign = Math.signum(1); // private final String outputFilename; private int sliceDeltaT; // The time difference between two slices used for velocity caluction. For constantDuration, this one is equal to the duration. For constantEventNumber, this value will change. private int MIN_SLICE_DURATION = 1000; private int MAX_SLICE_DURATION = 500000; public enum PatchCompareMethod { JaccardDistance, HammingDistance/*, SAD, EventSqeDistance*/ }; private PatchCompareMethod patchCompareMethod = PatchCompareMethod.valueOf(getString("patchCompareMethod", PatchCompareMethod.HammingDistance.toString())); public enum SearchMethod { FullSearch, DiamondSearch, CrossDiamondSearch }; private SearchMethod searchMethod = SearchMethod.valueOf(getString("searchMethod", SearchMethod.DiamondSearch.toString())); private int sliceDurationUs = getInt("sliceDurationUs", 20000); private int sliceEventCount = getInt("sliceEventCount", 10000); private boolean rewindFlg = false; // The flag to indicate the rewind event. private FilterChain filterChain; private Steadicam cameraMotion; // calibration private boolean calibrating = false; // used to flag calibration state private int calibrationSampleCount = 0; private int NUM_CALIBRATION_SAMPLES_DEFAULT = 800; // 400 samples /sec protected int numCalibrationSamples = getInt("numCalibrationSamples", NUM_CALIBRATION_SAMPLES_DEFAULT); TextRenderer imuTextRenderer = null; private boolean showGrid = getBoolean("showGrid", true); private boolean displayResultHistogram = getBoolean("displayResultHistogram", true); public enum SliceMethod { ConstantDuration, ConstantEventNumber, AdaptationDuration }; private SliceMethod sliceMethod = SliceMethod.valueOf(getString("sliceMethod", SliceMethod.ConstantDuration.toString())); private int eventCounter = 0; private int sliceLastTs = 0; ImageDisplay display; // makde a new ImageDisplay GLCanvas with default OpenGL capabilities private JFrame Frame = null; public PatchMatchFlow(AEChip chip) { super(chip); filterChain = new FilterChain(chip); cameraMotion = new Steadicam(chip); cameraMotion.setFilterEnabled(true); cameraMotion.setDisableRotation(true); cameraMotion.setDisableTranslation(true); // filterChain.add(cameraMotion); setEnclosedFilterChain(filterChain); setSliceDurationUs(getSliceDurationUs()); // 40ms is good for the start of the slice duration adatative since 4ms is too fast and 500ms is too slow. // // Save the result to the file // Format formatter = new SimpleDateFormat("YYYY-MM-dd_hh-mm-ss"); // // Instantiate a Date object // Date date = new Date(); // Log file for the OF distribution's statistics // outputFilename = "PMF_HistStdDev" + formatter.format(date) + ".txt"; String patchTT = "Block matching"; // String eventSqeMatching = "Event squence matching"; // String preProcess = "Denoise"; String metricConfid = "Confidence of current metric"; chip.addObserver(this); // to allocate memory once chip size is known // setPropertyTooltip(preProcess, "preProcessEnable", "enable this to denoise before data processing"); // setPropertyTooltip(preProcess, "forwardEventNum", "Number of events have fired on the current block since last processing"); setPropertyTooltip(metricConfid, "confidenceThreshold", "<html>Confidence threshold for rejecting unresonable value; Range from 0 to 1. <p>Higher value means it is harder to accept the event. <br>Set to 0 to accept all results."); setPropertyTooltip(metricConfid, "validPixOccupancy", "<html>Threshold for valid pixel percent for each block; Range from 0 to 1. <p>If either matching block is less occupied than this fraction, no motion vector will be calculated."); setPropertyTooltip(metricConfid, "weightDistance", "<html>The confidence value consists of the distance and the dispersion; <br>weightDistance sets the weighting of the distance value compared with the dispersion value; Range from 0 to 1. <p>To count only e.g. hamming distance, set weighting to 1. <p> To count only dispersion, set to 0."); setPropertyTooltip(patchTT, "patchDimension", "linear dimenion of patches to match, in pixels"); setPropertyTooltip(patchTT, "searchDistance", "search distance for matching patches, in pixels"); setPropertyTooltip(patchTT, "patchCompareMethod", "method to compare two patches"); setPropertyTooltip(patchTT, "searchMethod", "method to search patches"); setPropertyTooltip(patchTT, "sliceDurationUs", "duration of bitmaps in us, also called sample interval, when ConstantDuration method is used"); setPropertyTooltip(patchTT, "ppsScale", "scale of pixels per second to draw local motion vectors; global vectors are scaled up by an additional factor of " + GLOBAL_MOTION_DRAWING_SCALE); setPropertyTooltip(patchTT, "sliceEventCount", "number of events collected to fill a slice, when ConstantEventNumber method is used"); setPropertyTooltip(patchTT, "sliceMethod", "set method for determining time slice duration for block matching"); setPropertyTooltip(patchTT, "skipProcessingEventsCount", "skip this many events for processing (but not for accumulating to bitmaps)"); setPropertyTooltip(patchTT, "adaptiveEventSkipping", "enables adaptive event skipping depending on free time left in AEViewer animation loop"); setPropertyTooltip(patchTT, "adapativeSliceDuration", "<html>enables adaptive slice duration using feedback control, <br> based on average match search distance compared with total search distance. <p>If the match is too close short, increaes duration, and if too far, decreases duration"); setPropertyTooltip(patchTT, "processingTimeLimitMs", "<html>time limit for processing packet in ms to process OF events (events still accumulate). <br> Set to 0 to disable. <p>Alternative to the system EventPacket timelimiter, which cannot be used here because we still need to accumulate and render the events"); setPropertyTooltip(patchTT, "outputSearchErrorInfo", "enables displaying the search method error information"); setPropertyTooltip(patchTT, "showSliceBitMap", "enables displaying the slices' bitmap"); setPropertyTooltip(patchTT, "outlierMotionFilteringEnabled", "(Currently has no effect) discards first optical flow event that points in opposite direction as previous one (dot product is negative)"); // setPropertyTooltip(eventSqeMatching, "cost", "The cost to translation one event to the other position"); // setPropertyTooltip(eventSqeMatching, "thresholdTime", "The threshold value of interval time between the first event and the last event"); // setPropertyTooltip(eventSqeMatching, "sliceEventCount", "number of collected events in each bitmap"); // setPropertyTooltip(eventSqeMatching, "eventPatchDimension", "linear dimenion of patches to match, in pixels"); setPropertyTooltip(dispTT, "displayOutputVectors", "display the output motion vectors or not"); setPropertyTooltip(dispTT, "displayResultHistogram", "display the output motion vectors histogram to show disribution of results for each packet. Only implemented for HammingDistance"); getSupport().addPropertyChangeListener(AEViewer.EVENT_TIMESTAMPS_RESET, this); getSupport().addPropertyChangeListener(AEViewer.EVENT_FILEOPEN, this); getSupport().addPropertyChangeListener(AEInputStream.EVENT_REWIND, this); getSupport().addPropertyChangeListener(AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP, this); } @Override synchronized public EventPacket filterPacket(EventPacket in) { setupFilter(in); checkArrays(); adaptEventSkipping(); if (resultHistogram == null || resultHistogram.length != 2 * searchDistance + 1) { int dim = 2 * searchDistance + 1; // e.g. search distance 1, dim=3, 3x3 possibilties (including zero motion) resultHistogram = new int[dim][dim]; resultHistogramCount = 0; } else { if (adapativeSliceDuration && resultHistogramCount > 0) { // if (resultHistogramCount > 0) { // measure last hist to get control signal on slice duration float radiusSum = 0, countSum = 0; for (int x = -searchDistance; x <= searchDistance; x++) { for (int y = -searchDistance; y <= searchDistance; y++) { int count = resultHistogram[x + searchDistance][y + searchDistance]; if (count > 0) { final float radius = (float) Math.sqrt(x * x + y * y); countSum += count; radiusSum += radius * count; } } } avgMatchDistance = radiusSum / (countSum); double[] rstHist1D = new double[resultHistogram.length * resultHistogram.length]; int index = 0; int rstHistMax = 0; for (int[] resultHistogram1 : resultHistogram) { for (int n = 0; n < resultHistogram1.length; n++) { rstHist1D[index++] = resultHistogram1[n]; } } Statistics histStats = new Statistics(rstHist1D); // double histMax = Collections.max(Arrays.asList(ArrayUtils.toObject(rstHist1D))); double histMax = histStats.getMax(); for (int m = 0; m < rstHist1D.length; m++) { rstHist1D[m] = rstHist1D[m] / histMax; } lastHistStdDev = histStdDev; histStdDev = (float) histStats.getStdDev(); // try (FileWriter outFile = new FileWriter(outputFilename,true)) { // outFile.write(String.format(in.getFirstEvent().getTimestamp() + " " + histStdDev + "\r\n")); // outFile.close(); // } catch (IOException ex) { // Logger.getLogger(PatchMatchFlow.class.getName()).log(Level.SEVERE, null, ex); // } catch (Exception e) { // log.warning("Caught " + e + ". See following stack trace."); // e.printStackTrace(); float histMean = (float) histStats.getMean(); // compute error signal. // If err<0 it means the average match distance is larger than 1/2 search distance, so we need to reduce slice duration // If err>0, it means the avg match distance is too short, so increse time slice // TODO some bug in following final float err = (searchDistance / 2) - avgMatchDistance; final float lastErr = searchDistance / 2 - lastHistStdDev; // final double err = histMean - 1/ (rstHist1D.length * rstHist1D.length); float errSign = (float) Math.signum(err); // if(Math.abs(err) > Math.abs(lastErr)) { // errSign = -errSign; // if(histStdDev >= 0.14) { // if(lastHistStdDev > histStdDev) { // errSign = -lastErrSign; // } else { // errSign = lastErrSign; // errSign = 1; // } else { // errSign = (float) Math.signum(err); // lastErrSign = errSign; int durChange = (int) (errSign * adapativeSliceDurationProportionalErrorGain * sliceDurationUs); setSliceDurationUs(sliceDurationUs + durChange); } // clear histograms for each packet so that we accumulate OF distribution for this packet for (int[] h : resultHistogram) { Arrays.fill(h, 0); } } resultHistogramCount = 0; if (processingTimeLimitMs > 0) { timeLimiter.setTimeLimitMs(processingTimeLimitMs); timeLimiter.restart(); } else { timeLimiter.setEnabled(false); } // ApsDvsEventPacket in2 = (ApsDvsEventPacket) in; // Iterator itr = in2.fullIterator(); // Wfffsfe also need IMU data, so here we use the full iterator. for (Object o : in) { // to support pure DVS like DVS128 BasicEvent ein = (BasicEvent) o; if (ein == null) { log.warning("null event passed in, returning input packet"); return in; } if (!extractEventInfo(ein)) { continue; } if (measureAccuracy || discardOutliersForStatisticalMeasurementEnabled) { imuFlowEstimator.calculateImuFlow((ApsDvsEvent) inItr.next()); setGroundTruth(); } if (xyFilter()) { continue; } countIn++; // compute flow SADResult result = null; // int blockLocX = x / eventPatchDimension; // int blockLocY = y / eventPatchDimension; // Build the spike trains of every block, every block is consist of 3*3 pixels. // if (spikeTrains[blockLocX][blockLocY] == null) { // spikeTrains[blockLocX][blockLocY] = new ArrayList(); // int spikeBlokcLength = spikeTrains[blockLocX][blockLocY].size(); // int previousTsInterval = 0; // if (spikeBlokcLength == 0) { // previousTsInterval = ts; // } else { // previousTsInterval = ts - spikeTrains[blockLocX][blockLocY].get(spikeBlokcLength - 1)[0]; // if (preProcessEnable || patchCompareMethod == PatchCompareMethod.EventSqeDistance) { // spikeTrains[blockLocX][blockLocY].add(new Integer[]{ts, type}); int deltaTime = 0; if (sliceMethod == SliceMethod.ConstantDuration) { deltaTime = sliceDurationUs; } else if (sliceMethod == SliceMethod.ConstantEventNumber) { deltaTime = sliceDeltaT; } switch (patchCompareMethod) { case HammingDistance: maybeRotateSlices(); if (!accumulateEvent(in)) { // maybe skip events here break; } // result = minHammingDistance(x, y, tMinus2Sli, tMinus1Sli); result = minHammingDistance(x, y, bitmaps[sliceIndex(1)],bitmaps[sliceIndex(2)]); if (showSliceBitMap) { showBitmaps(x, y, (int) result.dx, (int) result.dy, bitmaps[sliceIndex(1)], bitmaps[sliceIndex(2)]); } result.dx = (result.dx / deltaTime) * 1000000; // hack, convert to pix/second result.dy = (result.dy / deltaTime) * 1000000; break; // case SAD: // maybeRotateSlices(); // if (!accumulateEvent(in)) { // break; //// if (preProcessEnable) { //// // There're enough events fire on the specific block now //// if ((spikeTrains[blockLocX][blockLocY].size() - lastFireIndex[blockLocX][blockLocY]) >= forwardEventNum) { //// lastFireIndex[blockLocX][blockLocY] = spikeTrains[blockLocX][blockLocY].size() - 1; //// result = minSad(x, y, tMinus2Sli, tMinus1Sli); //// result.dx = (result.dx / sliceDurationUs) * 1000000; //// result.dy = (result.dy / sliceDurationUs) * 1000000; //// } else { //// result = minSad(x, y, tMinus2Sli, tMinus1Sli); // result = minSad(x, y, tm2Bitmap, tm1Bitmap); // result.dx = (result.dx / sliceDurationUs) * 1000000; // result.dy = (result.dy / sliceDurationUs) * 1000000; // break; case JaccardDistance: maybeRotateSlices(); if (!accumulateEvent(in)) { break; } // if (preProcessEnable) { // // There're enough events fire on the specific block now // if ((spikeTrains[blockLocX][blockLocY].size() - lastFireIndex[blockLocX][blockLocY]) >= forwardEventNum) { // lastFireIndex[blockLocX][blockLocY] = spikeTrains[blockLocX][blockLocY].size() - 1; // result = minJaccardDistance(x, y, tMinus2Sli, tMinus1Sli); // result.dx = (result.dx / sliceDurationUs) * 1000000; // result.dy = (result.dy / sliceDurationUs) * 1000000; // } else { // result = minJaccardDistance(x, y, tMinus2Sli, tMinus1Sli); result = minJaccardDistance(x, y, bitmaps[sliceIndex(2)], bitmaps[sliceIndex(1)]); result.dx = (result.dx / deltaTime) * 1000000; result.dy = (result.dy / deltaTime) * 1000000; break; // case EventSqeDistance: // if (previousTsInterval < 0) { // spikeTrains[blockLocX][blockLocY].remove(spikeTrains[blockLocX][blockLocY].size() - 1); // continue; // if (previousTsInterval >= thresholdTime) { // float maxDt = 0; // float[][] dataPoint = new float[9][2]; // if ((blockLocX >= 1) && (blockLocY >= 1) && (blockLocX <= 238) && (blockLocY <= 178)) { // for (int ii = -1; ii < 2; ii++) { // for (int jj = -1; jj < 2; jj++) { // float dt = ts - eventSeqStartTs[blockLocX + ii][blockLocY + jj]; // // Remove the seq1 itself // if ((0 == ii) && (0 == jj)) { // // continue; // dt = 0; // dataPoint[((ii + 1) * 3) + (jj + 1)][0] = dt; // if (dt > maxDt) { // // result = minVicPurDistance(blockLocX, blockLocY); // eventSeqStartTs[blockLocX][blockLocY] = ts; // boolean allZeroFlg = true; // for (int mm = 0; mm < 9; mm++) { // for (int nn = 0; nn < 1; nn++) { // if (dataPoint[mm][nn] != 0) { // allZeroFlg = false; // if (allZeroFlg) { // continue; // KMeans cluster = new KMeans(); // cluster.setData(dataPoint); // int[] initialValue = new int[3]; // initialValue[0] = 0; // initialValue[1] = 4; // initialValue[2] = 8; // cluster.setInitialByUser(initialValue); // cluster.cluster(); // ArrayList<ArrayList<Integer>> kmeansResult = cluster.getResult(); // float[][] classData = cluster.getClassData(); // int firstClusterIdx = -1, secondClusterIdx = -1, thirdClusterIdx = -1; // for (int i = 0; i < 3; i++) { // if (kmeansResult.get(i).contains(0)) { // firstClusterIdx = i; // if (kmeansResult.get(i).contains(4)) { // secondClusterIdx = i; // if (kmeansResult.get(i).contains(8)) { // thirdClusterIdx = i; // if ((kmeansResult.get(firstClusterIdx).size() == 3) // && (kmeansResult.get(firstClusterIdx).size() == 3) // && (kmeansResult.get(firstClusterIdx).size() == 3) // && kmeansResult.get(firstClusterIdx).contains(1) // && kmeansResult.get(firstClusterIdx).contains(2)) { // result.dx = (-1 / (classData[secondClusterIdx][0] - classData[firstClusterIdx][0])) * 1000000 * 0.2f * eventPatchDimension;; // result.dy = 0; // if ((kmeansResult.get(firstClusterIdx).size() == 3) // && (kmeansResult.get(firstClusterIdx).size() == 3) // && (kmeansResult.get(firstClusterIdx).size() == 3) // && kmeansResult.get(thirdClusterIdx).contains(2) // && kmeansResult.get(thirdClusterIdx).contains(5)) { // result.dy = (-1 / (classData[thirdClusterIdx][0] - classData[secondClusterIdx][0])) * 1000000 * 0.2f * eventPatchDimension;; // result.dx = 0; // break; } if (result == null) { continue; // maybe some property change caused this } vx = result.dx; vy = result.dy; v = (float) Math.sqrt((vx * vx) + (vy * vy)); // reject values that are unreasonable if (isNotSufficientlyAccurate(result)) { continue; } // if (filterOutInconsistentEvent(result)) { // continue; if (resultHistogram != null) { resultHistogram[result.xidx][result.yidx]++; resultHistogramCount++; } processGoodEvent(); lastGoodSadResult.set(result); } if (rewindFlg) { rewindFlg = false; sliceLastTs = 0; // final int sx = chip.getSizeX(), sy = chip.getSizeY(); // for (int i = 0; i < sx; i++) { // for (int j = 0; j < sy; j++) { // if (spikeTrains != null && spikeTrains[i][j] != null) { // spikeTrains[i][j] = null; // if (lastFireIndex != null) { // lastFireIndex[i][j] = 0; // eventSeqStartTs[i][j] = 0; } motionFlowStatistics.updatePacket(countIn, countOut); return isDisplayRawInput() ? in : dirPacket; } private EngineeringFormat engFmt = new EngineeringFormat(); private TextRenderer textRenderer = null; @Override public void annotate(GLAutoDrawable drawable) { super.annotate(drawable); if (displayResultHistogram && resultHistogram != null) { GL2 gl = drawable.getGL().getGL2(); // draw histogram as shaded in 2d hist above color wheel // normalize hist int max = 0; for (int[] h : resultHistogram) { for (int v : h) { if (v > max) { max = v; } } } if (max == 0) { return; } final float maxRecip = 1f / max; int dim = resultHistogram.length; // 2*searchDistance+1 gl.glPushMatrix(); final float scale = 30 / (2 * searchDistance + 1); // size same as the color wheel gl.glTranslatef(-35, .65f * chip.getSizeY(), 0); // center above color wheel gl.glScalef(scale, scale, 1); gl.glColor3f(0, 0, 1); gl.glLineWidth(2f); gl.glBegin(GL.GL_LINE_LOOP); gl.glVertex2f(0, 0); gl.glVertex2f(dim, 0); gl.glVertex2f(dim, dim); gl.glVertex2f(0, dim); gl.glEnd(); for (int x = 0; x < dim; x++) { for (int y = 0; y < dim; y++) { float g = maxRecip * resultHistogram[x][y]; gl.glColor3f(g, g, g); gl.glBegin(GL2.GL_QUADS); gl.glVertex2f(x, y); gl.glVertex2f(x + 1, y); gl.glVertex2f(x + 1, y + 1); gl.glVertex2f(x, y + 1); gl.glEnd(); } } if (textRenderer == null) { textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 48)); } if (avgMatchDistance > 0) { gl.glColor3f(1, 0, 0); gl.glLineWidth(5f); DrawGL.drawCircle(gl, searchDistance + .5f, searchDistance + .5f, avgMatchDistance, 16); } // a bunch of cryptic crap to draw a string the same width as the histogram... gl.glTranslatef(0, dim, 0); // translate to UL corner of histogram textRenderer.begin3DRendering(); String s = String.format("d=%s ms", engFmt.format(1e-3f * sliceDeltaT)); // final float sc = TextRendererScale.draw3dScale(textRenderer, s, chip.getCanvas().getScale(), chip.getSizeX(), .1f); // determine width of string in pixels and scale accordingly FontRenderContext frc = textRenderer.getFontRenderContext(); Rectangle2D r = textRenderer.getBounds(s); // bounds in java2d coordinates, downwards more positive Rectangle2D rt = frc.getTransform().createTransformedShape(r).getBounds2D(); // get bounds in textrenderer coordinates // float ps = chip.getCanvas().getScale(); float w = (float) rt.getWidth(); // width of text in textrenderer, i.e. histogram cell coordinates (1 unit = 1 histogram cell) float sc = dim / w; // scale to histogram width textRenderer.draw3D(s, 0, 0, 0, sc); textRenderer.end3DRendering(); String s2 = String.format("skip %d", skipProcessingEventsCount); gl.glTranslatef(0f, (float) (rt.getHeight()) * sc, 0); textRenderer.begin3DRendering(); textRenderer.draw3D(s2, 0, 0, 0, sc); textRenderer.end3DRendering(); gl.glPopMatrix(); } } @Override public synchronized void resetFilter() { super.resetFilter(); eventCounter = 0; lastTs = Integer.MIN_VALUE; // if ((histograms == null) || (histograms.length != subSizeX) || (histograms[0].length != subSizeY)) { // if ((NUM_SLICES == 0) && (subSizeX == 0) && (subSizeX == 0)) { // return; // histograms = new int[NUM_SLICES][subSizeX][subSizeY]; // for (int[][] a : histograms) { // for (int[] b : a) { // Arrays.fill(b, 0); // if (histogramsBitSet == null) { // histogramsBitSet = new BitSet[NUM_SLICES]; // for (int ii = 0; ii < NUM_SLICES; ii++) { // histogramsBitSet[ii] = new BitSet(subSizeX * subSizeY); if (bitmaps == null || bitmaps[0].length != subSizeX || bitmaps[0][0].length != subSizeY) { bitmaps = new boolean[NUM_SLICES][subSizeX][subSizeY]; } else { for (boolean[][] b : bitmaps) { clearBitmap(b); } } // // Initialize 3 ArrayList's histogram, every pixel has three patches: current, previous and previous-1 // if (histogramsAL == null) { // histogramsAL = new ArrayList[3]; // if ((spikeTrains == null) & (subSizeX != 0) & (subSizeY != 0)) { // spikeTrains = new ArrayList[subSizeX][subSizeY]; // if (patchDimension != 0) { // int colPatchCnt = subSizeX / patchDimension; // int rowPatchCnt = subSizeY / patchDimension; //// for (int ii = 0; ii < NUM_SLICES; ii++) { //// histogramsAL[ii] = new ArrayList(); //// for (int jj = 0; jj < (colPatchCnt * rowPatchCnt); jj++) { //// int[][] patch = new int[patchDimension][patchDimension]; //// histogramsAL[ii].add(patch); // tMinus2SliceIdx = 0; // tMinus1SliceIdx = 1; currentSliceIdx = 0; // start by filling slice 0 currentBitmap = bitmaps[currentSliceIdx]; // assignSliceReferences(); sliceLastTs = 0; rewindFlg = true; if (adaptiveEventSkippingUpdateCounterLPFilter != null) { adaptiveEventSkippingUpdateCounterLPFilter.reset(); } } @Override public void update(Observable o, Object arg) { if (!isFilterEnabled()) { return; } super.update(o, arg); if ((o instanceof AEChip) && (chip.getNumPixels() > 0)) { resetFilter(); } } /** * uses the current event to maybe rotate the slices */ private void maybeRotateSlices() { int dt = ts - sliceLastTs; switch (sliceMethod) { case ConstantDuration: if (rewindFlg) { return; } if ((dt < sliceDurationUs) || (dt < 0)) { return; } break; case ConstantEventNumber: if (rewindFlg) { return; } if (eventCounter++ < sliceEventCount) { return; } break; case AdaptationDuration: log.warning("The adaptation method is not supported yet."); return; } rotateSlices(); eventCounter = 0; sliceDeltaT = ts - sliceLastTs; sliceLastTs = ts; } /** * Rotates slices by incrementing the slice pointer with rollover back to * zero, and sets currentSliceIdx and currentBitmap. Clears the new * currentBitmap. Thus the slice pointer increments. 0,1,2,0,1,2 * */ private void rotateSlices() { /*Thus if 0 is current index for current filling slice, then sliceIndex returns 1,2 for pointer =1,2. * Then if NUM_SLICES=3, after rotateSlices(), currentSliceIdx=NUM_SLICES-1=2, and sliceIndex(0)=2, sliceIndex(1)=0, sliceIndex(2)=1. */ currentSliceIdx if (currentSliceIdx < 0) { currentSliceIdx = NUM_SLICES - 1; } currentBitmap = bitmaps[currentSliceIdx]; clearBitmap(currentBitmap); } /** * Returns index to slice given pointer, with zero as current filling slice * pointer. * * * @param pointer how many slices in the past to index for. I.e.. 0 for * current slice (one being currently filled), 1 for next oldest, 2 for * oldest (when using NUM_SLICES=3). * @return */ private int sliceIndex(int pointer) { return (currentSliceIdx + pointer) % NUM_SLICES; } /** * Accumulates the current event to the current slice * * @return true if subsequent processing should done, false if it should be * skipped for efficiency */ private boolean accumulateEvent(EventPacket in) { switch (patchCompareMethod) { // case SAD: // case JaccardDistance: // currentSlice[x][y] += e.getPolaritySignum(); // break; case HammingDistance: // currentSli.set((x + 1) + (y * subSizeX)); // All events wheather 0 or 1 will be set in the BitSet Slice currentBitmap[x][y] = true; } if (timeLimiter.isTimedOut()) { return false; } if (skipProcessingEventsCount == 0) { return true; } if (skipCounter++ < skipProcessingEventsCount) { return false; } skipCounter = 0; return true; } // private void clearSlice(int idx) { // for (int[] a : histograms[idx]) { // Arrays.fill(a, 0); private float sumArray[][] = null; /** * Computes hamming eight around point x,y using patchDimension and * searchDistance * * @param x coordinate in subsampled space * @param y * @param prevSlice the slice over which we search for best match * @param curSlice the slice from which we get the reference block * @return SADResult that provides the shift and SAD value */ // private SADResult minHammingDistance(int x, int y, BitSet prevSlice, BitSet curSlice) { private SADResult minHammingDistance(int x, int y, boolean[][] curSlice, boolean[][] prevSlice) { float minSum = Integer.MAX_VALUE, minSum1 = Integer.MAX_VALUE, sum = 0; float FSDx = 0, FSDy = 0, DSDx = 0, DSDy = 0; // This is for testing the DS search accuracy. final int searchRange = 2 * searchDistance + 1; // The maxium search index, for xidx and yidx. if (sumArray == null || sumArray.length != searchRange) { sumArray = new float[searchRange][searchRange]; } else { for (float[] row : sumArray) { Arrays.fill(row, Integer.MAX_VALUE); } } if (outputSearchErrorInfo) { searchMethod = SearchMethod.FullSearch; } else { searchMethod = getSearchMethod(); } switch (searchMethod) { case FullSearch: for (int dx = -searchDistance; dx <= searchDistance; dx++) { for (int dy = -searchDistance; dy <= searchDistance; dy++) { sum = hammingDistance(x, y, dx, dy, prevSlice, curSlice); sumArray[dx + searchDistance][dy + searchDistance] = sum; if (sum <= minSum1) { // if (sum == minSum1 && minSum1 != Integer.MAX_VALUE) { // tmpSadResult.minSearchedFlg = true; // } else { // tmpSadResult.minSearchedFlg = false; minSum1 = sum; tmpSadResult.dx = dx; tmpSadResult.dy = dy; tmpSadResult.sadValue = minSum1; } } } // if (tmpSadResult.minSearchedFlg) { // tmpSadResult.sadValue = Integer.MAX_VALUE; // This minimum is not a unique minimum, we should reject this event. if (outputSearchErrorInfo) { FSCnt += 1; FSDx = tmpSadResult.dx; FSDy = tmpSadResult.dy; } else { break; } case DiamondSearch: /* The center of the LDSP or SDSP could change in the iteration process, so we need to use a variable to represent it. In the first interation, it's the Zero Motion Potion (ZMP). */ int xCenter = x, yCenter = y; /* x offset of center point relative to ZMP, y offset of center point to ZMP. x offset of center pointin positive number to ZMP, y offset of center point in positive number to ZMP. */ int dx, dy, xidx, yidx; int minPointIdx = 0; // Store the minimum point index. boolean SDSPFlg = false; // If this flag is set true, then it means LDSP search is finished and SDSP search could start. /* If one block has been already calculated, the computedFlg will be set so we don't to do the calculation again. */ boolean computedFlg[][] = new boolean[searchRange][searchRange]; for (boolean[] row : computedFlg) { Arrays.fill(row, false); } if (searchDistance == 1) { // LDSP search can only be applied for search distance >= 2. SDSPFlg = true; } while (!SDSPFlg) { /* 1. LDSP search */ for (int pointIdx = 0; pointIdx < LDSP.length; pointIdx++) { dx = LDSP[pointIdx][0] + xCenter - x; dy = LDSP[pointIdx][1] + yCenter - y; xidx = dx + searchDistance; yidx = dy + searchDistance; // Point to be searched is out of search area, skip it. if (xidx >= searchRange || yidx >= searchRange || xidx < 0 || yidx < 0) { continue; } /* We just calculate the blocks that haven't been calculated before */ if (computedFlg[xidx][yidx] == false) { sumArray[xidx][yidx] = hammingDistance(x, y, dx, dy, prevSlice, curSlice); computedFlg[xidx][yidx] = true; if (outputSearchErrorInfo) { DSAverageNum++; } if (outputSearchErrorInfo) { if (sumArray[xidx][yidx] != sumArray[xidx][yidx]) { log.warning("It seems that there're some bugs in the DS algorithm."); } } } if (sumArray[xidx][yidx] <= minSum) { minSum = sumArray[xidx][yidx]; minPointIdx = pointIdx; } } /* 2. Check the minimum value position is in the center or not. */ xCenter = xCenter + LDSP[minPointIdx][0]; yCenter = yCenter + LDSP[minPointIdx][1]; if (minPointIdx == 4) { // It means it's in the center, so we should break the loop and go to SDSP search. SDSPFlg = true; } else { SDSPFlg = false; } } /* 3. SDSP Search */ for (int pointIdx = 0; pointIdx < SDSP.length; pointIdx++) { dx = SDSP[pointIdx][0] + xCenter - x; dy = SDSP[pointIdx][1] + yCenter - y; xidx = dx + searchDistance; yidx = dy + searchDistance; // Point to be searched is out of search area, skip it. if (xidx >= searchRange || yidx >= searchRange || xidx < 0 || yidx < 0) { continue; } /* We just calculate the blocks that haven't been calculated before */ if (computedFlg[xidx][yidx] == false) { sumArray[xidx][yidx] = hammingDistance(x, y, dx, dy, prevSlice, curSlice); computedFlg[xidx][yidx] = true; if (outputSearchErrorInfo) { DSAverageNum++; } if (outputSearchErrorInfo) { if (sumArray[xidx][yidx] != sumArray[xidx][yidx]) { log.warning("It seems that there're some bugs in the DS algorithm."); } } } if (sumArray[xidx][yidx] <= minSum) { minSum = sumArray[xidx][yidx]; tmpSadResult.dx = dx; tmpSadResult.dy = dy; tmpSadResult.sadValue = minSum; } } if (outputSearchErrorInfo) { DSDx = tmpSadResult.dx; DSDy = tmpSadResult.dy; } break; case CrossDiamondSearch: break; } tmpSadResult.xidx = (int) tmpSadResult.dx + searchDistance; tmpSadResult.yidx = (int) tmpSadResult.dy + searchDistance; // what a hack.... if (outputSearchErrorInfo) { if (DSDx == FSDx && DSDy == FSDy) { DSCorrectCnt += 1; } else { DSAveError[0] += Math.abs(DSDx - FSDx); DSAveError[1] += Math.abs(DSDy - FSDy); } if (0 == FSCnt % 10000) { log.log(Level.INFO, "Correct Diamond Search times are {0}, Full Search times are {1}, accuracy is {2}, averageNumberPercent is {3}, averageError is ({4}, {5})", new Object[]{DSCorrectCnt, FSCnt, DSCorrectCnt / FSCnt, DSAverageNum / (searchRange * searchRange * FSCnt), DSAveError[0] / FSCnt, DSAveError[1] / (FSCnt - DSCorrectCnt)}); } } // if (tmpSadResult.xidx == searchRange-1 && tmpSadResult.yidx == searchRange-1) { // tmpSadResult.sadValue = 1; // reject results to top right that are likely result of ambiguous search return tmpSadResult; } /** * computes Hamming distance centered on x,y with patch of patchSize for * prevSliceIdx relative to curSliceIdx patch. * * @param x coordinate x in subSampled space * @param y coordinate y in subSampled space * @param dx * @param dy * @param prevSlice * @param curSlice * @return Hamming Distance value, max 1 when all bits differ, min 0 when * all the same */ // private float hammingDistance(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) { private float hammingDistance(int x, int y, int dx, int dy, boolean[][] prevSlice, boolean[][] curSlice) { float retVal = 0; int hd = 0; final int blockRadius = patchDimension / 2; float validPixNumCurrSli = 0, validPixNumPrevSli = 0; // The valid pixel number in the current block // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius)) || (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) { return 1; // TODO why return 1 here? } for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) { for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) { // boolean currSlicePol = curSlice.get((xx + 1) + ((yy) * subSizeX)); // binary value on (xx, yy) for current slice // boolean prevSlicePol = prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)); // binary value on (xx, yy) for previous slice boolean currSlicePol = curSlice[xx][yy]; // binary value on (xx, yy) for current slice boolean prevSlicePol = prevSlice[xx - dx][yy - dy]; // binary value on (xx, yy) for previous slice if (currSlicePol != prevSlicePol) { hd += 1; } if (currSlicePol == true) { validPixNumCurrSli++; } if (prevSlicePol == true) { validPixNumPrevSli++; } } } int blockArea = ((2 * blockRadius) + 1) * ((2 * blockRadius) + 1); // TODD: NEXT WORK IS TO DO THE RESEARCH ON WEIGHTED HAMMING DISTANCE // Calculate the metric confidence value float validPixNum = this.validPixOccupancy * blockArea; if ((validPixNumCurrSli <= validPixNum) || (validPixNumPrevSli <= validPixNum) || (validPixNumCurrSli == blockArea) || (validPixNumPrevSli == blockArea)) { // If valid pixel number of any slice is 0, then we set the distance to very big value so we can exclude it. return 1; } else { /* retVal consists of the distance and the dispersion. dispersion is used to describe the spatial relationship within one block. Here we use the difference between validPixNumCurrSli and validPixNumPrevSli to calculate the dispersion. Inspired by paper "Measuring the spatial dispersion of evolutionist search process: application to Walksat" by Alain Sidaner. */ return ((hd * weightDistance) + (Math.abs(validPixNumCurrSli - validPixNumPrevSli) * (1 - weightDistance))) / blockArea; } } /** * Computes hamming weight around point x,y using patchDimension and * searchDistance * * @param x coordinate in subsampled space * @param y * @param prevSlice * @param curSlice * @return SADResult that provides the shift and SAD value */ // private SADResult minJaccardDistance(int x, int y, BitSet prevSlice, BitSet curSlice) { private SADResult minJaccardDistance(int x, int y, boolean[][] prevSlice, boolean[][] curSlice) { float minSum = Integer.MAX_VALUE, sum = 0; SADResult sadResult = new SADResult(0, 0, 0); for (int dx = -searchDistance; dx <= searchDistance; dx++) { for (int dy = -searchDistance; dy <= searchDistance; dy++) { sum = jaccardDistance(x, y, dx, dy, prevSlice, curSlice); if (sum <= minSum) { minSum = sum; sadResult.dx = dx; sadResult.dy = dy; sadResult.sadValue = minSum; } } } return sadResult; } /** * computes Hamming distance centered on x,y with patch of patchSize for * prevSliceIdx relative to curSliceIdx patch. * * @param x coordinate in subSampled space * @param y * @param patchSize * @param prevSlice * @param curSlice * @return SAD value */ // private float jaccardDistance(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) { private float jaccardDistance(int x, int y, int dx, int dy, boolean[][] prevSlice, boolean[][] curSlice) { float retVal = 0; float M01 = 0, M10 = 0, M11 = 0; int blockRadius = patchDimension / 2; // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius)) || (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) { return 1; } for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) { for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) { final boolean c = curSlice[xx][yy], p = prevSlice[xx - dx][yy - dy]; if ((c == true) && (p == true)) { M11 += 1; } if ((c == true) && (p == false)) { M01 += 1; } if ((c == false) && (p == true)) { M10 += 1; } // if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == true) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == true)) { // M11 += 1; // if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == true) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == false)) { // M01 += 1; // if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == false) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == true)) { // M10 += 1; } } if (0 == (M01 + M10 + M11)) { retVal = 0; } else { retVal = M11 / (M01 + M10 + M11); } retVal = 1 - retVal; return retVal; } // private SADResult minVicPurDistance(int blockX, int blockY) { // ArrayList<Integer[]> seq1 = new ArrayList(1); // SADResult sadResult = new SADResult(0, 0, 0); // int size = spikeTrains[blockX][blockY].size(); // int lastTs = spikeTrains[blockX][blockY].get(size - forwardEventNum)[0]; // for (int i = size - forwardEventNum; i < size; i++) { // seq1.add(spikeTrains[blockX][blockY].get(i)); //// if(seq1.get(2)[0] - seq1.get(0)[0] > thresholdTime) { //// return sadResult; // double minium = Integer.MAX_VALUE; // for (int i = -1; i < 2; i++) { // for (int j = -1; j < 2; j++) { // // Remove the seq1 itself // if ((0 == i) && (0 == j)) { // continue; // ArrayList<Integer[]> seq2 = new ArrayList(1); // if ((blockX >= 2) && (blockY >= 2)) { // ArrayList<Integer[]> tmpSpikes = spikeTrains[blockX + i][blockY + j]; // if (tmpSpikes != null) { // for (int index = 0; index < tmpSpikes.size(); index++) { // if (tmpSpikes.get(index)[0] >= lastTs) { // seq2.add(tmpSpikes.get(index)); // double dis = vicPurDistance(seq1, seq2); // if (dis < minium) { // minium = dis; // sadResult.dx = -i; // sadResult.dy = -j; // lastFireIndex[blockX][blockY] = spikeTrains[blockX][blockY].size() - 1; // if ((sadResult.dx != 1) || (sadResult.dy != 0)) { // // sadResult = new SADResult(0, 0, 0); // return sadResult; // private double vicPurDistance(ArrayList<Integer[]> seq1, ArrayList<Integer[]> seq2) { // int sum1Plus = 0, sum1Minus = 0, sum2Plus = 0, sum2Minus = 0; // Iterator itr1 = seq1.iterator(); // Iterator itr2 = seq2.iterator(); // int length1 = seq1.size(); // int length2 = seq2.size(); // double[][] distanceMatrix = new double[length1 + 1][length2 + 1]; // for (int h = 0; h <= length1; h++) { // for (int k = 0; k <= length2; k++) { // if (h == 0) { // distanceMatrix[h][k] = k; // continue; // if (k == 0) { // distanceMatrix[h][k] = h; // continue; // double tmpMin = Math.min(distanceMatrix[h][k - 1] + 1, distanceMatrix[h - 1][k] + 1); // double event1 = seq1.get(h - 1)[0] - seq1.get(0)[0]; // double event2 = seq2.get(k - 1)[0] - seq2.get(0)[0]; // distanceMatrix[h][k] = Math.min(tmpMin, distanceMatrix[h - 1][k - 1] + (cost * Math.abs(event1 - event2))); // while (itr1.hasNext()) { // Integer[] ii = (Integer[]) itr1.next(); // if (ii[1] == 1) { // sum1Plus += 1; // } else { // sum1Minus += 1; // while (itr2.hasNext()) { // Integer[] ii = (Integer[]) itr2.next(); // if (ii[1] == 1) { // sum2Plus += 1; // } else { // sum2Minus += 1; // // return Math.abs(sum1Plus - sum2Plus) + Math.abs(sum1Minus - sum2Minus); // return distanceMatrix[length1][length2]; // /** // * Computes min SAD shift around point x,y using patchDimension and // * searchDistance // * // * @param x coordinate in subsampled space // * @param y // * @param prevSlice // * @param curSlice // * @return SADResult that provides the shift and SAD value // */ // private SADResult minSad(int x, int y, BitSet prevSlice, BitSet curSlice) { // // for now just do exhaustive search over all shifts up to +/-searchDistance // SADResult sadResult = new SADResult(0, 0, 0); // float minSad = 1; // for (int dx = -searchDistance; dx <= searchDistance; dx++) { // for (int dy = -searchDistance; dy <= searchDistance; dy++) { // float sad = sad(x, y, dx, dy, prevSlice, curSlice); // if (sad <= minSad) { // minSad = sad; // sadResult.dx = dx; // sadResult.dy = dy; // sadResult.sadValue = minSad; // return sadResult; // /** // * computes SAD centered on x,y with shift of dx,dy for prevSliceIdx // * relative to curSliceIdx patch. // * // * @param x coordinate x in subSampled space // * @param y coordinate y in subSampled space // * @param dx block shift of x // * @param dy block shift of y // * @param prevSliceIdx // * @param curSliceIdx // * @return SAD value // */ // private float sad(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) { // int blockRadius = patchDimension / 2; // // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. // if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius)) // || (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) { // return 1; // float sad = 0, retVal = 0; // float validPixNumCurrSli = 0, validPixNumPrevSli = 0; // The valid pixel number in the current block // for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) { // for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) { // boolean currSlicePol = curSlice.get((xx + 1) + ((yy) * subSizeX)); // binary value on (xx, yy) for current slice // boolean prevSlicePol = prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)); // binary value on (xx, yy) for previous slice // int d = (currSlicePol ? 1 : 0) - (prevSlicePol ? 1 : 0); // if (currSlicePol == true) { // validPixNumCurrSli += 1; // if (prevSlicePol == true) { // validPixNumPrevSli += 1; // if (d <= 0) { // d = -d; // sad += d; // // Calculate the metric confidence value // float validPixNum = this.validPixOccupancy * (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1)); // if ((validPixNumCurrSli <= validPixNum) || (validPixNumPrevSli <= validPixNum)) { // If valid pixel number of any slice is 0, then we set the distance to very big value so we can exclude it. // retVal = 1; // } else { // /* // retVal is consisted of the distance and the dispersion, dispersion is used to describe the spatial relationship within one block. // Here we use the difference between validPixNumCurrSli and validPixNumPrevSli to calculate the dispersion. // Inspired by paper "Measuring the spatial dispersion of evolutionist search process: application to Walksat" by Alain Sidaner. // */ // retVal = ((sad * weightDistance) + (Math.abs(validPixNumCurrSli - validPixNumPrevSli) * (1 - weightDistance))) / (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1)); // return retVal; private class SADResult { float dx, dy; float sadValue; int xidx, yidx; // x and y indices into 2d matrix of result. 0,0 corresponds to motion SW. dx, dy may be negative, like (-1, -1) represents SW. // However, for histgram index, it's not possible to use negative number. That's the reason for intrducing xidx and yidx. // boolean minSearchedFlg = false; // The flag indicates that this minimum have been already searched before. public SADResult(float dx, float dy, float sadValue) { this.dx = dx; this.dy = dy; this.sadValue = sadValue; } public void set(SADResult s) { this.dx = s.dx; this.dy = s.dy; this.sadValue = this.sadValue; this.xidx = s.xidx; this.yidx = s.yidx; } @Override public String toString() { return String.format("dx,dy=%d,%5 SAD=%d", dx, dy, sadValue); } } private class Statistics { double[] data; int size; public Statistics(double[] data) { this.data = data; size = data.length; } double getMean() { double sum = 0.0; for (double a : data) { sum += a; } return sum / size; } double getVariance() { double mean = getMean(); double temp = 0; for (double a : data) { temp += (a - mean) * (a - mean); } return temp / size; } double getStdDev() { return Math.sqrt(getVariance()); } public double median() { Arrays.sort(data); if (data.length % 2 == 0) { return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0; } return data[data.length / 2]; } public double getMin() { Arrays.sort(data); return data[0]; } public double getMax() { Arrays.sort(data); return data[data.length - 1]; } } /** * @return the patchDimension */ public int getPatchDimension() { return patchDimension; } /** * @param patchDimension the patchDimension to set */ public void setPatchDimension(int patchDimension) { int old = this.patchDimension; // enforce odd value if ((patchDimension & 1) == 0) { // even if (patchDimension > old) { patchDimension++; } else { patchDimension } } // clip final value if (patchDimension < 1) { patchDimension = 1; } else if (patchDimension > 63) { patchDimension = 63; } this.patchDimension = patchDimension; support.firePropertyChange("patchDimension", old, patchDimension); putInt("patchDimension", patchDimension); } // public int getEventPatchDimension() { // return eventPatchDimension; // public void setEventPatchDimension(int eventPatchDimension) { // this.eventPatchDimension = eventPatchDimension; // putInt("eventPatchDimension", eventPatchDimension); // public int getForwardEventNum() { // return forwardEventNum; // public void setForwardEventNum(int forwardEventNum) { // this.forwardEventNum = forwardEventNum; // putInt("forwardEventNum", forwardEventNum); // public float getCost() { // return cost; // public void setCost(float cost) { // this.cost = cost; // putFloat("cost", cost); // public int getThresholdTime() { // return thresholdTime; // public void setThresholdTime(int thresholdTime) { // this.thresholdTime = thresholdTime; // putInt("thresholdTime", thresholdTime); /** * @return the sliceMethod */ public SliceMethod getSliceMethod() { return sliceMethod; } /** * @param sliceMethod the sliceMethod to set */ public void setSliceMethod(SliceMethod sliceMethod) { this.sliceMethod = sliceMethod; putString("sliceMethod", sliceMethod.toString()); } public PatchCompareMethod getPatchCompareMethod() { return patchCompareMethod; } public void setPatchCompareMethod(PatchCompareMethod patchCompareMethod) { this.patchCompareMethod = patchCompareMethod; putString("patchCompareMethod", patchCompareMethod.toString()); } /** * * @return the search method */ public SearchMethod getSearchMethod() { return searchMethod; } /** * * @param searchMethod the method to be used for searching */ public void setSearchMethod(SearchMethod searchMethod) { this.searchMethod = searchMethod; putString("searchMethod", searchMethod.toString()); } @Override public synchronized void setSearchDistance(int searchDistance) { int old = this.searchDistance; if (searchDistance > 12) { searchDistance = 12; } else if (searchDistance < 1) { searchDistance = 1; // limit size } this.searchDistance = searchDistance; putInt("searchDistance", searchDistance); support.firePropertyChange("searchDistance", old, searchDistance); resetFilter(); } /** * @return the sliceDurationUs */ public int getSliceDurationUs() { return sliceDurationUs; } /** * @param sliceDurationUs the sliceDurationUs to set */ public void setSliceDurationUs(int sliceDurationUs) { int old = this.sliceDurationUs; if (sliceDurationUs < MIN_SLICE_DURATION) { sliceDurationUs = MIN_SLICE_DURATION; } else if (sliceDurationUs > MAX_SLICE_DURATION) { sliceDurationUs = MAX_SLICE_DURATION; // limit it to one second } this.sliceDurationUs = sliceDurationUs; /* If the slice duration is changed, reset FSCnt and DScorrect so we can get more accurate evaluation result */ FSCnt = 0; DSCorrectCnt = 0; putInt("sliceDurationUs", sliceDurationUs); getSupport().firePropertyChange("sliceDurationUs", old, this.sliceDurationUs); } /** * @return the sliceEventCount */ public int getSliceEventCount() { return sliceEventCount; } /** * @param sliceEventCount the sliceEventCount to set */ public void setSliceEventCount(int sliceEventCount) { this.sliceEventCount = sliceEventCount; putInt("sliceEventCount", sliceEventCount); } // public boolean isPreProcessEnable() { // return preProcessEnable; // public void setPreProcessEnable(boolean preProcessEnable) { // this.preProcessEnable = preProcessEnable; // putBoolean("preProcessEnable", preProcessEnable); public float getConfidenceThreshold() { return confidenceThreshold; } public void setConfidenceThreshold(float confidenceThreshold) { if (confidenceThreshold < 0) { confidenceThreshold = 0; } else if (confidenceThreshold > 1) { confidenceThreshold = 1; } this.confidenceThreshold = confidenceThreshold; putFloat("confidenceThreshold", confidenceThreshold); } public float getValidPixOccupancy() { return validPixOccupancy; } public void setValidPixOccupancy(float validPixOccupancy) { if (validPixOccupancy < 0) { validPixOccupancy = 0; } else if (validPixOccupancy > 1) { validPixOccupancy = 1; } this.validPixOccupancy = validPixOccupancy; putFloat("validPixOccupancy", validPixOccupancy); } public float getWeightDistance() { return weightDistance; } public void setWeightDistance(float weightDistance) { if (weightDistance < 0) { weightDistance = 0; } else if (weightDistance > 1) { weightDistance = 1; } this.weightDistance = weightDistance; putFloat("weightDistance", weightDistance); } // private int totalFlowEvents=0, filteredOutFlowEvents=0; // private boolean filterOutInconsistentEvent(SADResult result) { // if (!isOutlierMotionFilteringEnabled()) { // return false; // totalFlowEvents++; // if (lastGoodSadResult == null) { // return false; // if (result.dx * lastGoodSadResult.dx + result.dy * lastGoodSadResult.dy >= 0) { // return false; // filteredOutFlowEvents++; // return true; private void checkArrays() { // if (lastFireIndex == null) { // lastFireIndex = new int[chip.getSizeX()][chip.getSizeY()]; // if (eventSeqStartTs == null) { // eventSeqStartTs = new int[chip.getSizeX()][chip.getSizeY()]; if (lastTimesMap != null) { lastTimesMap = null; // save memory } } /** * * @param distResult * @return the confidence of the result. True means it's not good and should * be rejected, false means we should accept it. */ public synchronized boolean isNotSufficientlyAccurate(SADResult distResult) { boolean retVal = super.accuracyTests(); // check accuracy in super, if reject returns true // additional test, normalized blaock distance must be small enough // distance has max value 1 if (distResult.sadValue >= (1 - confidenceThreshold)) { retVal = true; } return retVal; } /** * @return the skipProcessingEventsCount */ public int getSkipProcessingEventsCount() { return skipProcessingEventsCount; } /** * @param skipProcessingEventsCount the skipProcessingEventsCount to set */ public void setSkipProcessingEventsCount(int skipProcessingEventsCount) { int old = this.skipProcessingEventsCount; if (skipProcessingEventsCount < 0) { skipProcessingEventsCount = 0; } if (skipProcessingEventsCount > MAX_SKIP_COUNT) { skipProcessingEventsCount = MAX_SKIP_COUNT; } this.skipProcessingEventsCount = skipProcessingEventsCount; getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount); putInt("skipProcessingEventsCount", skipProcessingEventsCount); } /** * @return the displayResultHistogram */ public boolean isDisplayResultHistogram() { return displayResultHistogram; } /** * @param displayResultHistogram the displayResultHistogram to set */ public void setDisplayResultHistogram(boolean displayResultHistogram) { this.displayResultHistogram = displayResultHistogram; putBoolean("displayResultHistogram", displayResultHistogram); } /** * @return the adaptiveEventSkipping */ public boolean isAdaptiveEventSkipping() { return adaptiveEventSkipping; } /** * @param adaptiveEventSkipping the adaptiveEventSkipping to set */ public void setAdaptiveEventSkipping(boolean adaptiveEventSkipping) { this.adaptiveEventSkipping = adaptiveEventSkipping; putBoolean("adaptiveEventSkipping", adaptiveEventSkipping); if (adaptiveEventSkipping) { adaptiveEventSkippingUpdateCounterLPFilter.reset(); } } public boolean isOutputSearchErrorInfo() { return outputSearchErrorInfo; } public boolean isShowSliceBitMap() { return showSliceBitMap; } /** * * @param showSliceBitMpa the option of displaying bitmap */ public void setShowSliceBitMap(boolean showSliceBitMap) { boolean old = this.showSliceBitMap; this.showSliceBitMap = showSliceBitMap; getSupport().firePropertyChange("showSliceBitMap", old, this.showSliceBitMap); putBoolean("showSliceBitMap", showSliceBitMap); } synchronized public void setOutputSearchErrorInfo(boolean outputSearchErrorInfo) { this.outputSearchErrorInfo = outputSearchErrorInfo; if (!outputSearchErrorInfo) { searchMethod = SearchMethod.valueOf(getString("searchMethod", SearchMethod.FullSearch.toString())); // make sure method is reset } } private LowpassFilter adaptiveEventSkippingUpdateCounterLPFilter = null; private int adaptiveEventSkippingUpdateCounter = 0; private void adaptEventSkipping() { if (!adaptiveEventSkipping) { return; } if (chip.getAeViewer() == null) { return; } int old = skipProcessingEventsCount; if (adaptiveEventSkippingUpdateCounterLPFilter == null) { adaptiveEventSkippingUpdateCounterLPFilter = new LowpassFilter(chip.getAeViewer().getFrameRater().FPS_LOWPASS_FILTER_TIMECONSTANT_MS); } final float averageFPS = chip.getAeViewer().getFrameRater().getAverageFPS(); final int frameRate = chip.getAeViewer().getDesiredFrameRate(); boolean skipMore = averageFPS < (int) (0.75f * frameRate); boolean skipLess = averageFPS > (int) (0.25f * frameRate); float newSkipCount = skipProcessingEventsCount; if (skipMore) { newSkipCount = adaptiveEventSkippingUpdateCounterLPFilter.filter(1 + (skipChangeFactor * skipProcessingEventsCount), 1000 * (int) System.currentTimeMillis()); } else if (skipLess) { newSkipCount = adaptiveEventSkippingUpdateCounterLPFilter.filter((skipProcessingEventsCount / skipChangeFactor) - 1, 1000 * (int) System.currentTimeMillis()); } skipProcessingEventsCount = (int) newSkipCount; if (skipProcessingEventsCount > MAX_SKIP_COUNT) { skipProcessingEventsCount = MAX_SKIP_COUNT; } else if (skipProcessingEventsCount < 0) { skipProcessingEventsCount = 0; } getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount); } /** * @return the adapativeSliceDuration */ public boolean isAdapativeSliceDuration() { return adapativeSliceDuration; } /** * @param adapativeSliceDuration the adapativeSliceDuration to set */ public void setAdapativeSliceDuration(boolean adapativeSliceDuration) { this.adapativeSliceDuration = adapativeSliceDuration; putBoolean("adapativeSliceDuration", adapativeSliceDuration); } /** * @return the processingTimeLimitMs */ public int getProcessingTimeLimitMs() { return processingTimeLimitMs; } /** * @param processingTimeLimitMs the processingTimeLimitMs to set */ public void setProcessingTimeLimitMs(int processingTimeLimitMs) { this.processingTimeLimitMs = processingTimeLimitMs; putInt("processingTimeLimitMs", processingTimeLimitMs); } @Override public void propertyChange(PropertyChangeEvent evt) { super.propertyChange(evt); // resets filter on rewind, etc } private void clearBitmap(boolean[][] bitmap) { for (boolean[] b : bitmap) { Arrays.fill(b, false); } } private int dim = patchDimension + 2 * searchDistance; private void showBitmaps(int x, int y, int dx, int dy, boolean[][] tm1Bitmap, boolean[][] tm2Bitmap) { int dimNew = patchDimension + 2 * searchDistance; if (Frame == null) { String windowName = "Slice bitmaps"; Frame = new JFrame(windowName); Frame.setLayout(new BoxLayout(Frame.getContentPane(), BoxLayout.Y_AXIS)); Frame.setPreferredSize(new Dimension(600, 600)); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); display = ImageDisplay.createOpenGLCanvas(); display.setBorderSpacePixels(10); display.setImageSize(dimNew, dimNew); display.setSize(200, 200); panel.add(display); Frame.getContentPane().add(panel); Frame.pack(); Frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { setShowSliceBitMap(false); } }); } if (!Frame.isVisible()) { Frame.setVisible(true); } if (dimNew != dim) { dim = dimNew; display.setImageSize(dimNew, dimNew); } final int radiaus = patchDimension / 2 + searchDistance; /* Reset the image first */ for (int i = 0; i < 2 * radiaus + 1; i++) { for (int j = 0; j < 2 * radiaus + 1; j++) { display.setPixmapRGB(i, j, 0, 0, 0); } } if ((x >= radiaus) && (x + radiaus < subSizeX) && (y >= radiaus) && (y + radiaus < subSizeY)) { /* Rendering the reference patch in t-d slice, it's on the center with color red */ for (int i = searchDistance; i < patchDimension + searchDistance; i++) { for (int j = searchDistance; j < patchDimension + searchDistance; j++) { float[] f = display.getPixmapRGB(i, j); f[0] = tm1Bitmap[x - patchDimension / 2 + i - searchDistance][y - patchDimension / 2 + j - searchDistance] ? 1 : 0; display.setPixmapRGB(i, j, f); } } /* Rendering the area within search distance in t-2d slice, it's full of the whole image with color green */ for (int i = 0; i < 2 * radiaus + 1; i++) { for (int j = 0; j < 2 * radiaus + 1; j++) { float[] f = display.getPixmapRGB(i, j); f[1] = tm2Bitmap[x - radiaus + i][y - radiaus + j] ? 1 : 0; display.setPixmapRGB(i, j, f); } } /* Rendering the best matching patch in t-2d slice, it's on the shifted position related to the center location with color blue */ for (int i = searchDistance + dx; i < patchDimension + searchDistance + dx; i++) { for (int j = searchDistance + dy; j < patchDimension + searchDistance + dy; j++) { float[] f = display.getPixmapRGB(i, j); f[2] = tm2Bitmap[x - patchDimension / 2 + i - searchDistance][y - patchDimension / 2 + j - searchDistance] ? 1 : 0; display.setPixmapRGB(i, j, f); } } } // gl.glPopMatrix(); display.repaint(); } }
package org.col.api.vocab; public enum DatasetType { /** * A list of names focussing on nomenclature and not dealing with taxonomy. */ NOMENCLATURAL, /** * A taxonomic checklist with global coverage, a global species database (GSD). */ GLOBAL, /** * A regional or national checklist. */ REGIONAL, /** * A dataset representing taxonomic treatments of a single scientific article. * Mostly published through Plazi or Pensoft at this stage. */ ARTICLE, /** * A list of names uploaded for personal use. */ PERSONAL, OTHER; }
package com.codahale.simplespec.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * An annotation used to indicate that the annotated method is a test method * and should be run by the simplespec test runner. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface test { }
package com.codepine.api.testrail.model; import com.codepine.api.testrail.TestRail; import com.fasterxml.jackson.annotation.JsonView; import lombok.Data; /** * TestRail section. */ @Data public class Section { private int id; @JsonView({TestRail.Sections.Add.class, TestRail.Sections.Update.class}) private String name; @JsonView({TestRail.Sections.Add.class, TestRail.Sections.Update.class}) private String description; @JsonView(TestRail.Sections.Add.class) private Integer suiteId; @JsonView(TestRail.Sections.Add.class) private Integer parentId; private int depth; private int displayOrder; }
package com.continuuity.common.metrics; import com.google.common.collect.Maps; import com.yammer.metrics.Metrics; import com.yammer.metrics.core.*; import java.util.Map; import java.util.concurrent.TimeUnit; /** * A simple API for translating the metrics collected for specific * groups in the systems into yammer metrics. It's more like an * adapter that simplifies our process. * * It current supports {@link Counter} and {@link Gauge}. */ public class CMetrics { /** * Type of metric the {@link CMetrics} is responsible for collecting. */ private final MetricType metricType; /** * Mapping of metric name to it's equivalent yammer metric counters. */ private Map<String, Counter> counters; /** * Mapping of metric name to it's equivalent yammer gauge. */ private Map<String, Gauge> gauges; /** * Mapping of metric name to it's equivalent meters measuring rates. */ private Map<String, Meter> meters; /** * Mapping of metric name to their histograms being tracked. */ private Map<String, Histogram> histograms; /** * Specifies the group the metrics are collected for. */ private final String metricGroup; /** * Constructor specifying the type of metric as specified by * the {@link MetricType} and the group the metrics belong to. * * @param metricType collected * @param metricGroup the metrics being collected belong to. */ public CMetrics(MetricType metricType, String metricGroup) throws IllegalArgumentException { // if a metric type is user or system flow metric then metric // group has be valid. if(metricType == MetricType.FlowSystem || metricType == MetricType.FlowUser) { if(metricGroup == null || metricGroup.isEmpty()) { throw new IllegalArgumentException("Metric group cannot be empty or null " + "for a flow metric."); } } this.metricType = metricType; this.metricGroup = metricGroup; this.counters = Maps.newConcurrentMap(); this.gauges = Maps.newConcurrentMap(); this.meters = Maps.newConcurrentMap(); this.histograms = Maps.newConcurrentMap(); } public CMetrics(MetricType metricType) throws IllegalArgumentException { this(metricType, ""); } /** * Increments a given metric counter. It's a specialization of a gauge * that allows to increment or decrement a value associated with the * counter metric. * * @param metricName name of the metric. * @param value to increment the metric by. */ public void counter(String metricName, long value) { counter(null, metricName, value); } /** * Increments a given metric counter. It's a specialization of a gauge * that allows to increment or decrement a value associated with the * counter metric. * * @param scope of the metric being measured. * @param metricName name of the metric. * @param value to increment the metric by. */ public void counter(Class<?> scope, String metricName, long value) { if(! counters.containsKey(metricName)) { MetricName name = getMetricName(scope, metricName); counters.put(metricName, Metrics.newCounter(name)); } counters.get(metricName).inc(value); } protected MetricName getMetricName(Class<?> scope, String metricName) { return new MetricName(metricGroup, metricType.name(), metricName, scope == null ? null : getScope(scope)); } /** * Sets a gauge to be measured. * * @param metricName name of the metric. * @param value to be associated with the metric. */ public void set(String metricName, final float value) { if(! gauges.containsKey(metricName)) { MetricName name = getMetricName(null, metricName); gauges.put(metricName, Metrics.newGauge(name, new Gauge<Float>() { @Override public Float value() { return value; } })); } } /** * Measures the rate of events over time. E.g. Requests per second. * It also allows to track mean rate, 1,5, 15 minute moving averages. * * @param metricName name of the metric. * @param value to increment the meter by. */ public void meter(String metricName, long value) { meter(null, metricName, value); } /** * Measures the rate of events over time for a metric within a * given scope of package. * * @param scope within which the metric is measured. This is essentially a tag. * @param metricName name of the metric. * @param value to increment the meter by. */ public void meter(Class<?> scope, String metricName, long value) { if(! meters.containsKey(metricName)) { MetricName name = getMetricName(scope, metricName); meters.put(metricName, Metrics.newMeter(name, metricName, TimeUnit.SECONDS)); } meters.get(metricName).mark(value); } /** * Measures the statistical distribution of values in a stream of * data. It measure min, max and mean and in addition also can measure * median, 75th, 90th, 95th, 98th, 99th and 99.9th percentiles. * * @param metricName name of the metric. * @param value to be used for histogram. */ public void histogram(String metricName, long value) { histogram(null, metricName, value); } /** * Measures the statistical distribution of values in a stream of * data. It measure min, max and mean and in addition also can measure * median, 75th, 90th, 95th, 98th, 99th and 99.9th percentiles. * * @param scope of the metric being measured. * @param metricName name of the metric. * @param value to be used for histogram. */ public void histogram(Class<?> scope, String metricName, long value) { if(! histograms.containsKey(metricName)) { MetricName name = getMetricName(scope, metricName); histograms.put(metricName, Metrics.newHistogram(name)); } histograms.get(metricName).update(value); } /** * Returns the scope based on the class specified. * * @param klass specified by class. * @return String representation of the scope. */ private String getScope(Class<?> klass) { return klass.getCanonicalName(); } }
package com.crawljax.forms; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.xpath.XPathExpressionException; import org.apache.commons.configuration.Configuration; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import com.crawljax.browser.EmbeddedBrowser; import com.crawljax.condition.eventablecondition.EventableCondition; import com.crawljax.core.CandidateElement; import com.crawljax.core.configuration.InputSpecification; import com.crawljax.core.configuration.InputSpecificationReader; import com.crawljax.core.state.Identification; import com.crawljax.util.Helper; import com.crawljax.util.XPathHelper; /** * Helper class for FormHandler. * * @author dannyroest@gmail.com (Danny Roest) * @author ali mesbah * @version $Id$ */ public final class FormInputValueHelper { private static final Logger LOGGER = Logger.getLogger(FormInputValueHelper.class.getName()); private Map<String, String> formFields = new HashMap<String, String>(); private Map<String, ArrayList<String>> formFieldNames = new HashMap<String, ArrayList<String>>(); private Map<String, ArrayList<String>> fieldValues = new HashMap<String, ArrayList<String>>(); private Configuration config; private boolean randomInput; /** * @param inputSpecification * the input specification. * @param randomInput * if random data should be used on the input fields. */ public FormInputValueHelper(InputSpecification inputSpecification, boolean randomInput) { this.randomInput = randomInput; if (inputSpecification != null) { config = new InputSpecificationReader(inputSpecification).getConfiguration(); Iterator keyIterator = config.getKeys(); while (keyIterator.hasNext()) { String fieldInfo = keyIterator.next().toString(); String id = fieldInfo.split("\\.")[0]; String property = fieldInfo.split("\\.")[1]; if (property.equalsIgnoreCase("fields")) { if (!formFields.containsKey(id)) { for (String fieldName : getPropertyAsList(fieldInfo)) { formFields.put(fieldName, id); } formFieldNames.put(id, getPropertyAsList(fieldInfo)); } } if (property.equalsIgnoreCase("values")) { fieldValues.put(id, getPropertyAsList(fieldInfo)); } } } } private Element getBelongingElement(Document dom, String fieldName) { List<String> names = getNamesForInputFieldId(fieldName); if (names != null) { for (String name : names) { /** * @param browser * the browser instance * @param sourceElement * the form elements * @param eventableCondition * the belonging eventable condition for sourceElement * @return a list with Candidate elements for the inputs */ public List<CandidateElement> getCandidateElementsForInputs(EmbeddedBrowser browser, Element sourceElement, EventableCondition eventableCondition) { List<CandidateElement> candidateElements = new ArrayList<CandidateElement>(); int maxValues = getMaxNumberOfValues(eventableCondition.getLinkedInputFields()); if (maxValues == 0) { LOGGER.warn("No input values found for element: " + Helper.getElementString(sourceElement)); return candidateElements; } Document dom; try { dom = Helper.getDocument(browser.getDomWithoutIframeContent()); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return candidateElements; } // add maxValues Candidate Elements for every input combination for (int curValueIndex = 0; curValueIndex < maxValues; curValueIndex++) { List<FormInput> formInputsForCurrentIndex = new ArrayList<FormInput>(); for (String fieldName : eventableCondition.getLinkedInputFields()) { Element element = getBelongingElement(dom, fieldName); if (element != null) { FormInput formInput = getFormInputWithIndexValue(browser, element, curValueIndex); formInputsForCurrentIndex.add(formInput); } else { LOGGER.warn("Could not find input element for: " + fieldName); } } String id = eventableCondition.getId() + "_" + curValueIndex; sourceElement.setAttribute("atusa", id); // clone node inclusive text content Element cloneElement = (Element) sourceElement.cloneNode(false); cloneElement.setTextContent(Helper.getTextValue(sourceElement)); CandidateElement candidateElement = new CandidateElement(cloneElement, XPathHelper .getXpathExpression(sourceElement)); candidateElement.setFormInputs(formInputsForCurrentIndex); candidateElements.add(candidateElement); } return candidateElements; } /** * @param input * the form input * @param dom * the document * @return returns the belonging node to input in dom * @throws XPathExpressionException * if a failure is occurred. */ public Node getBelongingNode(FormInput input, Document dom) throws XPathExpressionException { Node result = null; switch (input.getIdentification().getHow()) { case xpath: result = Helper.getElementByXpath(dom, input.getIdentification().getValue()); break; case id: case name: String xpath = ""; String element = ""; if (input.getType().equalsIgnoreCase("select") || input.getType().equalsIgnoreCase("textarea")) { element = input.getType().toUpperCase(); } else { element = "INPUT"; } xpath = "//" + element + "[@name='" + input.getIdentification().getValue() + "' or @id='" + input.getIdentification().getValue() + "']"; result = Helper.getElementByXpath(dom, xpath); break; default: LOGGER.info("Identification " + input.getIdentification() + " not supported yet for form inputs."); break; } return result; } /** * @param element * @return returns the id of the element if set, else the name. If none found, returns null * @throws Exception */ private Identification getIdentification(Node element) throws Exception { NamedNodeMap attributes = element.getAttributes(); if (attributes.getNamedItem("id") != null) { return new Identification(Identification.How.id, attributes.getNamedItem("id") .getNodeValue()); } else if (attributes.getNamedItem("name") != null) { return new Identification(Identification.How.name, attributes.getNamedItem("name") .getNodeValue()); } // try to find the xpath String xpathExpr = XPathHelper.getXpathExpression(element); if (xpathExpr != null && !xpathExpr.equals("")) { return new Identification(Identification.How.xpath, xpathExpr); } return null; } /** * @param browser * the current browser instance * @param element * the element in the dom * @return the first related formInput belonging to element in the browser */ public FormInput getFormInputWithDefaultValue(EmbeddedBrowser browser, Node element) { return getFormInput(browser, element, 0); } /** * @param browser * the current browser instance * @param element * the element in the dom * @param indexValue * the i-th specified value. if i>#values, first value is used * @return the specified value with index indexValue for the belonging elements */ public FormInput getFormInputWithIndexValue(EmbeddedBrowser browser, Node element, int indexValue) { return getFormInput(browser, element, indexValue); } private FormInput getFormInput(EmbeddedBrowser browser, Node element, int indexValue) { Identification identification; try { identification = getIdentification(element); if (identification == null) { return null; } } catch (Exception e) { return null; } // CHECK String id = fieldMatches(identification.getValue()); FormInput input = new FormInput(); input.setType(getElementType(element)); input.setIdentification(identification); Set<InputValue> values = new HashSet<InputValue>(); if (id != null && fieldValues.containsKey(id)) { // TODO: make multiple selection for list available // add defined value to element String value; if (indexValue == 0 || fieldValues.get(id).size() == 1 || indexValue + 1 > fieldValues.get(id).size()) { // default value value = fieldValues.get(id).get(0); } else if (indexValue > 0) { // index value value = fieldValues.get(id).get(indexValue); } else { // random value value = fieldValues.get(id).get( new Random().nextInt(fieldValues.get(id).size() - 1)); } if (input.getType().equals("checkbox") || input.getType().equals("radio")) { // check element values.add(new InputValue(value, value.equals("1"))); } else { // set value of text input field values.add(new InputValue(value, true)); } input.setInputValues(values); } else { if (this.randomInput) { return browser.getInputWithRandomValue(input); } // field is not specified, lets try a random value } return input; } /** * @param property * the property. * @return the values as a List. */ private ArrayList<String> getPropertyAsList(String property) { ArrayList<String> result = new ArrayList<String>(); String[] array = config.getStringArray(property); for (int i = 0; i < array.length; i++) { result.add(array[i]); } return result; } private String fieldMatches(String fieldName) { for (String field : formFields.keySet()) { Pattern p = Pattern.compile(field, Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(fieldName); if (m.matches()) { return formFields.get(field); } } return null; } private List<String> getValuesForName(String inputFieldId) { if (!fieldValues.containsKey(inputFieldId)) { return null; } return fieldValues.get(inputFieldId); } private List<String> getNamesForInputFieldId(String inputFieldId) { if (!formFieldNames.containsKey(inputFieldId)) { return null; } return formFieldNames.get(inputFieldId); } private String getElementType(Node node) { if (node.getAttributes().getNamedItem("type") != null) { return node.getAttributes().getNamedItem("type").getNodeValue().toLowerCase(); } else if (node.getNodeName().equalsIgnoreCase("input")) { return "text"; } else { return node.getNodeName().toLowerCase(); } } }
package com.emc.mongoose.metrics; import com.emc.mongoose.concurrent.DaemonBase; import com.emc.mongoose.concurrent.ServiceTaskExecutor; import com.emc.mongoose.concurrent.ThreadDump; import com.emc.mongoose.logging.*; import com.github.akurilov.commons.concurrent.AsyncRunnable; import com.github.akurilov.fiber4j.FiberBase; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.ThreadContext; import java.rmi.RemoteException; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import static com.emc.mongoose.Constants.KEY_CLASS_NAME; import static com.emc.mongoose.Constants.KEY_STEP_ID; import static org.apache.logging.log4j.CloseableThreadContext.Instance; import static org.apache.logging.log4j.CloseableThreadContext.put; public final class MetricsManager extends DaemonBase { private static final String CLS_NAME = MetricsManager.class.getSimpleName(); private static final MetricsManager INSTANCE; private static final int TIMEOUT = 10; static { try { INSTANCE = new MetricsManager(); } catch (final Throwable cause) { throw new AssertionError(cause); } } private final Map<String, Map<MetricsContext, AutoCloseable>> allMetrics = new HashMap<>(); private final Set<MetricsContext> selectedMetrics = new TreeSet<>(); private final Lock allMetricsLock = new ReentrantLock(); private final AsyncRunnable task = new FiberBase(ServiceTaskExecutor.INSTANCE) { private long outputPeriodMillis; private long lastOutputTs; private long nextOutputTs; @Override protected final void doClose() { } @Override protected final void invokeTimed(final long startTimeNanos) { try { for (final String id : allMetrics.keySet()) { for (final MetricsContext metricsCtx : allMetrics.get(id).keySet()) { metricsCtx.refreshLastSnapshot(); } } } catch (final ConcurrentModificationException ignored) { } if (allMetricsLock.tryLock()) { ThreadContext.put(KEY_CLASS_NAME, CLS_NAME); try { int actualConcurrency; int nextConcurrencyThreshold; for (final String id : allMetrics.keySet()) { for (final MetricsContext metricsCtx : allMetrics.get(id).keySet()) { ThreadContext.put(KEY_STEP_ID, metricsCtx.stepId()); actualConcurrency = metricsCtx.actualConcurrency(); //metricsCtx.refreshLastSnapshot(); // threshold load state checks nextConcurrencyThreshold = metricsCtx.concurrencyThreshold(); if (nextConcurrencyThreshold > 0 && actualConcurrency >= nextConcurrencyThreshold) { if (!metricsCtx.thresholdStateEntered() && !metricsCtx.thresholdStateExited()) { Loggers.MSG.info( "{}: the threshold of {} active tasks count is reached, starting the " + "additional metrics accounting", metricsCtx.toString(), metricsCtx.concurrencyThreshold() ); metricsCtx.enterThresholdState(); } } else if (metricsCtx.thresholdStateEntered() && !metricsCtx.thresholdStateExited()) { exitMetricsThresholdState(metricsCtx); } // periodic output outputPeriodMillis = metricsCtx.outputPeriodMillis(); lastOutputTs = metricsCtx.lastOutputTs(); nextOutputTs = System.currentTimeMillis(); if (outputPeriodMillis > 0 && nextOutputTs - lastOutputTs >= outputPeriodMillis) { selectedMetrics.add(metricsCtx); metricsCtx.lastOutputTs(nextOutputTs); if (metricsCtx.avgPersistEnabled()) { Loggers.METRICS_FILE.info(new MetricsCsvLogMessage(metricsCtx)); } } } } // periodic console output if (!selectedMetrics.isEmpty()) { Loggers.METRICS_STD_OUT.info(new MetricsAsciiTableLogMessage(selectedMetrics)); selectedMetrics.clear(); } } catch (final Throwable cause) { LogUtil.exception(Level.DEBUG, cause, "Metrics manager failure"); } finally { allMetricsLock.unlock(); } } } }; private MetricsManager() { } public static void register(final String id, final MetricsContext metricsCtx) throws InterruptedException { if (INSTANCE.allMetricsLock.tryLock(TIMEOUT, TimeUnit.SECONDS)) { try ( final Instance logCtx = put(KEY_STEP_ID, id) .put(KEY_CLASS_NAME, MetricsManager.class.getSimpleName()) ) { if (!INSTANCE.isStarted()) { INSTANCE.start(); Loggers.MSG.debug("Started the metrics manager fiber"); } final Map<MetricsContext, AutoCloseable> stepMetrics = INSTANCE.allMetrics.computeIfAbsent( id, c -> new HashMap<>() ); stepMetrics.put(metricsCtx, new Meter(metricsCtx)); Loggers.MSG.debug("Metrics context \"{}\" registered", metricsCtx); } catch (final Exception e) { LogUtil.exception( Level.WARN, e, "Failed to register the MBean for the metrics context \"{}\"", metricsCtx.toString() ); } finally { INSTANCE.allMetricsLock.unlock(); } } else { Loggers.ERR.warn("Locking timeout at register call, thread dump:\n{}", new ThreadDump().toString()); } } public static void unregister(final String id, final MetricsContext metricsCtx) throws InterruptedException { if (INSTANCE.allMetricsLock.tryLock(TIMEOUT, TimeUnit.SECONDS)) { try ( final Instance stepIdCtx = put(KEY_STEP_ID, id) .put(KEY_CLASS_NAME, MetricsManager.class.getSimpleName()) ) { final Map<MetricsContext, AutoCloseable> stepMetrics = INSTANCE.allMetrics.get(id); if (stepMetrics != null) { metricsCtx.refreshLastSnapshot(); // last time // check for the metrics threshold state if entered if (metricsCtx.thresholdStateEntered() && !metricsCtx.thresholdStateExited()) { exitMetricsThresholdState(metricsCtx); } // file output if (metricsCtx.sumPersistEnabled()) { Loggers.METRICS_FILE_TOTAL.info(new MetricsCsvLogMessage(metricsCtx)); } if (metricsCtx.perfDbResultsFileEnabled()) { Loggers.METRICS_EXT_RESULTS_FILE.info( new ExtResultsXmlLogMessage(metricsCtx) ); } // console output Loggers.METRICS_STD_OUT.info( new MetricsAsciiTableLogMessage(Collections.singleton(metricsCtx), true) ); Loggers.METRICS_STD_OUT.info(new StepResultsMetricsLogMessage(metricsCtx)); final AutoCloseable meterMBean = stepMetrics.remove(metricsCtx); if (meterMBean != null) { try { meterMBean.close(); } catch (final Exception e) { LogUtil.exception(Level.WARN, e, "Failed to close the meter MBean"); } } } else { Loggers.ERR.debug("Metrics context \"{}\" has not been registered", metricsCtx); } if (stepMetrics != null && stepMetrics.size() == 0) { INSTANCE.allMetrics.remove(id); } } finally { if (INSTANCE.allMetrics.size() == 0) { INSTANCE.stop(); Loggers.MSG.debug("Stopped the metrics manager fiber"); } INSTANCE.allMetricsLock.unlock(); Loggers.MSG.debug("Metrics context \"{}\" unregistered", metricsCtx); } } else { Loggers.ERR.warn("Locking timeout at unregister call, thread dump:\n{}", new ThreadDump().toString()); } } private static void exitMetricsThresholdState(final MetricsContext metricsCtx) { Loggers.MSG.info( "{}: the active tasks count is below the threshold of {}, stopping the additional metrics accounting", metricsCtx.toString(), metricsCtx.concurrencyThreshold() ); final MetricsContext lastThresholdMetrics = metricsCtx.thresholdMetrics(); if (lastThresholdMetrics.sumPersistEnabled()) { Loggers.METRICS_THRESHOLD_FILE_TOTAL.info(new MetricsCsvLogMessage(lastThresholdMetrics)); } if (lastThresholdMetrics.perfDbResultsFileEnabled()) { Loggers.METRICS_THRESHOLD_EXT_RESULTS_FILE.info(new ExtResultsXmlLogMessage(lastThresholdMetrics)); } metricsCtx.exitThresholdState(); } @Override protected final void doStart() { try { if (allMetricsLock.tryLock(TIMEOUT, TimeUnit.SECONDS)) { try { task.start(); } catch (final RemoteException ignored) { } finally { allMetricsLock.unlock(); } } else { Loggers.ERR.warn("Locking timeout at starting, thread dump:\n{}", new ThreadDump().toString()); } } catch (final InterruptedException e) { LogUtil.exception(Level.DEBUG, e, "Got interrupted exception"); } } @Override protected final void doShutdown() { } @Override protected final void doStop() { try { if (allMetricsLock.tryLock(TIMEOUT, TimeUnit.SECONDS)) { try { task.stop(); } catch (final RemoteException ignored) { } finally { allMetricsLock.unlock(); } } else { Loggers.ERR.warn("Locking timeout at stopping, thread dump:\n{}", new ThreadDump().toString()); } } catch (final InterruptedException e) { LogUtil.exception(Level.DEBUG, e, "Got interrupted exception"); } } @Override protected final void doClose() { try { if (allMetricsLock.tryLock(TIMEOUT, TimeUnit.SECONDS)) { try { for (final Map<MetricsContext, AutoCloseable> meters : allMetrics.values()) { meters.clear(); } allMetrics.clear(); } finally { allMetricsLock.unlock(); } } else { Loggers.ERR.warn("Locking timeout at closing, thread dump:\n{}", new ThreadDump().toString()); } } catch (final InterruptedException e) { LogUtil.exception(Level.DEBUG, e, "Got interrupted exception"); } } }
package com.etsy.jenkins.cli; import com.etsy.jenkins.MasterProject; import com.etsy.jenkins.SubProjectsAction; import com.etsy.jenkins.SubProjectsJobProperty; import com.etsy.jenkins.cli.handlers.MasterProjectOptionHandler; import com.etsy.jenkins.finder.BuildFinder; import com.etsy.jenkins.finder.ProjectFinder; import hudson.AbortException; import hudson.EnvVars; import hudson.Extension; import hudson.cli.CLICommand; import hudson.console.HyperlinkNote; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Cause; import hudson.model.EnvironmentContributor; import hudson.model.Hudson; import hudson.model.Item; import hudson.model.ParametersAction; import hudson.model.ParameterValue; import hudson.model.ParameterDefinition; import hudson.model.ParametersDefinitionProperty; import hudson.model.Run; import hudson.model.TaskListener; import hudson.model.TopLevelItem; import hudson.model.User; import hudson.util.EditDistance; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; import org.kohsuke.stapler.export.Exported; import com.google.common.base.Objects; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.inject.Inject; import java.io.PrintStream; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Future; @Extension public class BuildMasterCommand extends CLICommand { @Inject static Hudson hudson; @Inject static BuildFinder buildFinder; @Inject static ProjectFinder projectFinder; @Override public String getShortDescription() { return "Builds a try job," + " and optionally waits until its completion."; } @Argument( handler=MasterProjectOptionHandler.class, metaVar="MASTER_JOB", usage="Name of the job to build", required=true) public MasterProject job; @Argument( metaVar="SUB_JOBS", usage="List of sub jobs to execute. If Master Project plugin is" + " installed and the JOB is a Master Project.", index=1, multiValued=true) public List<String> subJobs = Lists.<String>newArrayList(); @Option( name="-s", usage="Wait until the completion/abortion of the command.") public boolean sync = false; @Option( name="-p", usage="Specify the build parameters in the key=value format.") public Map<String, String> parameters = Maps.<String, String>newHashMap(); @Override protected int run() throws Exception { job.checkPermission(Item.BUILD); SubProjectsAction sp = null; SubProjectsJobProperty spjp = (SubProjectsJobProperty) job.getProperty(SubProjectsJobProperty.class); if (!subJobs.isEmpty()) { if (spjp == null) { throw new AbortException( String.format( "%s does not allow sub-job selection but sub-jobs were" + " specified.", job.getDisplayName())); } Set<String> subProjects = Sets.<String>newHashSet(); Set<String> excludeProjects = Sets.<String>newHashSet(); for (String subJob : subJobs) { boolean exclude = false; if (subJob.charAt(0) == '-') { exclude = true; subJob = subJob.substring(1, subJob.length()); } AbstractProject project = projectFinder.findProject(subJob); if (project == null) { throw new AbortException( String.format( "Project does not exist: %s", subJob)); } if (!job.contains((TopLevelItem) project)) { throw new AbortException( String.format( "%s does not exist in Master Project: %s", subJob, job.getDisplayName())); } if (exclude) { excludeProjects.add(subJob); } else { subProjects.add(subJob); } } sp = new SubProjectsAction(subProjects, excludeProjects); } else if (spjp != null) { stdout.println( String.format( "Executing DEFAULT sub-jobs: %s", spjp.getDefaultSubProjectsString())); } ParametersAction a = null; if (!parameters.isEmpty()) { ParametersDefinitionProperty pdp = job.getProperty(ParametersDefinitionProperty.class); if (pdp == null) { throw new AbortException( String.format( "%s is not parameterized but the -p option was specified.", job.getDisplayName())); } List<ParameterValue> values = Lists.<ParameterValue>newArrayList(); for (Map.Entry<String, String> e : parameters.entrySet()) { String name = e.getKey(); ParameterDefinition pd = pdp.getParameterDefinition(name); if (pd == null) { throw new AbortException( String.format( "\'%s\' is not a valid parameter. Did you mean %s?", name, EditDistance.findNearest( name, pdp.getParameterDefinitionNames()))); } values.add(pd.createValue(this, e.getValue())); } // handle missing parameters by adding as default values ISSUE JENKINS-7162 for (ParameterDefinition pd : pdp.getParameterDefinitions()) { if (parameters.containsKey(pd.getName())) continue; // not passed in use default values.add(pd.getDefaultParameterValue()); } a = new ParametersAction(values); } String user = Hudson.getAuthentication().getName(); CLICause cause = new CLICause(user, a, sp); Future<? extends AbstractBuild> f = job.scheduleBuild2(0, cause, a, sp); AbstractBuild build = null; do { build = buildFinder.findBuild(job, cause); stdout.println( String.format("......... %s ( pending )", job.getDisplayName())); rest(); } while(build == null); stdout.println( String.format("......... %s ( %s%s )", job.getDisplayName(), hudson.getRootUrl(), build.getUrl())); build.setDescription("<h2>" + cause.getUserName() + "</h2>"); if (!sync) return 0; AbstractBuild b = f.get(); // wait for completion stdout.println( String.format( "Completed %s : %s", b.getFullDisplayName(), b.getResult())); return b.getResult().ordinal; } private void rest() { try { Thread.sleep(7000L); } catch (InterruptedException ignore) {} } @Override protected void printUsageSummary(PrintStream stderr) { stderr.println( "Starts a master job, and optionally waits for a completion.\n\n" + "Aside from general scripting use, this command can be\n" + "used to invoke another job from within a build of one job.\n" + "With the -s option, this command changes the exit code based on\n" + "the outcome of the build (exit code 0 indicates success.)\n"); } public static class CLICause extends Cause { private final String user; private final ParametersAction parameters; private final SubProjectsAction subProjects; public CLICause( String user, ParametersAction parameters, SubProjectsAction subProjects) { this.user = user; this.parameters = parameters; this.subProjects = subProjects; } @Exported(visibility=3) public String getUserName() { User u = User.get(user, false); return (u == null) ? user : u.getDisplayName(); } @Exported(visibility=3) public String getUserUrl() { User u = User.get(user, false); if (u == null) { u = User.getUnknown(); } return u.getAbsoluteUrl(); } @Override public String getShortDescription() { return "Started by command line"; } @Override public void print(TaskListener listener) { listener.getLogger().println(String.format( "Started by command line for %s\n", HyperlinkNote.encodeTo(getUserUrl(), getUserName()))); } @Override public boolean equals(Object o) { if (!(o instanceof CLICause)) { return false; } CLICause other = (CLICause) o; return Objects.equal(this.user, other.user) && Objects.equal(this.parameters, other.parameters) && Objects.equal(this.subProjects, other.subProjects); } @Override public int hashCode() { return Objects.hashCode(this.user, this.parameters, this.subProjects); } } @Extension public static class CLIEnvironmentContributor extends EnvironmentContributor { @Override public void buildEnvironmentFor(Run r, EnvVars envs, TaskListener listener) { CLICause cause = (CLICause) r.getCause(CLICause.class); if (cause == null) return; envs.put("TRIGGERING_USER", cause.getUserName()); } } }
package com.faforever.client.fx; import com.google.common.collect.Sets; import com.sun.jna.Platform; import com.sun.jna.platform.win32.User32; import com.sun.jna.platform.win32.WinDef.HWND; import com.sun.jna.platform.win32.WinUser; import com.sun.jna.platform.win32.WinUser.WINDOWPLACEMENT; import javafx.application.HostServices; import lombok.SneakyThrows; import org.apache.commons.lang3.SystemUtils; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermission; import java.util.regex.Pattern; import static com.github.nocatch.NoCatch.noCatch; import static org.bridj.Platform.show; public class PlatformService { public static final Pattern URL_REGEX_PATTERN = Pattern.compile("^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"); private final HostServices hostServices; private final boolean isWindows; public PlatformService(HostServices hostServices) { this.hostServices = hostServices; isWindows = Platform.isWindows(); } /** * Opens the specified URI in a new browser window or tab. */ public void showDocument(String url) { hostServices.showDocument(url); } /** * Show a file in its parent directory, if possible selecting the file (not possible on all platforms). */ @SneakyThrows public void reveal(Path path) { if (isWindows) { Path finalPath = path; noCatch(() -> show(finalPath.toFile())); } else if (Platform.isLinux()) { //Might not work on all linux distros but let's give it a try if (Files.isRegularFile(path)) { path = path.getParent(); } ProcessBuilder builder = new ProcessBuilder("xdg-open", path.toAbsolutePath().toString()); builder.start(); } } /** * Show a Window, restore it to it's state before minimizing (normal/restored or maximized) and move it to foreground * will only work on windows systems */ public void focusWindow(String windowTitle) { if (!isWindows) { return; } User32 user32 = User32.INSTANCE; HWND window = user32.FindWindow(null, windowTitle); // Does only set the window to visible, does not restore/bring it to foreground user32.ShowWindow(window, User32.SW_SHOW); WINDOWPLACEMENT windowplacement = new WINDOWPLACEMENT(); user32.GetWindowPlacement(window, windowplacement); if (windowplacement.showCmd == User32.SW_SHOWMINIMIZED) { // Bit 2 in flags (bitmask 0x2) signals that window should be maximized when restoring if ((windowplacement.flags & WINDOWPLACEMENT.WPF_RESTORETOMAXIMIZED) == WINDOWPLACEMENT.WPF_RESTORETOMAXIMIZED) { user32.ShowWindow(window, User32.SW_SHOWMAXIMIZED); } else { user32.ShowWindow(window, User32.SW_SHOWNORMAL); } } String foregroundWindowTitle = getForegroundWindowTitle(); if (foregroundWindowTitle == null || !getForegroundWindowTitle().equals(windowTitle.trim())) { user32.SetForegroundWindow(window); } } public void startFlashingWindow(String windowTitle) { if (!isWindows) { return; } HWND window = User32.INSTANCE.FindWindow(null, windowTitle); WinUser.FLASHWINFO flashwinfo = new WinUser.FLASHWINFO(); flashwinfo.hWnd = window; flashwinfo.dwFlags = WinUser.FLASHW_TRAY; flashwinfo.uCount = Integer.MAX_VALUE; flashwinfo.dwTimeout = 500; flashwinfo.cbSize = flashwinfo.size(); User32.INSTANCE.FlashWindowEx(flashwinfo); } public void stopFlashingWindow(String windowTitle) { if (!isWindows) { return; } HWND window = User32.INSTANCE.FindWindow(null, windowTitle); WinUser.FLASHWINFO flashwinfo = new WinUser.FLASHWINFO(); flashwinfo.hWnd = window; flashwinfo.dwFlags = WinUser.FLASHW_STOP; flashwinfo.cbSize = flashwinfo.size(); User32.INSTANCE.FlashWindowEx(flashwinfo); } @Nullable private String getForegroundWindowTitle() { if (!isWindows) { return null; } HWND window = User32.INSTANCE.GetForegroundWindow(); if (window == null) { return null; } char[] textBuffer = new char[255]; User32.INSTANCE.GetWindowText(window, textBuffer, 255); return new String(textBuffer).trim(); } public boolean isWindowFocused(String windowTitle) { return windowTitle.equals(getForegroundWindowTitle()); } public void setUnixExecutableAndWritableBits(Path exePath) throws IOException { // client needs executable bit for running and the writeable bit set to alter the version if (SystemUtils.IS_OS_UNIX) { Files.setPosixFilePermissions(exePath, Sets.immutableEnumSet(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE)); } } }
package com.github.mnicky.bible4j.data; /** * Class representing position (coordinates) in the Bible. */ public final class Position implements Comparable<Position> { /** * Bible Book. */ private final BibleBook book; /** * Chapter number. */ private final int chapterNum; /** * Verse number. */ private final int verseNum; /** * Constructs new Position with specified Bible book, chapter number and verse number. * @param book bible book * @param chapterNum chapter number * @param verseNum verse number */ public Position(BibleBook book, int chapterNum, int verseNum) { this.book = book; this.chapterNum = chapterNum; this.verseNum = verseNum; } /** * Returns the string representation of this Position. * The representation format is subject to change, * but the following may be regarded as typical: * * "MATTHEW 6,14" * * @return string representation of this Position */ @Override public String toString() { return book + " " + chapterNum + "," + verseNum; } /** * Indicates whether the provided object equals to this Position object. * @param obj object to compare this Position object with * * @return true if this Position object equals to provided */ @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof Position)) return false; Position pos = (Position) obj; return pos.book == this.book && pos.chapterNum == this.chapterNum && pos.verseNum == this.verseNum; } /** * Returns a hash code for this Position. * * @return a hash code for this Position */ @Override public int hashCode() { int result = 17; result = 31 * result + (book == null ? 0 : book.hashCode()); result = 31 * result + (Integer.valueOf(chapterNum).hashCode()); result = 31 * result + (Integer.valueOf(verseNum).hashCode()); return result; } public BibleBook getBook() { return book; } public int getChapterNum() { return chapterNum; } public int getVerseNum() { return verseNum; } @Override public int compareTo(Position p) { if (this.book.ordinal() > p.book.ordinal()) return 1; else if (this.book.ordinal() == p.book.ordinal()) { if (this.chapterNum > p.chapterNum) return 1; else if (this.chapterNum == p.chapterNum) { if (this.verseNum > p.verseNum) return 1; else if (this.verseNum == p.verseNum) return 0; else return -1; } else return -1; } else return -1; } }
package com.gocardless.resources; import com.google.gson.annotations.SerializedName; import java.util.List; import java.util.Map; public class BillingRequest { private BillingRequest() { // blank to prevent instantiation } private List<Action> actions; private String createdAt; private Boolean fallbackEnabled; private String id; private Links links; private MandateRequest mandateRequest; private Map<String, String> metadata; private PaymentRequest paymentRequest; private Resources resources; private Status status; /** * List of actions that can be performed before this billing request can be fulfilled. */ public List<Action> getActions() { return actions; } /** * Fixed [timestamp](#api-usage-time-zones--dates), recording when this resource was created. */ public String getCreatedAt() { return createdAt; } public Boolean getFallbackEnabled() { return fallbackEnabled; } /** * Unique identifier, beginning with "BRQ". */ public String getId() { return id; } public Links getLinks() { return links; } /** * Request for a mandate */ public MandateRequest getMandateRequest() { return mandateRequest; } /** * Key-value store of custom data. Up to 3 keys are permitted, with key names up to 50 * characters and values up to 500 characters. */ public Map<String, String> getMetadata() { return metadata; } /** * Request for a one-off strongly authorised payment */ public PaymentRequest getPaymentRequest() { return paymentRequest; } public Resources getResources() { return resources; } /** * One of: * <ul> * <li>`pending`: the billing request is pending and can be used</li> * <li>`ready_to_fulfil`: the billing request is ready to fulfil</li> * <li>`fulfilling`: the billing request is currently undergoing fulfilment</li> * <li>`fulfilled`: the billing request has been fulfilled and a payment created</li> * <li>`cancelled`: the billing request has been cancelled and cannot be used</li> * </ul> */ public Status getStatus() { return status; } public enum Status { @SerializedName("pending") PENDING, @SerializedName("ready_to_fulfil") READY_TO_FULFIL, @SerializedName("fulfilling") FULFILLING, @SerializedName("fulfilled") FULFILLED, @SerializedName("cancelled") CANCELLED, @SerializedName("unknown") UNKNOWN } public static class Action { private Action() { // blank to prevent instantiation } private List<String> availableCurrencies; private BankAuthorisation bankAuthorisation; private CollectCustomerDetails collectCustomerDetails; private List<String> completesActions; private Boolean required; private List<String> requiresActions; private Status status; private Type type; /** * List of currencies the current mandate supports */ public List<String> getAvailableCurrencies() { return availableCurrencies; } /** * Describes the behaviour of bank authorisations, for the bank_authorisation action */ public BankAuthorisation getBankAuthorisation() { return bankAuthorisation; } /** * Additional parameters to help complete the collect_customer_details action */ public CollectCustomerDetails getCollectCustomerDetails() { return collectCustomerDetails; } /** * Which other action types this action can complete. */ public List<String> getCompletesActions() { return completesActions; } /** * Informs you whether the action is required to fulfil the billing request or not. */ public Boolean getRequired() { return required; } /** * Requires completing these actions before this action can be completed. */ public List<String> getRequiresActions() { return requiresActions; } /** * Status of the action */ public Status getStatus() { return status; } /** * Unique identifier for the action. */ public Type getType() { return type; } public enum Status { @SerializedName("pending") PENDING, @SerializedName("completed") COMPLETED, @SerializedName("unknown") UNKNOWN } public enum Type { @SerializedName("choose_currency") CHOOSE_CURRENCY, @SerializedName("collect_customer_details") COLLECT_CUSTOMER_DETAILS, @SerializedName("collect_bank_account") COLLECT_BANK_ACCOUNT, @SerializedName("bank_authorisation") BANK_AUTHORISATION, @SerializedName("confirm_payer_details") CONFIRM_PAYER_DETAILS, @SerializedName("select_institution") SELECT_INSTITUTION, @SerializedName("unknown") UNKNOWN } /** * Represents a available currency resource returned from the API. * * List of currencies the current mandate supports */ public static class AvailableCurrencies { private AvailableCurrencies() { // blank to prevent instantiation } private String currency; public String getCurrency() { return currency; } } /** * Represents a bank authorisation resource returned from the API. * * Describes the behaviour of bank authorisations, for the bank_authorisation action */ public static class BankAuthorisation { private BankAuthorisation() { // blank to prevent instantiation } private Adapter adapter; private AuthorisationType authorisationType; private Boolean requiresInstitution; /** * Which authorisation adapter will be used to power these authorisations (GoCardless * internal use only) */ public Adapter getAdapter() { return adapter; } /** * What type of bank authorisations are supported on this billing request */ public AuthorisationType getAuthorisationType() { return authorisationType; } /** * Whether an institution is a required field when creating this bank authorisation */ public Boolean getRequiresInstitution() { return requiresInstitution; } public enum Adapter { @SerializedName("open_banking_gateway_pis") OPEN_BANKING_GATEWAY_PIS, @SerializedName("plaid_ais") PLAID_AIS, @SerializedName("open_banking_gateway_ais") OPEN_BANKING_GATEWAY_AIS, @SerializedName("bankid_ais") BANKID_AIS, @SerializedName("unknown") UNKNOWN } public enum AuthorisationType { @SerializedName("payment") PAYMENT, @SerializedName("mandate") MANDATE, @SerializedName("unknown") UNKNOWN } } /** * Represents a collect customer detail resource returned from the API. * * Additional parameters to help complete the collect_customer_details action */ public static class CollectCustomerDetails { private CollectCustomerDetails() { // blank to prevent instantiation } private String defaultCountryCode; /** * Default customer country code, as determined by scheme and payer location */ public String getDefaultCountryCode() { return defaultCountryCode; } } } public static class Links { private Links() { // blank to prevent instantiation } private String bankAuthorisation; private String creditor; private String customer; private String customerBankAccount; private String customerBillingDetail; private String mandateRequest; private String mandateRequestMandate; private String paymentRequest; private String paymentRequestPayment; /** * (Optional) ID of the [bank authorisation](#billing-requests-bank-authorisations) that was * used to verify this request. */ public String getBankAuthorisation() { return bankAuthorisation; } /** * ID of the associated [creditor](#core-endpoints-creditors). */ public String getCreditor() { return creditor; } /** * ID of the [customer](#core-endpoints-customers) that will be used for this request */ public String getCustomer() { return customer; } /** * (Optional) ID of the [customer_bank_account](#core-endpoints-customer-bank-accounts) that * will be used for this request */ public String getCustomerBankAccount() { return customerBankAccount; } /** * ID of the customer billing detail that will be used for this request */ public String getCustomerBillingDetail() { return customerBillingDetail; } /** * (Optional) ID of the associated mandate request */ public String getMandateRequest() { return mandateRequest; } /** * (Optional) ID of the [mandate](#core-endpoints-mandates) that was created from this * mandate request. this mandate request. */ public String getMandateRequestMandate() { return mandateRequestMandate; } /** * (Optional) ID of the associated payment request */ public String getPaymentRequest() { return paymentRequest; } /** * (Optional) ID of the [payment](#core-endpoints-payments) that was created from this * payment request. */ public String getPaymentRequestPayment() { return paymentRequestPayment; } } /** * Represents a mandate request resource returned from the API. * * Request for a mandate */ public static class MandateRequest { private MandateRequest() { // blank to prevent instantiation } private String currency; private Links links; private Map<String, String> metadata; private String scheme; private Verify verify; public String getCurrency() { return currency; } public Links getLinks() { return links; } /** * Key-value store of custom data. Up to 3 keys are permitted, with key names up to 50 * characters and values up to 500 characters. */ public Map<String, String> getMetadata() { return metadata; } /** * A Direct Debit scheme. Currently "ach", "bacs", "becs", "becs_nz", "betalingsservice", * "pad" and "sepa_core" are supported. */ public String getScheme() { return scheme; } public Verify getVerify() { return verify; } public enum Verify { @SerializedName("minimum") MINIMUM, @SerializedName("recommended") RECOMMENDED, @SerializedName("when_available") WHEN_AVAILABLE, @SerializedName("always") ALWAYS, @SerializedName("unknown") UNKNOWN } public static class Links { private Links() { // blank to prevent instantiation } private String mandate; /** * (Optional) ID of the [mandate](#core-endpoints-mandates) that was created from this * mandate request. this mandate request. * */ public String getMandate() { return mandate; } } } /** * Represents a payment request resource returned from the API. * * Request for a one-off strongly authorised payment */ public static class PaymentRequest { private PaymentRequest() { // blank to prevent instantiation } private Integer amount; private Integer appFee; private String currency; private String description; private Links links; private Map<String, String> metadata; private String scheme; /** * Amount in minor unit (e.g. pence in GBP, cents in EUR). */ public Integer getAmount() { return amount; } /** * The amount to be deducted from the payment as an app fee, to be paid to the partner * integration which created the billing request, in the lowest denomination for the * currency (e.g. pence in GBP, cents in EUR). */ public Integer getAppFee() { return appFee; } public String getCurrency() { return currency; } /** * A human-readable description of the payment. This will be displayed to the payer when * authorising the billing request. * */ public String getDescription() { return description; } public Links getLinks() { return links; } /** * Key-value store of custom data. Up to 3 keys are permitted, with key names up to 50 * characters and values up to 500 characters. */ public Map<String, String> getMetadata() { return metadata; } /** * (Optional) A scheme used for Open Banking payments. Currently `faster_payments` is * supported in the UK (GBP) and `sepa_credit_transfer` and `sepa_instant_credit_transfer` * are supported in Germany (EUR). In Germany, `sepa_credit_transfer` is used as the * default. Please be aware that `sepa_instant_credit_transfer` may incur an additional fee * for your customer. */ public String getScheme() { return scheme; } public static class Links { private Links() { // blank to prevent instantiation } private String payment; /** * (Optional) ID of the [payment](#core-endpoints-payments) that was created from this * payment request. */ public String getPayment() { return payment; } } } public static class Resources { private Resources() { // blank to prevent instantiation } private Customer customer; private CustomerBankAccount customerBankAccount; private CustomerBillingDetail customerBillingDetail; /** * Embedded customer */ public Customer getCustomer() { return customer; } /** * Embedded customer bank account, only if a bank account is linked */ public CustomerBankAccount getCustomerBankAccount() { return customerBankAccount; } /** * Embedded customer billing detail */ public CustomerBillingDetail getCustomerBillingDetail() { return customerBillingDetail; } /** * Represents a customer resource returned from the API. * * Embedded customer */ public static class Customer { private Customer() { // blank to prevent instantiation } private String companyName; private String createdAt; private String email; private String familyName; private String givenName; private String id; private String language; private Map<String, String> metadata; private String phoneNumber; /** * Customer's company name. Required unless a `given_name` and `family_name` are * provided. For Canadian customers, the use of a `company_name` value will mean that * any mandate created from this customer will be considered to be a "Business PAD" * (otherwise, any mandate will be considered to be a "Personal PAD"). */ public String getCompanyName() { return companyName; } /** * Fixed [timestamp](#api-usage-time-zones--dates), recording when this resource was * created. */ public String getCreatedAt() { return createdAt; } /** * Customer's email address. Required in most cases, as this allows GoCardless to send * notifications to this customer. */ public String getEmail() { return email; } /** * Customer's surname. Required unless a `company_name` is provided. */ public String getFamilyName() { return familyName; } /** * Customer's first name. Required unless a `company_name` is provided. */ public String getGivenName() { return givenName; } /** * Unique identifier, beginning with "CU". */ public String getId() { return id; } public String getLanguage() { return language; } /** * Key-value store of custom data. Up to 3 keys are permitted, with key names up to 50 * characters and values up to 500 characters. */ public Map<String, String> getMetadata() { return metadata; } public String getPhoneNumber() { return phoneNumber; } } /** * Represents a customer bank account resource returned from the API. * * Embedded customer bank account, only if a bank account is linked */ public static class CustomerBankAccount { private CustomerBankAccount() { // blank to prevent instantiation } private String accountHolderName; private String accountNumberEnding; private AccountType accountType; private String bankName; private String countryCode; private String createdAt; private String currency; private Boolean enabled; private String id; private Links links; private Map<String, String> metadata; /** * Name of the account holder, as known by the bank. Usually this is the same as the * name stored with the linked [creditor](#core-endpoints-creditors). This field will be * transliterated, upcased and truncated to 18 characters. This field is required unless * the request includes a [customer bank account * token](#javascript-flow-customer-bank-account-tokens). */ public String getAccountHolderName() { return accountHolderName; } /** * The last few digits of the account number. Currently 4 digits for NZD bank accounts * and 2 digits for other currencies. */ public String getAccountNumberEnding() { return accountNumberEnding; } /** * Bank account type. Required for USD-denominated bank accounts. Must not be provided * for bank accounts in other currencies. See [local * details](#local-bank-details-united-states) for more information. */ public AccountType getAccountType() { return accountType; } /** * Name of bank, taken from the bank details. */ public String getBankName() { return bankName; } public String getCountryCode() { return countryCode; } /** * Fixed [timestamp](#api-usage-time-zones--dates), recording when this resource was * created. */ public String getCreatedAt() { return createdAt; } public String getCurrency() { return currency; } /** * Boolean value showing whether the bank account is enabled or disabled. */ public Boolean getEnabled() { return enabled; } /** * Unique identifier, beginning with "BA". */ public String getId() { return id; } public Links getLinks() { return links; } /** * Key-value store of custom data. Up to 3 keys are permitted, with key names up to 50 * characters and values up to 500 characters. */ public Map<String, String> getMetadata() { return metadata; } public enum AccountType { @SerializedName("savings") SAVINGS, @SerializedName("checking") CHECKING, @SerializedName("unknown") UNKNOWN } public static class Links { private Links() { // blank to prevent instantiation } private String customer; /** * ID of the [customer](#core-endpoints-customers) that owns this bank account. */ public String getCustomer() { return customer; } } } /** * Represents a customer billing detail resource returned from the API. * * Embedded customer billing detail */ public static class CustomerBillingDetail { private CustomerBillingDetail() { // blank to prevent instantiation } private String addressLine1; private String addressLine2; private String addressLine3; private String city; private String countryCode; private String createdAt; private String danishIdentityNumber; private String id; private String ipAddress; private String postalCode; private String region; private List<String> schemes; private String swedishIdentityNumber; /** * The first line of the customer's address. */ public String getAddressLine1() { return addressLine1; } /** * The second line of the customer's address. */ public String getAddressLine2() { return addressLine2; } /** * The third line of the customer's address. */ public String getAddressLine3() { return addressLine3; } /** * The city of the customer's address. */ public String getCity() { return city; } public String getCountryCode() { return countryCode; } /** * Fixed [timestamp](#api-usage-time-zones--dates), recording when this resource was * created. */ public String getCreatedAt() { return createdAt; } /** * For Danish customers only. The civic/company number (CPR or CVR) of the customer. * Must be supplied if the customer's bank account is denominated in Danish krone (DKK). */ public String getDanishIdentityNumber() { return danishIdentityNumber; } /** * Unique identifier, beginning with "CU". */ public String getId() { return id; } /** * For ACH customers only. Required for ACH customers. A string containing the IP * address of the payer to whom the mandate belongs (i.e. as a result of their * completion of a mandate setup flow in their browser). */ public String getIpAddress() { return ipAddress; } /** * The customer's postal code. */ public String getPostalCode() { return postalCode; } public String getRegion() { return region; } /** * The schemes associated with this customer billing detail */ public List<String> getSchemes() { return schemes; } /** * For Swedish customers only. The civic/company number (personnummer, * samordningsnummer, or organisationsnummer) of the customer. Must be supplied if the * customer's bank account is denominated in Swedish krona (SEK). This field cannot be * changed once it has been set. */ public String getSwedishIdentityNumber() { return swedishIdentityNumber; } } } }
package com.inari.firefly.physics.gravity; import java.util.Set; import com.inari.commons.JavaUtils; import com.inari.firefly.component.attr.AttributeKey; import com.inari.firefly.component.attr.AttributeMap; import com.inari.firefly.entity.EntityComponent; public final class EMass extends EntityComponent { public static final EntityComponentTypeKey<EMass> TYPE_KEY = EntityComponentTypeKey.create( EMass.class ); public static final AttributeKey<Float> MASS = AttributeKey.createFloat( "mass", EMass.class ); public static final AttributeKey<Boolean> ON_GROUND = AttributeKey.createBoolean( "onGround", EMass.class ); public static final AttributeKey<Boolean> ACTIVE = AttributeKey.createBoolean( "noGravityAspects", EMass.class ); public static final Set<AttributeKey<?>> ATTRIBUTE_KEYS = JavaUtils.<AttributeKey<?>>unmodifiableSet( MASS, ON_GROUND, ACTIVE ); float mass; boolean onGround; boolean active; long fallingStartTime; protected EMass() { super( TYPE_KEY ); } @Override public final void resetAttributes() { mass = 0f; onGround = false; active = false; } public final float getMass() { return mass; } public final void setMass( float mass ) { this.mass = mass; } public final boolean isOnGround() { return onGround; } public final void setOnGround( boolean onGround ) { this.onGround = onGround; } public final boolean isActive() { return active; } public final void setActive( boolean active ) { this.active = active; } @Override public final Set<AttributeKey<?>> attributeKeys() { return ATTRIBUTE_KEYS; } @Override public final void fromAttributes( AttributeMap attributes ) { mass = attributes.getValue( MASS, mass ); onGround = attributes.getValue( ON_GROUND, onGround ); active = attributes.getValue( ACTIVE, active ); } @Override public final void toAttributes( AttributeMap attributes ) { attributes.put( MASS, mass ); attributes.put( ON_GROUND, onGround ); attributes.put( ACTIVE, active ); } }
package com.jcabi.w3c; import com.jcabi.log.Logger; import java.net.URI; import java.nio.charset.Charset; import java.util.Collections; import java.util.HashSet; import java.util.Set; import lombok.EqualsAndHashCode; /** * Default implementaiton of validation response. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ */ @EqualsAndHashCode( of = { "ivalid", "validator", "type", "encoding", "ierrors", "iwarnings" } ) final class DefaultValidationResponse implements ValidationResponse { /** * Is it valid? */ private final transient boolean ivalid; /** * Who validated it? */ private final transient URI validator; /** * DOCTYPE of the document. */ private final transient String type; /** * The encoding. */ private final transient Charset encoding; /** * Set of errors found. */ private final transient Set<Defect> ierrors = new HashSet<Defect>(0); /** * Set of warnings found. */ private final transient Set<Defect> iwarnings = new HashSet<Defect>(0); /** * Public ctor. * @param val The document is valid? * @param server Who validated it? * @param tpe DOCTYPE of the document * @param enc Charset of the document * @checkstyle ParameterNumber (3 lines) */ DefaultValidationResponse(final boolean val, final URI server, final String tpe, final Charset enc) { this.ivalid = val; this.validator = server; this.type = tpe; this.encoding = enc; } @Override public String toString() { return new StringBuilder(0) .append(Logger.format("Validity: %B\n", this.ivalid)) .append(Logger.format("Validator: \"%s\"\n", this.validator)) .append(Logger.format("DOCTYPE: \"%s\"\n", this.type)) .append(Logger.format("Charset: \"%s\"\n", this.encoding)) .append("Errors:\n").append(this.asText(this.ierrors)) .append("Warnings:\n").append(this.asText(this.iwarnings)) .toString(); } @Override public boolean valid() { return this.ivalid; } @Override public URI checkedBy() { return this.validator; } @Override public String doctype() { return this.type; } @Override public Charset charset() { return this.encoding; } @Override public Set<Defect> errors() { return Collections.unmodifiableSet(this.ierrors); } @Override public Set<Defect> warnings() { return Collections.unmodifiableSet(this.iwarnings); } /** * Add error. * @param error The error to add */ public void addError(final Defect error) { this.ierrors.add(error); } /** * Add warning. * @param warning The warning to add */ public void addWarning(final Defect warning) { this.iwarnings.add(warning); } /** * Convert list of defects into string. * @param defects Set of them * @return The text */ private String asText(final Set<Defect> defects) { final StringBuilder text = new StringBuilder(0); for (final Defect defect : defects) { text.append(" ").append(defect.toString()).append('\n'); } return text.toString(); } }
package cpw.mods.fml.common.event; import net.minecraft.server.MinecraftServer; import net.minecraft.src.CommandHandler; import net.minecraft.src.ICommand; import cpw.mods.fml.common.LoaderState.ModState; public class FMLServerStartingEvent extends FMLStateEvent { private MinecraftServer server; public FMLServerStartingEvent(Object... data) { super(data); this.server = (MinecraftServer) data[0]; } @Override public ModState getModState() { return ModState.AVAILABLE; } public MinecraftServer getServer() { return server; } public void registerServerCommand(ICommand command) { CommandHandler ch = (CommandHandler) getServer().func_71187_D(); ch.func_71560_a(command); } }
package com.jcabi.w3c; import com.jcabi.log.Logger; import java.net.URI; import java.nio.charset.Charset; import java.util.Collections; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import lombok.EqualsAndHashCode; /** * Default implementaiton of validation response. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ */ @EqualsAndHashCode( of = { "ivalid", "validator", "type", "encoding", "ierrors", "iwarnings" } ) final class DefaultValidationResponse implements ValidationResponse { /** * Is it valid? */ private final transient boolean ivalid; /** * Who validated it? */ private final transient URI validator; /** * DOCTYPE of the document. */ private final transient String type; /** * The encoding. */ private final transient Charset encoding; /** * Set of errors found. */ private final transient Set<Defect> ierrors = new CopyOnWriteArraySet<Defect>(); /** * Set of warnings found. */ private final transient Set<Defect> iwarnings = new CopyOnWriteArraySet<Defect>(); /** * Public ctor. * @param val The document is valid? * @param server Who validated it? * @param tpe DOCTYPE of the document * @param enc Charset of the document * @checkstyle ParameterNumber (3 lines) */ DefaultValidationResponse(final boolean val, final URI server, final String tpe, final Charset enc) { this.ivalid = val; this.validator = server; this.type = tpe; this.encoding = enc; } @Override public String toString() { return new StringBuilder(0) .append(Logger.format("Validity: %B\n", this.ivalid)) .append(Logger.format("Validator: \"%s\"\n", this.validator)) .append(Logger.format("DOCTYPE: \"%s\"\n", this.type)) .append(Logger.format("Charset: \"%s\"\n", this.encoding)) .append("Errors:\n").append(this.asText(this.ierrors)) .append("Warnings:\n").append(this.asText(this.iwarnings)) .toString(); } @Override public boolean valid() { return this.ivalid; } @Override public URI checkedBy() { return this.validator; } @Override public String doctype() { return this.type; } @Override public Charset charset() { return this.encoding; } @Override public Set<Defect> errors() { return Collections.unmodifiableSet(this.ierrors); } @Override public Set<Defect> warnings() { return Collections.unmodifiableSet(this.iwarnings); } /** * Add error. * @param error The error to add */ public void addError(final Defect error) { this.ierrors.add(error); } /** * Add warning. * @param warning The warning to add */ public void addWarning(final Defect warning) { this.iwarnings.add(warning); } /** * Convert list of defects into string. * @param defects Set of them * @return The text */ private String asText(final Set<Defect> defects) { final StringBuilder text = new StringBuilder(0); for (final Defect defect : defects) { text.append(" ").append(defect.toString()).append('\n'); } return text.toString(); } }
package com.justjournal.ctl.api; import com.justjournal.Login; import com.justjournal.model.Comment; import com.justjournal.model.Entry; import com.justjournal.model.User; import com.justjournal.repository.*; import com.justjournal.services.EntryService; import com.justjournal.services.ServiceException; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.cache.annotation.CacheEvict; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.transaction.Transactional; import java.util.*; /** * Entry Controller, for managing blog entries * * @author Lucas Holt */ @Controller @RequestMapping("/api/entry") public class EntryController { private static final Logger log = Logger.getLogger(EntryController.class); @Qualifier("commentRepository") @Autowired private CommentRepository commentDao = null; @Qualifier("entryRepository") @Autowired private EntryRepository entryDao = null; @Qualifier("securityDao") @Autowired private SecurityDao securityDao; @Qualifier("locationDao") @Autowired private LocationDao locationDao; @Qualifier("moodDao") @Autowired private MoodDao moodDao; @Qualifier("userRepository") @Autowired private UserRepository userRepository; @Autowired private EntryService entryService; public static Logger getLog() { return log; } @RequestMapping(value = "{username}/size/{size}/page/{page}", method = RequestMethod.GET, produces = "application/json") public @ResponseBody Page<Entry> getEntries(@PathVariable("username") String username, @PathVariable("size") int size, @PathVariable("page") int page, HttpServletResponse response, HttpSession session) { Page<Entry> entries; Pageable pageable = new PageRequest(page, size); try { if (Login.isAuthenticated(session) && Login.isUserName(username)) { entries = entryService.getEntries(username, pageable); } else { entries = entryService.getPublicEntries(username, pageable); } if (entries == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return null; } return entries; } catch (ServiceException e) { log.error(e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } } /** * Get an individual entry * * @param id entry id * @return entry */ @RequestMapping(value = "{username}/eid/{id}", method = RequestMethod.GET, produces = "application/json") @ResponseBody public Entry getById(@PathVariable("username") String username, @PathVariable("id") int id, HttpServletResponse response) { try { Entry entry = entryDao.findOne(id); if (entry == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return null; } if (entry.getUser().getUsername().equalsIgnoreCase(username)) { if (entry.getSecurity().getId() == 2) // public return entry; else response.setStatus(HttpServletResponse.SC_FORBIDDEN); return null; } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return null; } } catch (Exception e) { log.error(e.getMessage()); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } } /** * Get all the blog entries for a user (public) /api/entry/username * * @param username * @param response * @return */ @RequestMapping(value = "{username}", method = RequestMethod.GET, produces = "application/json") public @ResponseBody Collection<Entry> getEntries(@PathVariable("username") String username, HttpServletResponse response) { Collection<Entry> entries = null; try { entries = entryService.getPublicEntries(username); if (entries == null || entries.isEmpty()) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return null; } } catch (ServiceException e) { log.error(e.getMessage()); } return entries; } @Transactional(Transactional.TxType.REQUIRED) @RequestMapping(value = "", params = "username", method = RequestMethod.GET, produces = "application/json") public @ResponseBody Collection<Entry> getEntriesByUsername(@RequestParam("username") String username, HttpServletResponse response) { Collection<Entry> entries = new ArrayList<Entry>(); log.warn("in entriesByUsername with " + username); if (username == null || username.isEmpty()) { log.trace("Username was null or empty "); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return entries; } try { entries = entryService.getPublicEntries(username); if (entries == null || entries.isEmpty()) { log.warn("entries is null or empty"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } catch (Exception e) { log.error("error is happening " + e.getMessage()); } return entries; } public UserRepository getUserRepository() { return userRepository; } public void setUserRepository(final UserRepository userRepository) { this.userRepository = userRepository; } /** * Creates a new entry resource * * @param entry EntryTo * @param session HttpSession * @param response HttpServletResponse * @return status ok or error */ @CacheEvict(value = "recentblogs") @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json", headers = {"Accept=*/*", "content-type=application/json"}) public @ResponseBody Map<String, String> post(@ModelAttribute Entry entry, HttpSession session, HttpServletResponse response, Model model) { if (!Login.isAuthenticated(session)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return Collections.singletonMap("error", "The login timed out or is invalid."); } User user = userRepository.findOne(Login.currentLoginId(session)); if (user == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return Collections.singletonMap("error", "User not found"); } entry.setUser(user); if (entry.getLocation() == null) entry.setLocation(locationDao.findOne(0)); if (entry.getSecurity() == null) entry.setSecurity(securityDao.findOne(0)); if (entry.getMood() == null) entry.setMood(moodDao.findOne(12)); // not specified if (entry.getDate() == null) entry.setDate(new Date()); // TODO: validate Entry saved = entryDao.save(entry); if (saved.getId() < 1) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return Collections.singletonMap("error", "Could not save entry"); } model.addAttribute("status", "ok"); model.addAttribute("id", saved.getId()); // return java.util.Collections.singletonMap("id", Integer.toString(entry.getId())); HashMap<String, String> map = new HashMap<String, String>(); map.put("status", "ok"); map.put("id", Integer.toString(saved.getId())); return map; } /** * PUT generally allows for add or edit in REST. * * @param entry User's Blog entry * @param session HttpSession * @param response HttpServletResponse * @return */ @CacheEvict(value = "recentblogs") @RequestMapping(method = RequestMethod.PUT, consumes = "application/json", produces = "application/json") public @ResponseBody Map<String, String> put(@RequestBody Entry entry, HttpSession session, HttpServletResponse response) { if (!Login.isAuthenticated(session)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return Collections.singletonMap("error", "The login timed out or is invalid."); } User user = userRepository.findOne(Login.currentLoginId(session)); entry.setUser(user); // TODO: validate boolean result; Entry entryTo = entryDao.findOne(entry.getId()); if (entryTo != null && entryTo.getId() > 0 && entryTo.getUser().getId() == user.getId()) { entry.setId(entryTo.getId()); entryDao.save(entry); } else entryDao.save(entry); return Collections.singletonMap("id", Integer.toString(entry.getId())); } /** * @param entryId entry id * @param session HttpSession * @param response HttpServletResponse * @return errors or entry id if success * @throws Exception */ @CacheEvict(value = "recentblogs") @RequestMapping(method = RequestMethod.DELETE) public @ResponseBody Map<String, String> delete(@RequestBody int entryId, HttpSession session, HttpServletResponse response) throws Exception { if (!Login.isAuthenticated(session)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return Collections.singletonMap("error", "The login timed out or is invalid."); } if (entryId < 1) return Collections.singletonMap("error", "The entry id was invalid."); try { User user = userRepository.findOne(Login.currentLoginId(session)); Entry entry = entryDao.findOne(entryId); if (user.getId() == entry.getUser().getId()) { Iterable<Comment> comments = entry.getComments(); commentDao.delete(comments); entryDao.delete(entryId); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return Collections.singletonMap("error", "Could not delete entry."); } return Collections.singletonMap("id", Integer.toString(entryId)); } catch (Exception e) { log.error(e.getMessage()); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return Collections.singletonMap("error", "Could not delete the comment."); } } }
package com.minespaceships.mod.menu; import java.util.ArrayList; import net.minecraft.util.EnumChatFormatting; import com.minespaceships.mod.overhead.CustomGuiChat; import com.minespaceships.mod.spaceship.Spaceship; /** * This class displays a menu structure. * @author ovae. * @version 20150302 */ public class MenuDisplay { //The terminal to write in. private CustomGuiChat terminal; //The root of the menu structure. private Menu root; /** * Creates a new MenuDisplay. * @param root * @param terminal */ public MenuDisplay(final Menu root, final CustomGuiChat terminal){ if(root.equals(null)){ throw new IllegalArgumentException("root can not be null."); } if(terminal.equals(null)){ throw new IllegalArgumentException("termianl can not be null."); } this.root = root; this.terminal = terminal; } /** * Get the currently selected menu and prepares the output of that menu. * @param menu * @param command */ private String preparingOutput(final Menu menu, final String command){ String out = ""; if(menu == null){ return EnumChatFormatting.RED+"unknown command.\nPress 'm' to get back."; } if(menu instanceof FunctionalMenu){ return ((FunctionalMenu)menu).activate(command); } root.setSelectedMenu(menu); //add the menu name out += EnumChatFormatting.GOLD+" "+EnumChatFormatting.BOLD+"]--"+(menu.getMenuName().toUpperCase())+" ("+menu.getMenuID()+")--[\n\n"; //add all sub menus to the string. int position = 1; ArrayList<Menu> list = menu.getChildrenList(); for(Menu child: list){ if(child instanceof FunctionalMenu || child instanceof FunctionalParamMenu){ out+= " "+EnumChatFormatting.GREEN+"["+position+"] "+child.getMenuName()+" ("+child.getMenuID()+")"+'\n'; }else{ out+= EnumChatFormatting.WHITE+" ["+position+"] "+child.getMenuName()+" ("+child.getMenuID()+")"+'\n'; } position++; } return out; } /** * Displays the current selected menu. * @param command */ public void display(final String command){ if(command.trim().isEmpty()){ terminal.display(EnumChatFormatting.RED+"unknown command.\nPress 'm' to get back.", true); return; } terminal.display(preparingOutput(root.switchMenu(command),command),true); } /** * Displays the root menu. * @param menu */ public void displayMain(final Menu menu){ if(menu.equals(null)){ throw new IllegalArgumentException("Menu can not be null."); } terminal.display(preparingOutput(menu, ""),true); } }
package com.mnubo.java.sdk.client.utils; import static java.lang.String.format; import java.util.List; import com.google.common.collect.Lists; import com.mnubo.java.sdk.client.models.result.BooleanValue; import com.mnubo.java.sdk.client.models.result.DoubleValue; import com.mnubo.java.sdk.client.models.result.FloatValue; import com.mnubo.java.sdk.client.models.result.IntegerValue; import com.mnubo.java.sdk.client.models.result.LongValue; import com.mnubo.java.sdk.client.models.result.ResultValue; import com.mnubo.java.sdk.client.models.result.StringValue; public class Convert { public static String highLevelToPrimitiveType(String highLevelType) { String primitiveType = "unknown"; switch( highLevelType.toUpperCase() ){ case "INT": case "TIME": primitiveType = "INT"; break; case "COUNTRY_ISO": case "DATETIME": case "EMAIL": case "STATE": case "TEXT": case "TIME_ZONE": primitiveType = "STRING"; break; case "LONG": case "DURATION": primitiveType = "LONG"; break; case "ACCELERATION": case "AREA": case "DOUBLE": case "LENGTH": case "SPEED": case "TEMPERATURE": case "VOLUME": primitiveType = "DOUBLE"; break; case "BOOLEAN": primitiveType = "BOOLEAN"; break; case "MASS": case "FLOAT": primitiveType = "FLOAT"; break; case "PREDICTIVE_MODEL": primitiveType = "BLOB"; break; } return primitiveType; } public static ResultValue toResultValue(Object value){ ResultValue resultValue; if( value instanceof String){ resultValue = new StringValue((String)value); } else if( value instanceof Integer) { resultValue = new IntegerValue((Integer)value); } else if( value instanceof Long) { resultValue = new LongValue((Long)value); } else if( value instanceof Float) { resultValue = new FloatValue((Float)value); } else if( value instanceof Double) { resultValue = new DoubleValue((Double)value); } else if( value instanceof Boolean) { resultValue = new BooleanValue((Boolean)value); } else { throw new NumberFormatException(format("Unsupported type for value '%s'", value.toString())); } return resultValue; } public static List<ResultValue> toResultValueList(List<Object> values){ List<ResultValue> resultValues = Lists.newArrayList(); for(Object value : values){ resultValues.add(toResultValue(value)); } return resultValues; } }
package org.codeliners.mod.oreliners.config; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.codeliners.mod.oreliners.OreLiners; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import cpw.mods.fml.common.event.FMLPreInitializationEvent; public class CreateOreXML { public static void CreateOreXML(FMLPreInitializationEvent event) { boolean success = (new File(event.getModConfigurationDirectory(), "OreLiners/").mkdirs()); if (!success) { System.out.println("OreLiners directory failed to be created."); } try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("Ores"); doc.appendChild(rootElement); // Ore elements Element ore = doc.createElement("Ore"); rootElement.appendChild(ore); // OreName elements Element OreName = doc.createElement("OreName"); OreName.appendChild(doc.createTextNode("Iron")); ore.appendChild(OreName); // OreID elements Element OreID = doc.createElement("OreID"); OreID.appendChild(doc.createTextNode("15")); ore.appendChild(OreID); // SpawnRatePerChunk elements Element SpawnRatePerChunk = doc.createElement("SpawnRatePerChunk"); SpawnRatePerChunk.appendChild(doc.createTextNode("20")); ore.appendChild(SpawnRatePerChunk); // MaxSpawnHeight elements Element MaxSpawnHeight = doc.createElement("MaxSpawnHeight"); MaxSpawnHeight.appendChild(doc.createTextNode("40")); ore.appendChild(MaxSpawnHeight); // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(OreLiners.oreXML); // Output to console for testing //StreamResult result = new StreamResult(System.out); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.transform(source, result); System.out.println("File saved!"); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } } }
package com.perimeterx.internals; import com.perimeterx.http.PXClient; import com.perimeterx.internals.cookie.DataEnrichmentCookie; import com.perimeterx.models.PXContext; import com.perimeterx.models.configuration.PXConfiguration; import com.perimeterx.models.exceptions.PXException; import com.perimeterx.models.httpmodels.RiskResponse; import com.perimeterx.models.risk.BlockReason; import com.perimeterx.models.risk.PassReason; import com.perimeterx.models.risk.S2SErrorReason; import com.perimeterx.utils.Constants; import com.perimeterx.utils.PXLogger; import org.apache.http.conn.ConnectTimeoutException; public class PXS2SValidator implements PXValidator { private static final PXLogger logger = PXLogger.getLogger(PXS2SValidator.class); private PXClient pxClient; private PXConfiguration pxConfiguration; public PXS2SValidator(PXClient pxClient, PXConfiguration pxConfiguration) { this.pxClient = pxClient; this.pxConfiguration = pxConfiguration; } /** * Verify if request is valid or not * * @param pxContext - Request context * @return risk response from PX servers * @throws PXException will be thrown when an error occurs */ public boolean verify(PXContext pxContext) throws PXException { logger.debug(PXLogger.LogReason.DEBUG_S2S_RISK_API_REQUEST, pxContext.getS2sCallReason()); RiskResponse response = null; long startRiskRtt = System.currentTimeMillis(); long rtt; try { response = pxClient.riskApiCall(pxContext); rtt = System.currentTimeMillis() - startRiskRtt; logger.debug(PXLogger.LogReason.DEBUG_S2S_RISK_API_RESPONSE, (response == null) ? "" : response.getScore(), rtt); if (isResponseInvalid(response)) { handleS2SError(pxContext, rtt, response, null); return true; } updateContext(pxContext, response); if (pxContext.getRiskScore() < pxConfiguration.getBlockingScore()) { pxContext.setPassReason(PassReason.S2S); return true; } else if (response.getAction().equals(Constants.BLOCK_ACTION_CHALLENGE) && response.getActionData() != null && response.getActionData().getBody() != null) { pxContext.setBlockActionData(response.getActionData().getBody()); pxContext.setBlockReason(BlockReason.CHALLENGE); } else { pxContext.setBlockReason(BlockReason.SERVER); } logger.debug(PXLogger.LogReason.DEBUG_S2S_ENFORCING_ACTION, pxContext.getBlockReason()); return false; } catch (ConnectTimeoutException e) { // Timeout handling - report pass reason and proceed with request pxContext.setPassReason(PassReason.S2S_TIMEOUT); return true; } catch (Exception e) { handleS2SError(pxContext, System.currentTimeMillis() - startRiskRtt, response, e); logger.debug("Error {}: {}", e.getMessage(), e.getStackTrace()); throw new PXException(e); } finally { pxContext.setRiskRtt(System.currentTimeMillis() - startRiskRtt); } } private void updateContext(PXContext pxContext, RiskResponse response) { pxContext.setResponsePxhd(response.getPxhd()); pxContext.setRiskScore(response.getScore()); pxContext.setUuid(response.getUuid()); pxContext.setBlockAction(response.getAction()); DataEnrichmentCookie dataEnrichment = new DataEnrichmentCookie(response.getDataEnrichment(), true); pxContext.setPxde(dataEnrichment.getJsonPayload()); pxContext.setPxdeVerified(dataEnrichment.isValid()); } private boolean isResponseInvalid(RiskResponse response) { return response == null || response.getStatus() != 0; } private void handleS2SError(PXContext pxContext, long rtt, RiskResponse response, Exception exception) { pxContext.setRiskRtt(rtt); pxContext.setPassReason(PassReason.S2S_ERROR); if (pxContext.getS2sErrorReason() == S2SErrorReason.NO_ERROR) { S2SErrorReason errorReason = getS2SErrorReason(pxContext, response); String errorMessage = getS2SErrorMessage(response, exception); pxContext.setS2SErrorInfo(errorReason, errorMessage, pxContext.getS2sErrorHttpStatus(), pxContext.getS2sErrorHttpMessage()); } } private S2SErrorReason getS2SErrorReason(PXContext pxContext, RiskResponse response) { if (!pxContext.isMadeS2SApiCall()) { return S2SErrorReason.UNABLE_TO_SEND_REQUEST; } else if (response != null && isResponseInvalid(response)) { return S2SErrorReason.REQUEST_FAILED_ON_SERVER; } return S2SErrorReason.UNKNOWN_ERROR; } private String getS2SErrorMessage(RiskResponse response, Exception exception) { if (exception != null) { return exception.getMessage(); } else if (response != null && isResponseInvalid(response)) { return response.getMessage(); } int CURRENT_FUNCTION_INDEX = 1; return String.format("Error: %s", Thread.currentThread().getStackTrace()[CURRENT_FUNCTION_INDEX].toString()); } }
package com.planetvoor; import com.planetvoor.domain.MovieEntity; import com.planetvoor.domain.RatingEntity; import com.planetvoor.domain.UserEntity; import com.planetvoor.repository.MovieRepository; import com.planetvoor.repository.RatingRepository; import com.planetvoor.repository.UserRepository; import lombok.extern.slf4j.Slf4j; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.core.io.Resource; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import java.io.IOException; import java.net.URI; import java.net.URL; import java.util.Arrays; import java.util.Date; import java.util.List; @SpringBootApplication @EnableJpaRepositories @Slf4j public class DataTransformApplication implements CommandLineRunner { @Autowired UserRepository userRepository; @Autowired MovieRepository movieRepository; @Autowired RatingRepository ratingRepository; @Value("${files.data.path}") private Resource data; @Value("${files.movie.path}") private Resource movie; @Value("${files.user.path}") private Resource user; public static void main(String[] args) { SpringApplication.run(DataTransformApplication.class, args); } @Override public void run(String... params) throws Exception { List<String> options = Arrays.asList(params); if (options.contains("data")) { readDataIn(); } if (options.contains("movie")) { readMovieIn(); } if (options.contains("user")) { readUserIn(); } } public void readUserIn() { try { CSVLooper.builder().file(user.getFile()).separator('|').line(x -> { UserEntity user = UserEntity.builder().id(Long.valueOf(x[0])) .age(Long.valueOf(x[1])) .gender("M".equals(x[2]) ? UserEntity.Gender.MALE : UserEntity.Gender.FEMALE) .job(x[3]) .zip(x[4]).build(); log.debug("Adding new user {}", user); userRepository.save(user); }).build().loop(); } catch (IOException e) { log.error(e.getMessage(), e); } } public void readMovieIn() { try { DateTimeFormatter parser = DateTimeFormat.forPattern("dd-MMM-yyyy"); CSVLooper.builder().file(movie.getFile()).separator('|').line(x -> { Date release = null; try { release = parser.parseDateTime(x[2]).toDate(); } catch (IllegalArgumentException e) { log.error("Unable to parse date {} for {}", x[2], x[1]); } URL url = null; try { url = URI.create(x[4]).toURL(); } catch (Exception e) { log.error("Unable to parse url {} for {}", x[4], x[1]); } MovieEntity movie = MovieEntity.builder().id(Long.valueOf(x[0])) .title(x[1]) .release(release) // x[3] empty .url(url) .unknown("1".equals(x[5])) .action("1".equals(x[6])) .adventure("1".equals(x[6])) .animation("1".equals(x[6])) .children("1".equals(x[6])) .comedy("1".equals(x[6])) .crime("1".equals(x[6])) .documentary("1".equals(x[6])) .drama("1".equals(x[6])) .fantasy("1".equals(x[6])) .filmnoir("1".equals(x[6])) .horror("1".equals(x[6])) .musical("1".equals(x[6])) .mystery("1".equals(x[6])) .romance("1".equals(x[6])) .scifi("1".equals(x[6])) .thriller("1".equals(x[6])) .war("1".equals(x[6])) .western("1".equals(x[6])).build(); log.debug("Adding new movie {}", movie); this.movieRepository.save(movie); }).build().loop(); } catch (IOException e) { log.error(e.getMessage(), e); } } public void readDataIn() { try { CSVLooper.builder().file(data.getFile()).separator('\t').line(x -> { RatingEntity ratingEntity = RatingEntity.builder() .userId(Long.valueOf(x[0])) .movieId(Long.valueOf(x[1])) .rating(Long.valueOf(x[2])) .time(new Date(Long.valueOf(x[3]))) .build(); ratingRepository.save(ratingEntity); }).build().loop(); } catch (IOException e) { log.error(e.getMessage(), e); } } public void readAll() { readUserIn(); readDataIn(); readMovieIn(); } }
package com.redhat.ceylon.compiler.js; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import com.redhat.ceylon.compiler.loader.MetamodelGenerator; import com.redhat.ceylon.compiler.typechecker.model.Annotation; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Generic; import com.redhat.ceylon.compiler.typechecker.model.IntersectionType; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ParameterList; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.Setter; import com.redhat.ceylon.compiler.typechecker.model.TypeAlias; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.UnionType; import com.redhat.ceylon.compiler.typechecker.model.Util; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; /** A convenience class to help with the handling of certain type declarations. */ public class TypeUtils { final TypeDeclaration tuple; final TypeDeclaration iterable; final TypeDeclaration sequential; final TypeDeclaration numeric; final TypeDeclaration _integer; final TypeDeclaration _boolean; final TypeDeclaration _float; final TypeDeclaration _null; final TypeDeclaration anything; final TypeDeclaration callable; final TypeDeclaration empty; final TypeDeclaration metaClass; final TypeDeclaration destroyable; TypeUtils(Module languageModule) { com.redhat.ceylon.compiler.typechecker.model.Package pkg = languageModule.getPackage(Module.LANGUAGE_MODULE_NAME); tuple = (TypeDeclaration)pkg.getDirectMember("Tuple", null, false); iterable = (TypeDeclaration)pkg.getDirectMember("Iterable", null, false); sequential = (TypeDeclaration)pkg.getDirectMember("Sequential", null, false); numeric = (TypeDeclaration)pkg.getDirectMember("Numeric", null, false); _integer = (TypeDeclaration)pkg.getDirectMember("Integer", null, false); _boolean = (TypeDeclaration)pkg.getDirectMember("Boolean", null, false); _float = (TypeDeclaration)pkg.getDirectMember("Float", null, false); _null = (TypeDeclaration)pkg.getDirectMember("Null", null, false); anything = (TypeDeclaration)pkg.getDirectMember("Anything", null, false); callable = (TypeDeclaration)pkg.getDirectMember("Callable", null, false); empty = (TypeDeclaration)pkg.getDirectMember("Empty", null, false); destroyable = (TypeDeclaration)pkg.getDirectMember("Destroyable", null, false); pkg = languageModule.getPackage("ceylon.language.meta.model"); metaClass = (TypeDeclaration)pkg.getDirectMember("Class", null, false); } /** Prints the type arguments, usually for their reification. */ public static void printTypeArguments(final Node node, final Map<TypeParameter,ProducedType> targs, final GenerateJsVisitor gen, final boolean skipSelfDecl) { gen.out("{"); boolean first = true; for (Map.Entry<TypeParameter,ProducedType> e : targs.entrySet()) { if (first) { first = false; } else { gen.out(","); } gen.out(e.getKey().getName(), "$", e.getKey().getDeclaration().getName(), ":"); final ProducedType pt = e.getValue(); if (pt == null) { gen.out("'", e.getKey().getName(), "'"); } else if (!outputTypeList(node, pt, gen, skipSelfDecl)) { boolean hasParams = pt.getTypeArgumentList() != null && !pt.getTypeArgumentList().isEmpty(); boolean closeBracket = false; final TypeDeclaration d = pt.getDeclaration(); if (d instanceof TypeParameter) { resolveTypeParameter(node, (TypeParameter)d, gen, skipSelfDecl); } else { closeBracket = pt.getDeclaration() instanceof TypeAlias==false; if (closeBracket)gen.out("{t:"); outputQualifiedTypename( gen.isImported(node == null ? null : node.getUnit().getPackage(), pt.getDeclaration()), pt, gen, skipSelfDecl); } if (hasParams) { gen.out(",a:"); printTypeArguments(node, pt.getTypeArguments(), gen, skipSelfDecl); } if (closeBracket) { gen.out("}"); } } } gen.out("}"); } static void outputQualifiedTypename(final boolean imported, final ProducedType pt, final GenerateJsVisitor gen, final boolean skipSelfDecl) { TypeDeclaration t = pt.getDeclaration(); final String qname = t.getQualifiedNameString(); if (qname.equals("ceylon.language::Nothing")) { //Hack in the model means hack here as well gen.out(GenerateJsVisitor.getClAlias(), "Nothing"); } else if (qname.equals("ceylon.language::null") || qname.equals("ceylon.language::Null")) { gen.out(GenerateJsVisitor.getClAlias(), "Null"); } else if (pt.isUnknown()) { gen.out(GenerateJsVisitor.getClAlias(), "Anything"); } else { final String modAlias = imported ? gen.getNames().moduleAlias(t.getUnit().getPackage().getModule()) : null; if (modAlias != null && !modAlias.isEmpty()) { gen.out(modAlias, "."); } if (t.getContainer() instanceof ClassOrInterface) { List<ClassOrInterface> parents = new ArrayList<>(); ClassOrInterface parent = (ClassOrInterface)t.getContainer(); parents.add(0, parent); while (parent.getContainer() instanceof ClassOrInterface) { parent = (ClassOrInterface)parent.getContainer(); parents.add(0, parent); } for (ClassOrInterface p : parents) { gen.out(gen.getNames().name(p), "."); } } if (!outputTypeList(null, pt, gen, skipSelfDecl)) { gen.out(gen.getNames().name(t)); } } } /** Prints out an object with a type constructor under the property "t" and its type arguments under * the property "a", or a union/intersection type with "u" or "i" under property "t" and the list * of types that compose it in an array under the property "l", or a type parameter as a reference to * already existing params. */ static void typeNameOrList(final Node node, final ProducedType pt, final GenerateJsVisitor gen, final boolean skipSelfDecl) { TypeDeclaration type = pt.getDeclaration(); if (!outputTypeList(node, pt, gen, skipSelfDecl)) { if (type instanceof TypeParameter) { resolveTypeParameter(node, (TypeParameter)type, gen, skipSelfDecl); } else if (type instanceof TypeAlias) { outputQualifiedTypename(gen.isImported(node == null ? null : node.getUnit().getPackage(), type), pt, gen, skipSelfDecl); } else { gen.out("{t:"); outputQualifiedTypename(gen.isImported(node == null ? null : node.getUnit().getPackage(), type), pt, gen, skipSelfDecl); if (!pt.getTypeArgumentList().isEmpty()) { final Map<TypeParameter,ProducedType> targs; if (pt.getDeclaration().isToplevel()) { targs = pt.getTypeArguments(); } else { //Gather all type parameters from containers Scope scope = node.getScope(); final HashSet<TypeParameter> parenttp = new HashSet<>(); while (scope != null) { if (scope instanceof Generic) { for (TypeParameter tp : ((Generic)scope).getTypeParameters()) { parenttp.add(tp); } } scope = scope.getScope(); } targs = new HashMap<>(); targs.putAll(pt.getTypeArguments()); Declaration cd = Util.getContainingDeclaration(pt.getDeclaration()); while (cd != null) { if (cd instanceof Generic) { for (TypeParameter tp : ((Generic)cd).getTypeParameters()) { if (parenttp.contains(tp)) { targs.put(tp, tp.getType()); } } } cd = Util.getContainingDeclaration(cd); } } gen.out(",a:"); printTypeArguments(node, targs, gen, skipSelfDecl); } gen.out("}"); } } } /** Appends an object with the type's type and list of union/intersection types. */ static boolean outputTypeList(final Node node, final ProducedType pt, final GenerateJsVisitor gen, final boolean skipSelfDecl) { TypeDeclaration d = pt.getDeclaration(); final List<ProducedType> subs; if (d instanceof IntersectionType) { gen.out("{t:'i"); subs = d.getSatisfiedTypes(); } else if (d instanceof UnionType) { gen.out("{t:'u"); subs = d.getCaseTypes(); } else if ("ceylon.language::Tuple".equals(d.getQualifiedNameString())) { gen.out("{t:'T"); subs = node.getUnit().getTupleElementTypes(pt); } else { return false; } gen.out("',l:["); boolean first = true; for (ProducedType t : subs) { if (!first) gen.out(","); typeNameOrList(node, t, gen, skipSelfDecl); first = false; } gen.out("]}"); return true; } /** Finds the owner of the type parameter and outputs a reference to the corresponding type argument. */ static void resolveTypeParameter(final Node node, final TypeParameter tp, final GenerateJsVisitor gen, final boolean skipSelfDecl) { Scope parent = node.getScope(); int outers = 0; while (parent != null && parent != tp.getContainer()) { if (parent instanceof TypeDeclaration && !((TypeDeclaration) parent).isAnonymous()) { outers++; } parent = parent.getScope(); } if (tp.getContainer() instanceof ClassOrInterface) { if (parent == tp.getContainer()) { if (!skipSelfDecl) { ClassOrInterface ontoy = Util.getContainingClassOrInterface(node.getScope()); while (ontoy.isAnonymous())ontoy=Util.getContainingClassOrInterface(ontoy.getScope()); gen.out(gen.getNames().self((TypeDeclaration)ontoy)); for (int i = 0; i < outers; i++) { gen.out(".outer$"); } gen.out("."); } gen.out("$$targs$$.", tp.getName(), "$", tp.getDeclaration().getName()); } else { //This can happen in expressions such as Singleton(n) when n is dynamic gen.out("{/*NO PARENT*/t:", GenerateJsVisitor.getClAlias(), "Anything}"); } } else if (tp.getContainer() instanceof TypeAlias) { if (parent == tp.getContainer()) { gen.out("'", tp.getName(), "$", tp.getDeclaration().getName(), "'"); } else { //This can happen in expressions such as Singleton(n) when n is dynamic gen.out("{/*NO PARENT ALIAS*/t:", GenerateJsVisitor.getClAlias(), "Anything}"); } } else { //it has to be a method, right? //We need to find the index of the parameter where the argument occurs //...and it could be null... int plistCount = -1; ProducedType type = null; for (Iterator<ParameterList> iter0 = ((Method)tp.getContainer()).getParameterLists().iterator(); type == null && iter0.hasNext();) { plistCount++; for (Iterator<Parameter> iter1 = iter0.next().getParameters().iterator(); type == null && iter1.hasNext();) { if (type == null) { type = typeContainsTypeParameter(iter1.next().getType(), tp); } } } //The ProducedType that we find corresponds to a parameter, whose type can be: //A type parameter in the method, in which case we just use the argument's type (may be null) //A component of a union/intersection type, in which case we just use the argument's type (may be null) //A type argument of the argument's type, in which case we must get the reified generic from the argument if (tp.getContainer() == parent) { gen.out("$$$mptypes.", tp.getName(), "$", tp.getDeclaration().getName()); } else { gen.out("/*METHOD TYPEPARM plist ", Integer.toString(plistCount), "#", tp.getName(), "*/'", type.getProducedTypeQualifiedName(), "'"); } } } static ProducedType typeContainsTypeParameter(ProducedType td, TypeParameter tp) { TypeDeclaration d = td.getDeclaration(); if (d == tp) { return td; } else if (d instanceof UnionType || d instanceof IntersectionType) { List<ProducedType> comps = td.getCaseTypes(); if (comps == null) comps = td.getSupertypes(); for (ProducedType sub : comps) { td = typeContainsTypeParameter(sub, tp); if (td != null) { return td; } } } else if (d instanceof ClassOrInterface) { for (ProducedType sub : td.getTypeArgumentList()) { if (typeContainsTypeParameter(sub, tp) != null) { return td; } } } return null; } /** Find the type with the specified declaration among the specified type's supertypes, case types, satisfied types, etc. */ static ProducedType findSupertype(TypeDeclaration d, ProducedType pt) { if (pt.getDeclaration().equals(d)) { return pt; } List<ProducedType> list = pt.getSupertypes() == null ? pt.getCaseTypes() : pt.getSupertypes(); for (ProducedType t : list) { if (t.getDeclaration().equals(d)) { return t; } } return null; } static Map<TypeParameter, ProducedType> matchTypeParametersWithArguments(List<TypeParameter> params, List<ProducedType> targs) { if (params != null && targs != null && params.size() == targs.size()) { HashMap<TypeParameter, ProducedType> r = new HashMap<TypeParameter, ProducedType>(); for (int i = 0; i < targs.size(); i++) { r.put(params.get(i), targs.get(i)); } return r; } return null; } Map<TypeParameter, ProducedType> wrapAsIterableArguments(ProducedType pt) { HashMap<TypeParameter, ProducedType> r = new HashMap<TypeParameter, ProducedType>(); r.put(iterable.getTypeParameters().get(0), pt); r.put(iterable.getTypeParameters().get(1), _null.getType()); return r; } static boolean isUnknown(ProducedType pt) { return pt == null || pt.isUnknown(); } static boolean isUnknown(Parameter param) { return param == null || isUnknown(param.getType()); } static boolean isUnknown(Declaration d) { return d == null || d.getQualifiedNameString().equals("UnknownType"); } /** Generates the code to throw an Exception if a dynamic object is not of the specified type. */ static void generateDynamicCheck(final Tree.Term term, final ProducedType t, final GenerateJsVisitor gen, final boolean skipSelfDecl) { String tmp = gen.getNames().createTempVariable(); gen.out("(", tmp, "="); term.visit(gen); gen.out(",", GenerateJsVisitor.getClAlias(), "is$(", tmp, ","); TypeUtils.typeNameOrList(term, t, gen, skipSelfDecl); gen.out(")?", tmp, ":function(){throw new Error('dynamic objects cannot be used here (", term.getUnit().getFilename(), " ", term.getLocation(), ")')}())"); } static void encodeParameterListForRuntime(Node n, ParameterList plist, GenerateJsVisitor gen) { boolean first = true; gen.out("["); for (Parameter p : plist.getParameters()) { if (first) first=false; else gen.out(","); gen.out("{", MetamodelGenerator.KEY_NAME, ":'", p.getName(), "',"); gen.out(MetamodelGenerator.KEY_METATYPE, ":'", MetamodelGenerator.METATYPE_PARAMETER, "',"); if (p.getModel() instanceof Method) { gen.out("$pt:'f',"); } if (p.isSequenced()) { gen.out("seq:1,"); } if (p.isDefaulted()) { gen.out(MetamodelGenerator.KEY_DEFAULT, ":1,"); } gen.out(MetamodelGenerator.KEY_TYPE, ":"); metamodelTypeNameOrList(gen.getCurrentPackage(), p.getType(), gen); new ModelAnnotationGenerator(gen, p.getModel(), n).generateAnnotations(); gen.out("}"); } gen.out("]"); } /** Turns a Tuple type into a parameter list. */ List<Parameter> convertTupleToParameters(ProducedType _tuple) { ArrayList<Parameter> rval = new ArrayList<>(); int pos = 0; TypeDeclaration tdecl = _tuple.getDeclaration(); while (!(empty.equals(tdecl) || tdecl instanceof TypeParameter)) { Parameter _p = null; if (tuple.equals(tdecl) || (tdecl.getCaseTypeDeclarations() != null && tdecl.getCaseTypeDeclarations().size()==2 && tdecl.getCaseTypeDeclarations().contains(tuple))) { _p = new Parameter(); _p.setModel(new Value()); if (tuple.equals(tdecl)) { _p.getModel().setType(_tuple.getTypeArgumentList().get(1)); _tuple = _tuple.getTypeArgumentList().get(2); } else { //Handle union types for defaulted parameters for (ProducedType mt : _tuple.getCaseTypes()) { if (tuple.equals(mt.getDeclaration())) { _p.getModel().setType(mt.getTypeArgumentList().get(1)); _tuple = mt.getTypeArgumentList().get(2); break; } } _p.setDefaulted(true); } } else if (tdecl.inherits(sequential)) { //Handle Sequence, for nonempty variadic parameters _p = new Parameter(); _p.setModel(new Value()); _p.getModel().setType(_tuple.getTypeArgumentList().get(0)); _p.setSequenced(true); _tuple = empty.getType(); } else { if (pos > 100) { return rval; } } if (_tuple != null) tdecl = _tuple.getDeclaration(); if (_p != null) { _p.setName("arg" + pos); rval.add(_p); } pos++; } return rval; } /** This method encodes the type parameters of a Tuple in the same way * as a parameter list for runtime. */ private static void encodeTupleAsParameterListForRuntime(ProducedType _tuple, boolean nameAndMetatype, GenerateJsVisitor gen) { gen.out("["); int pos = 1; TypeDeclaration tdecl = _tuple.getDeclaration(); while (!(gen.getTypeUtils().empty.equals(tdecl) || tdecl instanceof TypeParameter)) { if (pos > 1) gen.out(","); gen.out("{"); pos++; if (nameAndMetatype) { gen.out(MetamodelGenerator.KEY_NAME, ":'p", Integer.toString(pos), "',"); gen.out(MetamodelGenerator.KEY_METATYPE, ":'", MetamodelGenerator.METATYPE_PARAMETER, "',"); } gen.out(MetamodelGenerator.KEY_TYPE, ":"); if (gen.getTypeUtils().tuple.equals(tdecl) || (tdecl.getCaseTypeDeclarations() != null && tdecl.getCaseTypeDeclarations().size()==2 && tdecl.getCaseTypeDeclarations().contains(gen.getTypeUtils().tuple))) { if (gen.getTypeUtils().tuple.equals(tdecl)) { metamodelTypeNameOrList(gen.getCurrentPackage(), _tuple.getTypeArgumentList().get(1), gen); _tuple = _tuple.getTypeArgumentList().get(2); } else { //Handle union types for defaulted parameters for (ProducedType mt : _tuple.getCaseTypes()) { if (gen.getTypeUtils().tuple.equals(mt.getDeclaration())) { metamodelTypeNameOrList(gen.getCurrentPackage(), mt.getTypeArgumentList().get(1), gen); _tuple = mt.getTypeArgumentList().get(2); break; } } gen.out(",", MetamodelGenerator.KEY_DEFAULT,":1"); } } else if (tdecl.inherits(gen.getTypeUtils().sequential)) { //Handle Sequence, for nonempty variadic parameters metamodelTypeNameOrList(gen.getCurrentPackage(), _tuple.getTypeArgumentList().get(0), gen); gen.out(",seq:1"); _tuple = gen.getTypeUtils().empty.getType(); } else if (tdecl instanceof UnionType) { metamodelTypeNameOrList(gen.getCurrentPackage(), _tuple, gen); tdecl = gen.getTypeUtils().empty; _tuple=null; } else { gen.out("\n/*WARNING3! Tuple is actually ", _tuple.getProducedTypeQualifiedName(), ", ", tdecl.getName(),"*/"); if (pos > 100) { break; } } gen.out("}"); if (_tuple != null) tdecl = _tuple.getDeclaration(); } gen.out("]"); } /** This method encodes the Arguments type argument of a Callable the same way * as a parameter list for runtime. */ static void encodeCallableArgumentsAsParameterListForRuntime(ProducedType _callable, GenerateJsVisitor gen) { if (_callable.getCaseTypes() != null) { for (ProducedType pt : _callable.getCaseTypes()) { if (pt.getProducedTypeQualifiedName().startsWith("ceylon.language::Callable<")) { _callable = pt; break; } } } else if (_callable.getSatisfiedTypes() != null) { for (ProducedType pt : _callable.getSatisfiedTypes()) { if (pt.getProducedTypeQualifiedName().startsWith("ceylon.language::Callable<")) { _callable = pt; break; } } } if (!_callable.getProducedTypeQualifiedName().contains("ceylon.language::Callable<")) { gen.out("[/*WARNING1: got ", _callable.getProducedTypeQualifiedName(), " instead of Callable*/]"); return; } List<ProducedType> targs = _callable.getTypeArgumentList(); if (targs == null || targs.size() != 2) { gen.out("[/*WARNING2: missing argument types for Callable*/]"); return; } encodeTupleAsParameterListForRuntime(targs.get(1), true, gen); } static void encodeForRuntime(Node that, final Declaration d, final GenerateJsVisitor gen) { if (d.getAnnotations() == null || d.getAnnotations().isEmpty()) { encodeForRuntime(that, d, gen, null); } else { encodeForRuntime(that, d, gen, new ModelAnnotationGenerator(gen, d, that)); } } /** Output a metamodel map for runtime use. */ static void encodeForRuntime(final Declaration d, final Tree.AnnotationList annotations, final GenerateJsVisitor gen) { final boolean include = annotations != null && !(annotations.getAnnotations().isEmpty() && annotations.getAnonymousAnnotation()==null); encodeForRuntime(annotations, d, gen, include ? new RuntimeMetamodelAnnotationGenerator() { @Override public void generateAnnotations() { gen.out(",", MetamodelGenerator.KEY_ANNOTATIONS, ":"); outputAnnotationsFunction(annotations, d, gen); } } : null); } /** Returns the list of keys to get from the package to the declaration, in the model. */ public static List<String> generateModelPath(final Declaration d) { final ArrayList<String> sb = new ArrayList<>(); final String pkgName = d.getUnit().getPackage().getNameAsString(); sb.add(Module.LANGUAGE_MODULE_NAME.equals(pkgName)?"$":pkgName); if (d.isToplevel()) { sb.add(d.getName()); if (d instanceof Setter) { sb.add("$set"); } } else { Declaration p = d; final int i = sb.size(); while (p instanceof Declaration) { if (p instanceof Setter) { sb.add(i, "$set"); } sb.add(i, TypeUtils.modelName(p)); //Build the path in reverse if (!p.isToplevel()) { if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Class) { sb.add(i, p.isAnonymous() ? MetamodelGenerator.KEY_OBJECTS : MetamodelGenerator.KEY_CLASSES); } else if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) { sb.add(i, MetamodelGenerator.KEY_INTERFACES); } else if (p instanceof Method) { sb.add(i, MetamodelGenerator.KEY_METHODS); } else if (p instanceof TypeAlias || p instanceof Setter) { sb.add(i, MetamodelGenerator.KEY_ATTRIBUTES); } else { //It's a value TypeDeclaration td=((TypedDeclaration)p).getTypeDeclaration(); sb.add(i, (td!=null&&td.isAnonymous())? MetamodelGenerator.KEY_OBJECTS : MetamodelGenerator.KEY_ATTRIBUTES); } } p = Util.getContainingDeclaration(p); } } return sb; } static void outputModelPath(final Declaration d, GenerateJsVisitor gen) { List<String> parts = generateModelPath(d); gen.out("["); boolean first = true; for (String p : parts) { if (first)first=false;else gen.out(","); gen.out("'", p, "'"); } gen.out("]"); } static void encodeForRuntime(final Node that, final Declaration d, final GenerateJsVisitor gen, final RuntimeMetamodelAnnotationGenerator annGen) { gen.out("function(){return{mod:$CCMM$"); List<TypeParameter> tparms = d instanceof Generic ? ((Generic)d).getTypeParameters() : null; List<ProducedType> satisfies = null; List<ProducedType> caseTypes = null; if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) { com.redhat.ceylon.compiler.typechecker.model.Class _cd = (com.redhat.ceylon.compiler.typechecker.model.Class)d; if (_cd.getExtendedType() != null) { gen.out(",'super':"); metamodelTypeNameOrList(d.getUnit().getPackage(), _cd.getExtendedType(), gen); } //Parameter types if (_cd.getParameterList()!=null) { gen.out(",", MetamodelGenerator.KEY_PARAMS, ":"); encodeParameterListForRuntime(that, _cd.getParameterList(), gen); } satisfies = _cd.getSatisfiedTypes(); caseTypes = _cd.getCaseTypes(); } else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) { satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getSatisfiedTypes(); caseTypes = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getCaseTypes(); } else if (d instanceof MethodOrValue) { gen.out(",", MetamodelGenerator.KEY_TYPE, ":"); //This needs a new setting to resolve types but not type parameters metamodelTypeNameOrList(d.getUnit().getPackage(), ((MethodOrValue)d).getType(), gen); if (d instanceof Method) { gen.out(",", MetamodelGenerator.KEY_PARAMS, ":"); //Parameter types of the first parameter list encodeParameterListForRuntime(that, ((Method)d).getParameterLists().get(0), gen); tparms = ((Method) d).getTypeParameters(); } } if (!d.isToplevel()) { //Find the first container that is a Declaration final Declaration _cont = Util.getContainingDeclaration(d); gen.out(",$cont:"); if (_cont instanceof Value) { if (gen.defineAsProperty(_cont)) { gen.qualify(that, _cont); gen.out("$prop$"); } gen.out(gen.getNames().getter(_cont)); } else if (_cont instanceof Setter) { gen.out("{setter:"); if (gen.defineAsProperty(_cont)) { gen.qualify(that, _cont); gen.out("$prop$", gen.getNames().getter(((Setter) _cont).getGetter()), ".set"); } else { gen.out(gen.getNames().setter(((Setter) _cont).getGetter())); } gen.out("}"); } else { gen.out(gen.getNames().name(_cont)); } } if (tparms != null && !tparms.isEmpty()) { gen.out(",", MetamodelGenerator.KEY_TYPE_PARAMS, ":{"); encodeTypeParametersForRuntime(d, tparms, true, gen); gen.out("}"); } if (satisfies != null && !satisfies.isEmpty()) { gen.out(",satisfies:["); boolean first = true; for (ProducedType st : satisfies) { if (!first)gen.out(","); first=false; metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen); } gen.out("]"); } if (caseTypes != null && !caseTypes.isEmpty()) { gen.out(",of:["); boolean first = true; for (ProducedType st : caseTypes) { if (!first)gen.out(","); first=false; if (st.getDeclaration().isAnonymous()) { gen.out("$prop$", gen.getNames().getter(st.getDeclaration())); } else { metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen); } } gen.out("]"); } if (annGen != null) { annGen.generateAnnotations(); } //Path to its model gen.out(",d:"); outputModelPath(d, gen); gen.out("};}"); } static boolean encodeTypeParametersForRuntime(final Declaration d, final List<TypeParameter> tparms, boolean first, final GenerateJsVisitor gen) { for(TypeParameter tp : tparms) { boolean comma = false; if (!first)gen.out(","); first=false; gen.out(tp.getName(), "$", tp.getDeclaration().getName(), ":{"); if (tp.isCovariant()) { gen.out("'var':'out'"); comma = true; } else if (tp.isContravariant()) { gen.out("'var':'in'"); comma = true; } List<ProducedType> typelist = tp.getSatisfiedTypes(); if (typelist != null && !typelist.isEmpty()) { if (comma)gen.out(","); gen.out("'satisfies':["); boolean first2 = true; for (ProducedType st : typelist) { if (!first2)gen.out(","); first2=false; metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen); } gen.out("]"); comma = true; } typelist = tp.getCaseTypes(); if (typelist != null && !typelist.isEmpty()) { if (comma)gen.out(","); gen.out("of:["); boolean first3 = true; for (ProducedType st : typelist) { if (!first3)gen.out(","); first3=false; metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen); } gen.out("]"); comma = true; } if (tp.getDefaultTypeArgument() != null) { if (comma)gen.out(","); gen.out("'def':"); metamodelTypeNameOrList(d.getUnit().getPackage(), tp.getDefaultTypeArgument(), gen); } gen.out("}"); } return first; } /** Prints out an object with a type constructor under the property "t" and its type arguments under * the property "a", or a union/intersection type with "u" or "i" under property "t" and the list * of types that compose it in an array under the property "l", or a type parameter as a reference to * already existing params. */ static void metamodelTypeNameOrList(final com.redhat.ceylon.compiler.typechecker.model.Package pkg, ProducedType pt, GenerateJsVisitor gen) { if (pt == null) { //In dynamic blocks we sometimes get a null producedType pt = ((TypeDeclaration)pkg.getModule().getLanguageModule().getDirectPackage( Module.LANGUAGE_MODULE_NAME).getDirectMember("Anything", null, false)).getType(); } if (!outputMetamodelTypeList(pkg, pt, gen)) { TypeDeclaration type = pt.getDeclaration(); if (type instanceof TypeParameter) { gen.out("'", type.getNameAsString(), "$", ((TypeParameter)type).getDeclaration().getName(), "'"); } else if (type instanceof TypeAlias) { outputQualifiedTypename(gen.isImported(pkg, type), pt, gen, false); } else { gen.out("{t:"); outputQualifiedTypename(gen.isImported(pkg, type), pt, gen, false); //Type Parameters if (!pt.getTypeArgumentList().isEmpty()) { gen.out(",a:{"); boolean first = true; for (Map.Entry<TypeParameter, ProducedType> e : pt.getTypeArguments().entrySet()) { if (first) first=false; else gen.out(","); gen.out(e.getKey().getNameAsString(), "$", e.getKey().getDeclaration().getName(), ":"); metamodelTypeNameOrList(pkg, e.getValue(), gen); } gen.out("}"); } gen.out("}"); } } } /** Appends an object with the type's type and list of union/intersection types; works only with union, * intersection and tuple types. * @return true if output was generated, false otherwise (it was a regular type) */ static boolean outputMetamodelTypeList(final com.redhat.ceylon.compiler.typechecker.model.Package pkg, ProducedType pt, GenerateJsVisitor gen) { TypeDeclaration type = pt.getDeclaration(); final List<ProducedType> subs; if (type instanceof IntersectionType) { gen.out("{t:'i"); subs = type.getSatisfiedTypes(); } else if (type instanceof UnionType) { //It still could be a Tuple with first optional type List<TypeDeclaration> cts = type.getCaseTypeDeclarations(); if (cts.size()==2 && cts.contains(gen.getTypeUtils().empty) && cts.contains(gen.getTypeUtils().tuple)) { //yup... gen.out("{t:'T',l:"); encodeTupleAsParameterListForRuntime(pt,false,gen); gen.out("}"); return true; } gen.out("{t:'u"); subs = type.getCaseTypes(); } else if (type.getQualifiedNameString().equals("ceylon.language::Tuple")) { gen.out("{t:'T',l:"); encodeTupleAsParameterListForRuntime(pt,false, gen); gen.out("}"); return true; } else { return false; } gen.out("',l:["); boolean first = true; for (ProducedType t : subs) { if (!first) gen.out(","); metamodelTypeNameOrList(pkg, t, gen); first = false; } gen.out("]}"); return true; } ProducedType tupleFromParameters(List<com.redhat.ceylon.compiler.typechecker.model.Parameter> params) { if (params == null || params.isEmpty()) { return empty.getType(); } ProducedType tt = empty.getType(); ProducedType et = null; for (int i = params.size()-1; i>=0; i com.redhat.ceylon.compiler.typechecker.model.Parameter p = params.get(i); if (et == null) { et = p.getType(); } else { UnionType ut = new UnionType(p.getModel().getUnit()); ArrayList<ProducedType> types = new ArrayList<>(); if (et.getCaseTypes() == null || et.getCaseTypes().isEmpty()) { types.add(et); } else { types.addAll(et.getCaseTypes()); } types.add(p.getType()); ut.setCaseTypes(types); et = ut.getType(); } Map<TypeParameter,ProducedType> args = new HashMap<>(); for (TypeParameter tp : tuple.getTypeParameters()) { if ("First".equals(tp.getName())) { args.put(tp, p.getType()); } else if ("Element".equals(tp.getName())) { args.put(tp, et); } else if ("Rest".equals(tp.getName())) { args.put(tp, tt); } } if (i == params.size()-1) { tt = tuple.getType(); } tt = tt.substitute(args); } return tt; } static String pathToModelDoc(final Declaration d) { if (d == null)return null; final StringBuilder sb = new StringBuilder(); for (String p : generateModelPath(d)) { if (sb.length()==0) { sb.append("$CCMM$"); if ("$".equals(p)) { p = Module.LANGUAGE_MODULE_NAME; } if (p.isEmpty() || p.indexOf('.') >= 0) { sb.append("['").append(p).append("']"); } else { sb.append(".").append(p); } } else { sb.append(".").append(p); } } sb.append(".$an.doc[0]"); return sb.toString(); } /** Outputs a function that returns the specified annotations, so that they can be loaded lazily. * @param annotations The annotations to be output. * @param d The declaration to which the annotations belong. * @param gen The generator to use for output. */ static void outputAnnotationsFunction(final Tree.AnnotationList annotations, final Declaration d, final GenerateJsVisitor gen) { if (annotations == null || (annotations.getAnnotations().isEmpty() && annotations.getAnonymousAnnotation()==null)) { gen.out("[]"); } else { gen.out("function(){return["); boolean first = true; //Leave the annotation but remove the doc from runtime for brevity if (annotations.getAnonymousAnnotation() != null) { first = false; final Tree.StringLiteral lit = annotations.getAnonymousAnnotation().getStringLiteral(); gen.out(GenerateJsVisitor.getClAlias(), "doc("); final String sb = pathToModelDoc(d); if (sb != null && sb.length() < lit.getText().length()) { gen.out(sb); } else { lit.visit(gen); } gen.out(")"); } for (Tree.Annotation a : annotations.getAnnotations()) { if (first) first=false; else gen.out(","); gen.getInvoker().generateInvocation(a); } gen.out("];}"); } } /** Abstraction for a callback that generates the runtime annotations list as part of the metamodel. */ static interface RuntimeMetamodelAnnotationGenerator { public void generateAnnotations(); } static class ModelAnnotationGenerator implements RuntimeMetamodelAnnotationGenerator { private final GenerateJsVisitor gen; private final Declaration d; private final Node node; private boolean includeAnnotationKey=true; ModelAnnotationGenerator(GenerateJsVisitor generator, Declaration decl, Node n) { gen = generator; d = decl; node = n; } public ModelAnnotationGenerator omitKey() { includeAnnotationKey=false; return this; } @Override public void generateAnnotations() { if (includeAnnotationKey) { gen.out(",", MetamodelGenerator.KEY_ANNOTATIONS, ":"); } gen.out("function(){return["); boolean first = true; for (Annotation a : d.getAnnotations()) { if (first) first=false; else gen.out(","); Declaration ad = d.getUnit().getPackage().getMemberOrParameter(d.getUnit(), a.getName(), null, false); if (ad instanceof Method) { gen.qualify(node, ad); gen.out(gen.getNames().name(ad), "("); if (a.getPositionalArguments() == null) { for (Parameter p : ((Method)ad).getParameterLists().get(0).getParameters()) { String v = a.getNamedArguments().get(p.getName()); gen.out(v == null ? "undefined" : v); } } else { if ("ceylon.language::doc".equals(ad.getQualifiedNameString())) { //Use ref if it's too long final String ref = pathToModelDoc(d); final String doc = a.getPositionalArguments().get(0); if (ref != null && ref.length() < doc.length()) { gen.out(ref); } else { gen.out("\"", gen.escapeStringLiteral(doc), "\""); } } else { boolean farg = true; for (String s : a.getPositionalArguments()) { if (farg)farg=false; else gen.out(","); gen.out("\"", gen.escapeStringLiteral(s), "\""); } } } gen.out(")"); } else { gen.out("null/*MISSING DECLARATION FOR ANNOTATION ", a.getName(), "*/"); } } gen.out("];}"); } } /** Generates the right type arguments for operators that are sugar for method calls. * @param left The left term of the operator * @param right The right term of the operator * @param methodName The name of the method that is to be invoked * @param rightTpName The name of the type argument on the right term * @param leftTpName The name of the type parameter on the method * @return A map with the type parameter of the method as key * and the produced type belonging to the type argument of the term on the right. */ static Map<TypeParameter, ProducedType> mapTypeArgument(final Tree.BinaryOperatorExpression expr, final String methodName, final String rightTpName, final String leftTpName) { Method md = (Method)expr.getLeftTerm().getTypeModel().getDeclaration().getMember(methodName, null, false); if (md == null) { expr.addUnexpectedError("Left term of intersection operator should have method named " + methodName); return null; } Map<TypeParameter, ProducedType> targs = expr.getRightTerm().getTypeModel().getTypeArguments(); ProducedType otherType = null; for (TypeParameter tp : targs.keySet()) { if (tp.getName().equals(rightTpName)) { otherType = targs.get(tp); break; } } if (otherType == null) { expr.addUnexpectedError("Right term of intersection operator should have type parameter named " + rightTpName); return null; } targs = new HashMap<>(); TypeParameter mtp = null; for (TypeParameter tp : md.getTypeParameters()) { if (tp.getName().equals(leftTpName)) { mtp = tp; break; } } if (mtp == null) { expr.addUnexpectedError("Left term of intersection should have type parameter named " + leftTpName); } targs.put(mtp, otherType); return targs; } /** Returns the qualified name of a declaration, skipping any containing methods. */ public static String qualifiedNameSkippingMethods(Declaration d) { final StringBuilder p = new StringBuilder(d.getName()); Scope s = d.getContainer(); while (s != null) { if (s instanceof com.redhat.ceylon.compiler.typechecker.model.Package) { final String pkname = ((com.redhat.ceylon.compiler.typechecker.model.Package)s).getNameAsString(); if (!pkname.isEmpty()) { p.insert(0, "::"); p.insert(0, pkname); } } else if (s instanceof TypeDeclaration) { p.insert(0, '.'); p.insert(0, ((TypeDeclaration)s).getName()); } s = s.getContainer(); } return p.toString(); } public static String modelName(Declaration d) { if (d.isToplevel() || d.isShared()) { return d.getName(); } if (d instanceof Setter) { d = ((Setter)d).getGetter(); } return d.getName()+"$"+Long.toString(Math.abs((long)d.hashCode()), 36); } }
package com.salesforce.dataloader.config; import com.salesforce.dataloader.action.OperationInfo; import com.salesforce.dataloader.exception.ConfigInitializationException; import com.salesforce.dataloader.exception.ParameterLoadException; import com.salesforce.dataloader.exception.ProcessInitializationException; import com.salesforce.dataloader.security.EncryptionAesUtil; import com.salesforce.dataloader.util.AppUtil; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; 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.io.PrintStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.security.GeneralSecurityException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.StringJoiner; import java.util.TimeZone; public class Config { private static Logger logger = LogManager.getLogger(Config.class); private static final String DECRYPTED_SUFFIX = ".decrypted"; /** * Default values for specific parameters */ public static final int DEFAULT_EXTRACT_REQUEST_SIZE = 500; public static final int DEFAULT_MIN_RETRY_SECS = 2; public static final int DEFAULT_MAX_RETRIES = 3; public static final int MAX_RETRIES_LIMIT = 10; public static final int DEFAULT_CONNECTION_TIMEOUT_SECS = 60; public static final int DEFAULT_TIMEOUT_SECS = 540; public static final int DEFAULT_LOAD_BATCH_SIZE = 200; public static final int DEFAULT_DAO_WRITE_BATCH_SIZE = 500; public static final int DEFAULT_DAO_READ_BATCH_SIZE = 200; public static final int MAX_LOAD_BATCH_SIZE = 200; public static final int MAX_DAO_READ_BATCH_SIZE = 200; public static final int MAX_DAO_WRITE_BATCH_SIZE = 2000; public static final int MAX_BULK_API_BATCH_BYTES = 10000000; public static final int MAX_BULK_API_BATCH_SIZE = 10000; public static final int DEFAULT_BULK_API_BATCH_SIZE = 2000; public static final long DEFAULT_BULK_API_CHECK_STATUS_INTERVAL = 5000L; public static final String DEFAULT_ENDPOINT_URL = "https://login.salesforce.com"; public static final String OAUTH_PROD_ENVIRONMENT_VAL = "Production"; public static final String OAUTH_SB_ENVIRONMENT_VAL = "Sandbox"; public static final String OAUTH_PROD_SERVER_VAL = "https://login.salesforce.com/"; public static final String OAUTH_SB_SERVER_VAL = "https://test.salesforce.com/"; public static final String OAUTH_PROD_REDIRECTURI_VAL = "https://login.salesforce.com/services/oauth2/success"; public static final String OAUTH_SB_REDIRECTURI_VAL = "https://test.salesforce.com/services/oauth2/success"; public static final String OAUTH_BULK_CLIENTID_VAL = "DataLoaderBulkUI/"; public static final String OAUTH_PARTNER_CLIENTID_VAL = "DataLoaderPartnerUI/"; public static final int DEFAULT_BULK_QUERY_PK_CHUNK_SIZE = 100000; public static final int MAX_BULK_QUERY_PK_CHUNK_SIZE = 250000; /* * Issue #59 - Dataloader will not read all the database rows to get a total count * when skipTotalCount = "false" * * The default is "true" */ public static final Boolean DEFAULT_SKIP_TOTAL_COUNT = true; /** * Constants that were made not configurable by choice */ public static final String ID_COLUMN_NAME = "ID"; //$NON-NLS-1$ public static final String ERROR_COLUMN_NAME = "ERROR"; //$NON-NLS-1$ public static final String STATUS_COLUMN_NAME = "STATUS"; //$NON-NLS-1$ /** * The mapping from preference name to preference value (represented as strings). */ private Properties properties; private Properties readOnlyProperties; private Map<String, String> parameterOverridesMap; /** * The default-default value for the respective types. */ public static final boolean BOOLEAN_DEFAULT = false; public static final double DOUBLE_DEFAULT = 0.0; public static final float FLOAT_DEFAULT = 0.0f; public static final int INT_DEFAULT = 0; public static final long LONG_DEFAULT = 0L; public static final String STRING_DEFAULT = ""; //$NON-NLS-1$ public static final Map<String, String> MAP_STRING_DEFAULT = new LinkedHashMap<>(); /** * The Constants for the current Loader Keys */ // salesforce constants // Loader Preferences public static final String HIDE_WELCOME_SCREEN = "loader.hideWelcome"; // Delimiter settings public static final String CSV_DELIMETER_COMMA = "loader.csvComma"; public static final String CSV_DELIMETER_TAB = "loader.csvTab"; public static final String CSV_DELIMETER_OTHER = "loader.csvOther"; public static final String CSV_DELIMETER_OTHER_VALUE = "loader.csvOtherValue"; public static final String BUFFER_UNPROCESSED_BULK_QUERY_RESULTS = "loader.bufferUnprocessedBulkQueryResults"; //Special Internal Configs public static final String SFDC_INTERNAL = "sfdcInternal"; //$NON-NLS-1$ public static final String SFDC_INTERNAL_IS_SESSION_ID_LOGIN = "sfdcInternal.isSessionIdLogin"; //$NON-NLS-1$ public static final String SFDC_INTERNAL_SESSION_ID = "sfdcInternal.sessionId"; //$NON-NLS-1$ // salesforce client connectivity public static final String USERNAME = "sfdc.username"; //$NON-NLS-1$ public static final String PASSWORD = "sfdc.password"; //$NON-NLS-1$ public static final String ENDPOINT = "sfdc.endpoint"; //$NON-NLS-1$ public static final String PROXY_HOST = "sfdc.proxyHost"; //$NON-NLS-1$ public static final String PROXY_PORT = "sfdc.proxyPort"; //$NON-NLS-1$ public static final String PROXY_USERNAME = "sfdc.proxyUsername"; //$NON-NLS-1$ public static final String PROXY_PASSWORD = "sfdc.proxyPassword"; //$NON-NLS-1$ public static final String PROXY_NTLM_DOMAIN = "sfdc.proxyNtlmDomain"; //$NON-NLS-1$ public static final String TIMEOUT_SECS = "sfdc.timeoutSecs"; //$NON-NLS-1$ public static final String CONNECTION_TIMEOUT_SECS = "sfdc.connectionTimeoutSecs"; //$NON-NLS-1$ public static final String NO_COMPRESSION = "sfdc.noCompression"; //$NON-NLS-1$ public static final String ENABLE_RETRIES = "sfdc.enableRetries"; //$NON-NLS-1$ public static final String MAX_RETRIES = "sfdc.maxRetries"; //$NON-NLS-1$ public static final String MIN_RETRY_SLEEP_SECS = "sfdc.minRetrySleepSecs"; //$NON-NLS-1$ public static final String DEBUG_MESSAGES = "sfdc.debugMessages"; //$NON-NLS-1$ public static final String DEBUG_MESSAGES_FILE = "sfdc.debugMessagesFile"; //$NON-NLS-1$ public static final String RESET_URL_ON_LOGIN = "sfdc.resetUrlOnLogin"; //$NON-NLS-1$ public static final String TRUNCATE_FIELDS = "sfdc.truncateFields";//$NON-NLS-1$ public static final String BULK_API_ENABLED = "sfdc.useBulkApi"; public static final String BULK_API_SERIAL_MODE = "sfdc.bulkApiSerialMode"; public static final String BULK_API_CHECK_STATUS_INTERVAL = "sfdc.bulkApiCheckStatusInterval"; public static final String BULK_API_ZIP_CONTENT = "sfdc.bulkApiZipContent"; public static final String WIRE_OUTPUT = "sfdc.wireOutput"; public static final String TIMEZONE = "sfdc.timezone"; public static final String OAUTH_PREFIX = "sfdc.oauth."; public static final String OAUTH_PARTIAL_BULK = "bulk"; public static final String OAUTH_PARTIAL_PARTNER = "partner"; public static final String OAUTH_PARTIAL_SERVER = "server"; public static final String OAUTH_PARTIAL_CLIENTSECRET = "clientsecret"; public static final String OAUTH_PARTIAL_CLIENTID = "clientid"; public static final String OAUTH_PARTIAL_REDIRECTURI = "redirecturi"; public static final String OAUTH_PARTIAL_BULK_CLIENTID = OAUTH_PARTIAL_BULK + "." + OAUTH_PARTIAL_CLIENTID; public static final String OAUTH_PARTIAL_PARTNER_CLIENTID = OAUTH_PARTIAL_PARTNER + "." + OAUTH_PARTIAL_CLIENTID; public static final String OAUTH_ENVIRONMENTS = OAUTH_PREFIX + "environments"; public static final String OAUTH_ENVIRONMENT = OAUTH_PREFIX + "environment"; public static final String OAUTH_ACCESSTOKEN = OAUTH_PREFIX + "accesstoken"; public static final String OAUTH_REFRESHTOKEN = OAUTH_PREFIX + "refreshtoken"; public static final String OAUTH_SERVER = OAUTH_PREFIX + OAUTH_PARTIAL_SERVER; public static final String OAUTH_CLIENTSECRET = OAUTH_PREFIX + OAUTH_PARTIAL_CLIENTSECRET; public static final String OAUTH_CLIENTID = OAUTH_PREFIX + OAUTH_PARTIAL_CLIENTID; public static final String OAUTH_REDIRECTURI = OAUTH_PREFIX + OAUTH_PARTIAL_REDIRECTURI; public static final String OAUTH_LOGIN_FROM_BROWSER = OAUTH_PREFIX + "loginfrombrowser"; public static final String REUSE_CLIENT_CONNECTION = "sfdc.reuseClientConnection"; // salesforce operation parameters public static final String INSERT_NULLS = "sfdc.insertNulls"; //$NON-NLS-1$ public static final String ENTITY = "sfdc.entity"; //$NON-NLS-1$ public static final String LOAD_BATCH_SIZE = "sfdc.loadBatchSize"; //$NON-NLS-1$ public static final String ASSIGNMENT_RULE = "sfdc.assignmentRule"; //$NON-NLS-1$ public static final String EXTERNAL_ID_FIELD = "sfdc.externalIdField"; //$NON-NLS-1$ public static final String EXTRACT_REQUEST_SIZE = "sfdc.extractionRequestSize"; //$NON-NLS-1$ public static final String EXTRACT_SOQL = "sfdc.extractionSOQL"; //$NON-NLS-1$ public static final String SORT_EXTRACT_FIELDS = "sfdc.sortExtractionFields"; //$NON-NLS-1$ public static final String LOAD_PRESERVE_WHITESPACE_IN_RICH_TEXT = "sfdc.load.preserveWhitespaceInRichText"; // process configuration (action parameters) public static final String OPERATION = "process.operation"; //$NON-NLS-1$ public static final String MAPPING_FILE = "process.mappingFile"; //$NON-NLS-1$ public static final String EURO_DATES = "process.useEuropeanDates"; //$NON-NLS-1$ // process configuration public static final String OUTPUT_STATUS_DIR = "process.statusOutputDirectory"; //$NON-NLS-1$ public static final String OUTPUT_SUCCESS = "process.outputSuccess"; //$NON-NLS-1$ public static final String ENABLE_EXTRACT_STATUS_OUTPUT = "process.enableExtractStatusOutput"; //$NON-NLS-1$ public static final String ENABLE_LAST_RUN_OUTPUT = "process.enableLastRunOutput"; //$NON-NLS-1$ public static final String LAST_RUN_OUTPUT_DIR = "process.lastRunOutputDirectory"; //$NON-NLS-1$ public static final String OUTPUT_ERROR = "process.outputError"; //$NON-NLS-1$ public static final String OUTPUT_UNPROCESSED_RECORDS = "process.unprocessedRecords"; //$NON-NLS-1$ public static final String LOAD_ROW_TO_START_AT = "process.loadRowToStartAt"; //$NON-NLS-1$ public static final String INITIAL_LAST_RUN_DATE = "process.initialLastRunDate"; public static final String ENCRYPTION_KEY_FILE = "process.encryptionKeyFile"; //$NON-NLS-1$ // data access configuration (e.g., for CSV file, database, etc). public static final String DAO_TYPE = "dataAccess.type"; //$NON-NLS-1$ public static final String DAO_NAME = "dataAccess.name"; //$NON-NLS-1$ public static final String DAO_READ_BATCH_SIZE = "dataAccess.readBatchSize"; public static final String DAO_WRITE_BATCH_SIZE = "dataAccess.writeBatchSize"; public static final String DAO_SKIP_TOTAL_COUNT = "dataAccess.skipTotalCount"; /* * TODO: when batching is introduced to the DataAccess, these parameters will become useful * public static final String DAO_REQUEST_SIZE = "dataAccess.extractionRequestSize"; * public static final String DAO_BATCH_SIZE = "dataAccess.batchSize"; */ public static final String READ_UTF8 = "dataAccess.readUTF8"; //$NON-NLS-1$ public static final String WRITE_UTF8 = "dataAccess.writeUTF8"; //$NON-NLS-1$ public static final String PILOT_PROPERTY_PREFIX = "pilot."; /* public static final String ENABLE_BULK_QUERY_PK_CHUNKING = PILOT_PROPERTY_PREFIX + "sfdc.enableBulkQueryPKChunking"; public static final String BULK_QUERY_PK_CHUNK_SIZE = PILOT_PROPERTY_PREFIX + "sfdc.bulkQueryPKChunkSize"; public static final String BULK_QUERY_PK_CHUNK_START_ROW = PILOT_PROPERTY_PREFIX + "sfdc.bulkQueryChunkStartRow"; */ public static final String DUPLICATE_RULE_ALLOW_SAVE = PILOT_PROPERTY_PREFIX + "sfdc.duplicateRule.allowSave"; //$NON-NLS-1$ public static final String DUPLICATE_RULE_INCLUDE_RECORD_DETAILS = PILOT_PROPERTY_PREFIX + "sfdc.duplicateRule.includeRecordDetails"; //$NON-NLS-1$ public static final String DUPLICATE_RULE_RUN_AS_CURRENT_USER = PILOT_PROPERTY_PREFIX + "sfdc.duplicateRule.runAsCurrentUser"; //$NON-NLS-1$ public static final String BULKV2_API_ENABLED = PILOT_PROPERTY_PREFIX + "sfdc.useBulkV2Api"; /** * Indicates whether a value as been changed */ private boolean dirty = false; /** * The file name used by the <code>load</code> method to load a property file. This filename is * used to save the properties file when <code>save</code> is called. */ private String filename; /** * The <code>lastRun</code> is for last run statistics file */ private LastRun lastRun; /** * <code>encrypter</code> is a utility used internally in the config for reading/writing * encrypted values. Right now, the list of encrypted values is known to this class only. */ private final EncryptionAesUtil encrypter = new EncryptionAesUtil(); private final String configDir; /** * <code>dateFormatter</code> will be used for getting dates in/out of the configuration * file(s) */ public static final DateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); /** * The string representation used for <code>true</code>(<code>"true"</code>). */ public static final String TRUE = "true"; //$NON-NLS-1$ /** * The string representation used for <code>false</code>(<code>"false"</code>). */ public static final String FALSE = "false"; //$NON-NLS-1$ /** * communications with bulk api always use UTF8 */ public static final String BULK_API_ENCODING = "UTF-8"; public static final String CONFIG_FILE = "config.properties"; //$NON-NLS-1$ public static final String CLI_OPTION_RUN_MODE = "run.mode"; public static final String RUN_MODE_UI_VAL = "ui"; public static final String RUN_MODE_BATCH_VAL = "batch"; public static final String CLI_OPTION_GMT_FOR_DATE_FIELD_VALUE = "datefield.usegmt"; public static final String CLI_OPTION_SWT_NATIVE_LIB_IN_JAVA_LIB_PATH = "swt.nativelib.inpath"; public static final String CLI_OPTION_CONFIG_DIR_PROP = "salesforce.config.dir"; public static final String CLI_OPTION_API_VERSION="salesforce.api.version"; public static final String CLI_OPTION_READ_ONLY_CONFIG_PROPERTIES = "config.properties.readonly"; public static final String CONFIG_DIR_DEFAULT_VALUE = "configs"; public static final String SAVE_BULK_SERVER_LOAD_AND_RAW_RESULTS_IN_CSV = "process.bulk.saveServerLoadAndRawResultsInCSV"; private static final String LAST_RUN_FILE_SUFFIX = "_lastRun.properties"; //$NON-NLS-1$ // Following properties are read-only, i.e. they are not overridden during save() to config.properties // - These properties are not set in Advanced Settings dialog. // - Make sure to list all sensitive properties such as password because these properties are not saved. private static final String[] READ_ONLY_PROPERTY_NAMES = { PASSWORD, PROXY_PASSWORD, OAUTH_ACCESSTOKEN, OAUTH_REFRESHTOKEN, EXTERNAL_ID_FIELD, EXTRACT_SOQL, OUTPUT_SUCCESS, OUTPUT_ERROR, DAO_NAME, DAO_TYPE, ENTITY, OPERATION, DEBUG_MESSAGES_FILE }; /** * Creates an empty config that loads from and saves to the a file. <p> Use the methods * <code>load()</code> and <code>save()</code> to load and store this preference store. </p> * * @param filename the file name * @see #load() * @see #save() */ private Config(String filename, String lastRunFileNamePrefix, Map<String, String> overridesMap) throws ConfigInitializationException, IOException { properties = new LinkedProperties(); this.filename = filename; File configFile = new File(this.filename); this.configDir = configFile.getParentFile().getAbsolutePath(); // initialize with defaults this.setDefaults(); // load from config.properties file this.load(); // load parameter overrides after loading from config.properties // parameter overrides are from two places: // 1. process-conf.properties for CLI mode // 2. command line options for both CLI and UI modes this.loadParameterOverrides(overridesMap); // last run gets initialized after loading config and overrides // since config params are needed for initializing last run. initializeLastRun(lastRunFileNamePrefix); // Properties initialization completed. Configure OAuth environment next setOAuthEnvironment(getString(OAUTH_ENVIRONMENT)); } private void initializeLastRun(String lastRunFileNamePrefix) { if (lastRunFileNamePrefix == null || lastRunFileNamePrefix.isBlank()) { lastRunFileNamePrefix = getString(Config.CLI_OPTION_RUN_MODE); } String lastRunFileName = lastRunFileNamePrefix + LAST_RUN_FILE_SUFFIX; String lastRunDir = getString(Config.LAST_RUN_OUTPUT_DIR); if (lastRunDir == null || lastRunDir.length() == 0) { lastRunDir = this.configDir; } this.lastRun = new LastRun(lastRunFileName, lastRunDir, getBoolean(Config.ENABLE_LAST_RUN_OUTPUT)); // Need to initialize last run date if it's present neither in config or override lastRun.setDefault(LastRun.LAST_RUN_DATE, getString(INITIAL_LAST_RUN_DATE)); try { this.lastRun.load(); } catch (IOException e) { logger.warn(Messages.getFormattedString("LastRun.errorLoading", new String[]{ this.lastRun.getFullPath(), e.getMessage()}), e); } } private boolean useBulkApiByDefault() { return false; } /** * This sets the current defaults. */ private void setDefaults() { setDefaultValue(HIDE_WELCOME_SCREEN, true); setDefaultValue(CSV_DELIMETER_COMMA, true); setDefaultValue(CSV_DELIMETER_TAB, true); setDefaultValue(CSV_DELIMETER_OTHER, false); setDefaultValue(CSV_DELIMETER_OTHER_VALUE, "-"); setDefaultValue(ENDPOINT, DEFAULT_ENDPOINT_URL); setDefaultValue(LOAD_BATCH_SIZE, useBulkApiByDefault() ? DEFAULT_BULK_API_BATCH_SIZE : DEFAULT_LOAD_BATCH_SIZE); setDefaultValue(LOAD_ROW_TO_START_AT, 0); setDefaultValue(TIMEOUT_SECS, DEFAULT_TIMEOUT_SECS); setDefaultValue(CONNECTION_TIMEOUT_SECS, DEFAULT_CONNECTION_TIMEOUT_SECS); setDefaultValue(ENABLE_RETRIES, true); setDefaultValue(MAX_RETRIES, DEFAULT_MAX_RETRIES); setDefaultValue(MIN_RETRY_SLEEP_SECS, DEFAULT_MIN_RETRY_SECS); setDefaultValue(ASSIGNMENT_RULE, ""); //$NON-NLS-1$ setDefaultValue(INSERT_NULLS, false); setDefaultValue(ENABLE_EXTRACT_STATUS_OUTPUT, false); setDefaultValue(ENABLE_LAST_RUN_OUTPUT, true); setDefaultValue(RESET_URL_ON_LOGIN, true); setDefaultValue(EXTRACT_REQUEST_SIZE, DEFAULT_EXTRACT_REQUEST_SIZE); setDefaultValue(SORT_EXTRACT_FIELDS, true); setDefaultValue(DAO_WRITE_BATCH_SIZE, DEFAULT_DAO_WRITE_BATCH_SIZE); setDefaultValue(DAO_READ_BATCH_SIZE, DEFAULT_DAO_READ_BATCH_SIZE); setDefaultValue(TRUNCATE_FIELDS, true); // TODO: When we're ready, make Bulk API turned on by default. setDefaultValue(BULK_API_ENABLED, useBulkApiByDefault()); setDefaultValue(BULK_API_SERIAL_MODE, false); setDefaultValue(BULK_API_ZIP_CONTENT, false); setDefaultValue(BULK_API_CHECK_STATUS_INTERVAL, DEFAULT_BULK_API_CHECK_STATUS_INTERVAL); setDefaultValue(WIRE_OUTPUT, false); setDefaultValue(TIMEZONE, TimeZone.getDefault().getID()); //sfdcInternal settings setDefaultValue(SFDC_INTERNAL, false); setDefaultValue(SFDC_INTERNAL_IS_SESSION_ID_LOGIN, false); setDefaultValue(SFDC_INTERNAL_SESSION_ID, (String) null); //oauth settings setDefaultValue(OAUTH_SERVER, DEFAULT_ENDPOINT_URL); setDefaultValue(OAUTH_REDIRECTURI, DEFAULT_ENDPOINT_URL); setDefaultValue(OAUTH_ENVIRONMENT, OAUTH_PROD_ENVIRONMENT_VAL); setDefaultValue(OAUTH_ENVIRONMENTS, OAUTH_PROD_ENVIRONMENT_VAL + "," + OAUTH_SB_ENVIRONMENT_VAL); /* sfdc.oauth.<env>.<bulk | partner>.clientid = DataLoaderBulkUI | DataLoaderPartnerUI */ setDefaultValue(OAUTH_PREFIX + OAUTH_PROD_ENVIRONMENT_VAL + "." + OAUTH_PARTIAL_BULK_CLIENTID, OAUTH_BULK_CLIENTID_VAL); setDefaultValue(OAUTH_PREFIX + OAUTH_PROD_ENVIRONMENT_VAL + "." + OAUTH_PARTIAL_PARTNER_CLIENTID, OAUTH_PARTNER_CLIENTID_VAL); setDefaultValue(OAUTH_PREFIX + OAUTH_SB_ENVIRONMENT_VAL + "." + OAUTH_PARTIAL_BULK_CLIENTID, OAUTH_BULK_CLIENTID_VAL); setDefaultValue(OAUTH_PREFIX + OAUTH_SB_ENVIRONMENT_VAL + "." + OAUTH_PARTIAL_PARTNER_CLIENTID, OAUTH_PARTNER_CLIENTID_VAL); /* production server and redirecturi, sandbox server and redirecturi */ setDefaultValue(OAUTH_PREFIX + OAUTH_PROD_ENVIRONMENT_VAL + "." + OAUTH_PARTIAL_SERVER, OAUTH_PROD_SERVER_VAL); setDefaultValue(OAUTH_PREFIX + OAUTH_PROD_ENVIRONMENT_VAL + "." + OAUTH_PARTIAL_REDIRECTURI, OAUTH_PROD_REDIRECTURI_VAL); setDefaultValue(OAUTH_PREFIX + OAUTH_SB_ENVIRONMENT_VAL + "." + OAUTH_PARTIAL_SERVER, OAUTH_SB_SERVER_VAL); setDefaultValue(OAUTH_PREFIX + OAUTH_SB_ENVIRONMENT_VAL + "." + OAUTH_PARTIAL_REDIRECTURI, OAUTH_SB_REDIRECTURI_VAL); setDefaultValue(REUSE_CLIENT_CONNECTION, true); /* setDefaultValue(ENABLE_BULK_QUERY_PK_CHUNKING, false); setDefaultValue(BULK_QUERY_PK_CHUNK_SIZE, DEFAULT_BULK_QUERY_PK_CHUNK_SIZE); setDefaultValue(BULK_QUERY_PK_CHUNK_START_ROW, ""); */ setDefaultValue(DUPLICATE_RULE_ALLOW_SAVE, false); setDefaultValue(DUPLICATE_RULE_INCLUDE_RECORD_DETAILS, false); setDefaultValue(DUPLICATE_RULE_RUN_AS_CURRENT_USER, false); setDefaultValue(BUFFER_UNPROCESSED_BULK_QUERY_RESULTS, false); setDefaultValue(BULKV2_API_ENABLED, false); setDefaultValue(OAUTH_LOGIN_FROM_BROWSER, true); setDefaultValue(LOAD_PRESERVE_WHITESPACE_IN_RICH_TEXT, true); setDefaultValue(Config.CLI_OPTION_RUN_MODE, Config.RUN_MODE_UI_VAL); setDefaultValue(SAVE_BULK_SERVER_LOAD_AND_RAW_RESULTS_IN_CSV, false); } /** * Returns true if the name is a key in the config * * @param name the name of the key */ public boolean contains(String name) { return properties.containsKey(name) || lastRun.hasParameter(name) && lastRun.containsKey(name); } /** * Gets boolean for a given name * * @return boolean */ public boolean getBoolean(String name) { String value = getParamValue(name); if (value == null || value.length() == 0) return BOOLEAN_DEFAULT; if (value.equals(Config.TRUE)) return true; return false; } /** * Gets double for a given name. * * @return double */ public double getDouble(String name) throws ParameterLoadException { String value = getParamValue(name); if (value == null || value.length() == 0) return DOUBLE_DEFAULT; double ival; try { ival = Double.parseDouble(value); } catch (NumberFormatException e) { String errMsg = Messages.getFormattedString("Config.errorParameterLoad", new String[]{name, Double.class.getName()}); logger.warn(errMsg, e); throw new ParameterLoadException(e.getMessage(), e); } return ival; } /** * Gets float for a given name. * * @return float */ public float getFloat(String name) throws ParameterLoadException { String value = getParamValue(name); if (value == null || value.length() == 0) return FLOAT_DEFAULT; float ival = FLOAT_DEFAULT; try { ival = Float.parseFloat(value); } catch (NumberFormatException e) { String errMsg = Messages.getFormattedString("Config.errorParameterLoad", new String[]{name, Float.class.getName()}); logger.warn(errMsg, e); throw new ParameterLoadException(e.getMessage(), e); } return ival; } /** * Gets int for a given name. * * @return int */ public int getInt(String name) throws ParameterLoadException { String value = getParamValue(name); if (value == null || value.length() == 0) return INT_DEFAULT; int ival = 0; try { ival = Integer.parseInt(value); } catch (NumberFormatException e) { String errMsg = Messages.getFormattedString("Config.errorParameterLoad", new String[]{name, Integer.class.getName()}); logger.warn(errMsg, e); throw new ParameterLoadException(e.getMessage(), e); } return ival; } /** * Gets long for a given name. * * @return long */ public long getLong(String name) throws ParameterLoadException { String value = getParamValue(name); if (value == null || value.length() == 0) return LONG_DEFAULT; long ival = LONG_DEFAULT; try { ival = Long.parseLong(value); } catch (NumberFormatException e) { String errMsg = Messages.getFormattedString("Config.errorParameterLoad", new String[]{name, Long.class.getName()}); logger.warn(errMsg, e); throw new ParameterLoadException(e.getMessage(), e); } return ival; } /** * Gets required string param for a given name. If not found, throws an exception * * @return string */ public String getStringRequired(String name) throws ParameterLoadException { String value = getString(name); if (value == null || value.length() == 0) { String errMsg = Messages.getFormattedString("Config.errorNoRequiredParameter", name); //$NON-NLS-1$ logger.fatal(errMsg); throw new ParameterLoadException(errMsg); } return value; } /** * Gets string for a given name. * * @return string */ public String getString(String name) { String value = getParamValue(name); if (value == null) return STRING_DEFAULT; return value; } public ArrayList<String> getStrings(String name) { String values = getString(name); ArrayList<String> list = new ArrayList<>(); if (values != null && !values.trim().isEmpty()) { Collections.addAll(list, values.trim().split(",")); } return list; } /** * Gets an enum value for a given config name. */ public <T extends Enum<T>> T getEnum(Class<T> enumClass, String name) { return Enum.valueOf(enumClass, getString(name)); } public TimeZone getTimeZone() { return TimeZone.getTimeZone(getString(TIMEZONE)); } /** * Gets path to a config file given the config file property name * * @param configFileProperty property containing a config filename * @return Config filename path based on config property value. Config file is assumed to reside * in the global config directory */ public String getConfigFilename(String configFileProperty) { String value = getParamValue(configFileProperty); if (value == null) return null; return constructConfigFilePath(new File(value).getName()); } public String getLastRunFilename() { return this.lastRun == null ? null : this.lastRun.getFullPath(); } /** * Constructs config file path based on the configuration directory and the passed in config * filename * * @param configFilename Config filename that resides in the config directory * @return Full path to the config file */ public String constructConfigFilePath(String configFilename) { File configPathFile = new File(this.filename).getParentFile(); return new File(configPathFile, configFilename).getAbsolutePath(); } /** * @return Date */ public Date getDate(String name) throws ParameterLoadException { String value = getParamValue(name); if (value == null || value.length() == 0) return Calendar.getInstance().getTime(); Date dval = null; try { dval = DATE_FORMATTER.parse(value); } catch (ParseException e) { String errMsg = Messages.getFormattedString("Config.errorParameterLoad", new String[]{name, Date.class.getName()}); logger.warn(errMsg, e); throw new ParameterLoadException(e.getMessage(), e); } return dval; } /** * Get map from a string param value. String format of map is key1=val1,key2=val2,... * * @return Map */ public Map<String, String> getMap(String name) throws ParameterLoadException { String value = getParamValue(name); if (value == null || value.length() == 0) return MAP_STRING_DEFAULT; Map<String, String> mval = new HashMap<String, String>(); String[] pairs = value.split(","); for (String pair : pairs) { String[] nameValue = pair.split("="); if (nameValue.length != 2) { String errMsg = Messages.getFormattedString("Config.errorParameterLoad", new String[]{name, Map.class.getName()}); logger.warn(errMsg); throw new ParameterLoadException(errMsg); } mval.put(nameValue[0], nameValue[1]); } return mval; } /** * @return parameter value */ private String getParamValue(String name) { String propValue; if (lastRun != null && lastRun.hasParameter(name)) { propValue = lastRun.getProperty(name); } else { propValue = properties != null ? properties.getProperty(name) : null; } // check if a property's value is configured when it used to be a pilot property // if value not set. if (propValue == null && !name.startsWith(PILOT_PROPERTY_PREFIX)) { String pilotName = PILOT_PROPERTY_PREFIX + name; String pilotValue = getParamValue(pilotName); if (pilotValue != null && !pilotValue.isEmpty()) { // if picking up the value from a pilot property that is no longer in pilot, // set the value for the new property to be the same as the value of the pilot property doSetPropertyAndUpdateConfig(name, propValue, pilotValue); } propValue = pilotValue; } return propValue; } /** * Prints the contents of this preference store to the given print stream. * * @param out the print stream */ public void list(PrintStream out) { properties.list(out); lastRun.list(out); } /** * Prints the contents of this preference store to the given print writer. * * @param out the print writer */ public void list(PrintWriter out) { properties.list(out); lastRun.list(out); } /** * Loads this preference store from the file established in the constructor * <code>Config(java.lang.String)</code> (or by <code>setFileName</code>). Default preference * values are not affected. * * @throws java.io.IOException if there is a problem loading this store */ public void load() throws IOException, ConfigInitializationException { if (filename == null) { logger.fatal(Messages.getString("Config.fileMissing")); throw new IOException(Messages.getString("Config.fileMissing")); //$NON-NLS-1$ } FileInputStream in = new FileInputStream(filename); try { load(in); } finally { in.close(); } } /** * Loads this preference store from the given input stream. Default preference values are not * affected. * * @param in the input stream * @throws ConfigInitializationException If there's a problem loading the parameters * @throws IOException IF there's an I/O problem loading parameter from file */ private void load(InputStream in) throws ConfigInitializationException, IOException { try { properties.load(in); } catch (IOException e) { logger.fatal(Messages.getFormattedString("Config.errorPropertiesLoad", e.getMessage())); throw e; } // paramter post-processing postLoad(properties, true); dirty = false; } private void restoreReadOnlyProperty(String propertyName) { String preservedPropertyValue = (String)this.readOnlyProperties.get(propertyName); if (preservedPropertyValue == null) { this.properties.remove(propertyName); return; } this.properties.put(propertyName, preservedPropertyValue); } private void preserveReadOnlyProperty(Map<?, ?> propMap, String propertyName) { if (this.readOnlyProperties == null) { this.readOnlyProperties = new Properties(); } String propertyValueToPreserve = (String) propMap.get(propertyName); if (propertyValueToPreserve == null) { return; } this.readOnlyProperties.put(propertyName, propertyValueToPreserve); } /** * Post process parameters. Right now, only decrypts encrypted values in the map * * @param values Values to be post-processed */ @SuppressWarnings("unchecked") private void postLoad(Map<?, ?> propMap, boolean isConfigFilePropsMap) throws ConfigInitializationException { if (isConfigFilePropsMap) { for (String propertyName : READ_ONLY_PROPERTY_NAMES) { preserveReadOnlyProperty(propMap, propertyName); } } // initialize encryption initEncryption((Map<String, String>) propMap); // decrypt encrypted values decryptPasswordProperty(propMap, PASSWORD); decryptPasswordProperty(propMap, PROXY_PASSWORD); decryptPasswordProperty(propMap, OAUTH_ACCESSTOKEN); decryptPasswordProperty(propMap, OAUTH_REFRESHTOKEN); // Do not load unsupported properties and CLI options even if they are specified in config.properties file if (isConfigFilePropsMap) { removeCLIOptionsFromProperties(); removeUnsupportedProperties(); } } private void decryptPasswordProperty(Map<?, ?> values, String propertyName) throws ConfigInitializationException { @SuppressWarnings("unchecked") Map<String, String> propMap = (Map<String, String>)values; // initialize encryption if (propMap != null && propMap.containsKey(propertyName)) { if (propMap.containsKey(propertyName + DECRYPTED_SUFFIX)) { String decryptedPropValue = propMap.get(propertyName + DECRYPTED_SUFFIX); String propValueToBeDecrypted = propMap.get(propertyName); if (decryptedPropValue != null && propValueToBeDecrypted != null && decryptedPropValue.equals(propValueToBeDecrypted)) { return; // do not decrypt an already decrypted value } } String propValue = decryptProperty(encrypter, propMap, propertyName, isBatchMode()); if (propValue == null) propValue = ""; propMap.put(propertyName, propValue); // cache decrypted value propMap.put(propertyName + DECRYPTED_SUFFIX, propValue); } } /** * Load config parameter override values. The main use case is loading of overrides from * external config file */ private void loadParameterOverrides(Map<String, String> configOverrideMap) throws ParameterLoadException, ConfigInitializationException { this.parameterOverridesMap = configOverrideMap; // make sure to post-process the args to be loaded postLoad(configOverrideMap, false); // replace values in the Config putValue(configOverrideMap); } /** * Decrypt property with propName using the encrypter. If decryption succeeds, return the * decrypted value * * @return decrypted property value */ static private String decryptProperty(EncryptionAesUtil encrypter, Map<String, String> propMap, String propName, boolean isBatch) throws ParameterLoadException { String propValue = propMap.get(propName); if (propValue != null && propValue.length() > 0) { try { return encrypter.decryptMsg(propValue); } catch (GeneralSecurityException e) { // if running in the UI, we can ignore encryption errors if (isBatch) { String errMsg = Messages.getFormattedString("Config.errorParameterLoad", new String[]{propName, String.class.getName()}); logger.error(errMsg, e); throw new ParameterLoadException(errMsg, e); } else { return null; } } catch (Exception e) { String errMsg = Messages.getFormattedString("Config.errorParameterLoad", new String[]{propName, String.class.getName()}); logger.error(errMsg, e); throw new ParameterLoadException(errMsg, e); } } return propValue; } /** * @throws ConfigInitializationException */ private void initEncryption(Map<String, String> values) throws ConfigInitializationException { if (values == null) { return; } // initialize encrypter String keyFile = values.get(ENCRYPTION_KEY_FILE); if (keyFile != null && keyFile.length() != 0) { try { encrypter.setCipherKeyFromFilePath(keyFile); } catch (Exception e) { String errMsg = Messages.getFormattedString("Config.errorSecurityInit", new String[]{keyFile, e.getMessage()}); logger.error(errMsg); throw new ConfigInitializationException(errMsg); } } } /** * Returns whether the config needs saving * * @return boolean */ public boolean needsSaving() { return dirty; } /** * Returns an enumeration of all preferences known to this config * * @return an array of preference names */ public String[] preferenceNames() { ArrayList<String> list = new ArrayList<String>(); Enumeration<?> en = properties.propertyNames(); while (en.hasMoreElements()) { list.add((String) en.nextElement()); } return list.toArray(new String[list.size()]); } /** * Puts a set of values from a map into config * * @param values Map of overriding values */ public void putValue(Map<String, String> values) throws ParameterLoadException, ConfigInitializationException { if (values == null) { return; } for (String key : values.keySet()) { putValue(key, values.get(key)); } } /** * Puts a value into the config */ public void putValue(String name, String value) { String oldValue = getString(name); if (oldValue == null || !oldValue.equals(value)) { setValue(name, value); dirty = true; } } /** * Saves the preferences to the file from which they were originally loaded. * * @throws java.io.IOException if there is a problem saving this store */ public void save() throws IOException, GeneralSecurityException { if (getString(Config.CLI_OPTION_RUN_MODE).equalsIgnoreCase(Config.RUN_MODE_BATCH_VAL) || getBoolean(CLI_OPTION_READ_ONLY_CONFIG_PROPERTIES)) { return; // do not save as it updates config.properties } if (filename == null) { throw new IOException(Messages.getString("Config.fileMissing")); //$NON-NLS-1$ } Properties inMemoryProperties = new Properties(); inMemoryProperties.putAll(this.properties); // do not save properties set through parameter overrides if (this.parameterOverridesMap != null) { for (String propertyName : this.parameterOverridesMap.keySet()) { this.properties.remove(propertyName); } } // keep the property values for the read-only properties as retrieved from config.properties for (String propertyName : READ_ONLY_PROPERTY_NAMES) { this.restoreReadOnlyProperty(propertyName); } removeUnsupportedProperties(); removeDecryptedProperties(); removeCLIOptionsFromProperties(); FileOutputStream out = null; try { out = new FileOutputStream(filename); save(out, "Loader Config"); //$NON-NLS-1$ } finally { if (out != null) { out.close(); } // restore original property values properties = inMemoryProperties; } // save last run statistics lastRun.save(); } private void removeUnsupportedProperties() { // do not save a value for enabling Bulk V2 this.properties.remove(BULKV2_API_ENABLED); } private void removeDecryptedProperties() { this.properties.remove(PASSWORD + DECRYPTED_SUFFIX); this.properties.remove(PROXY_PASSWORD + DECRYPTED_SUFFIX); this.properties.remove(OAUTH_ACCESSTOKEN + DECRYPTED_SUFFIX); this.properties.remove(OAUTH_REFRESHTOKEN + DECRYPTED_SUFFIX); } private void removeCLIOptionsFromProperties() { Set<String> keys = this.properties.stringPropertyNames(); Field[] allFields = Config.class.getDeclaredFields(); for (Field field : allFields) { if (field.getName().startsWith("CLI_OPTION_")) { String fieldVal = null; try { fieldVal = (String)field.get(null); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (fieldVal == null) { continue; } for (String key : keys) { if (key.equalsIgnoreCase(fieldVal)) { this.properties.remove(key); } } } } } /** * Save statistics from the last run */ public void saveLastRun() throws IOException { lastRun.save(); } /** * @param propName name of the property * @return old value of the property */ private String encryptProperty(String propName) throws GeneralSecurityException, UnsupportedEncodingException { String oldValue = getString(propName); if (oldValue != null && oldValue.length() > 0) { putValue(propName, encrypter.encryptMsg(oldValue)); } return oldValue; } /** * Saves this config to the given output stream. The given string is inserted as header * information. * * @param out the output stream * @param header the header * @throws java.io.IOException if there is a problem saving this store */ private void save(OutputStream out, String header) throws IOException { properties.store(out, header); dirty = false; } public void setValue(String name, Map<String, String> valueMap) { StringBuilder sb = new StringBuilder(); for (String key : valueMap.keySet()) { // add comma for subsequent entries if (sb.length() != 0) { sb.append(","); } sb.append(key + "=" + valueMap.get(key)); } putValue(name, sb.toString()); } /** * Sets the name of the file used when loading and storing this config * * @param name the file name * @see #load() * @see #save() */ public void setFilename(String name) { filename = name; } /** * @return the current configuration filename */ public String getFilename() { return filename; } /* * Sets a date */ public void setValue(String name, Date value) { setValue(name, value, false); } private void setDefaultValue(String name, Date value) { setValue(name, value, true); } private void setValue(String name, Date value, boolean skipIfAlreadySet) { setProperty(name, DATE_FORMATTER.format(value), skipIfAlreadySet); } /** * Sets a list of String values */ public void setValue(String name, String... values) { setValue(name, false, values); } private void setDefaultValue(String name, String... values) { setValue(name, true, values); } private void setValue(String name, boolean skipIfAlreadySet, String... values) { if (values != null && values.length > 1) { StringJoiner joiner = new StringJoiner(","); for (String value : values) { joiner.add(value); } setProperty(name, joiner.toString(), skipIfAlreadySet); } else if (values != null && values.length > 0) { setProperty(name, values[0], skipIfAlreadySet); } else { setProperty(name, null, skipIfAlreadySet); } } /** * Sets a value other than a date or a list of String values */ public <T> void setValue(String name, T value) { setValue(name, value, false); } private <T> void setDefaultValue(String name, T value) { setValue(name, value, true); } private <T> void setValue(String name, T value, boolean skipIfAlreadySet) { if (value != null) { setProperty(name, value.toString(), skipIfAlreadySet); } } /** * @param name * @param newValue */ private void setProperty(String name, String newValue, boolean skipIfAlreadySet) { final String oldValue = getString(name); if (skipIfAlreadySet && oldValue != null && !oldValue.isEmpty()) { // do not override the old value return; } final boolean paramChanged = (oldValue == null || oldValue.length() == 0) ? (newValue != null && newValue .length() > 0) : !oldValue.equals(newValue); if (paramChanged) { doSetPropertyAndUpdateConfig(name, oldValue, newValue); } } private void doSetPropertyAndUpdateConfig(String name, String oldValue, String newValue) { this.dirty = true; configChanged(name, oldValue, newValue); if (lastRun != null && lastRun.hasParameter(name)) { lastRun.put(name, newValue); } else { properties.put(name, newValue); } } public boolean isBatchMode() { return (Config.RUN_MODE_BATCH_VAL.equalsIgnoreCase(getString(Config.CLI_OPTION_RUN_MODE))); } public int getLoadBatchSize() { boolean bulkApi = isBulkAPIEnabled(); int bs = -1; try { bs = getInt(LOAD_BATCH_SIZE); } catch (ParameterLoadException e) { } int maxBatchSize = bulkApi ? MAX_BULK_API_BATCH_SIZE : MAX_LOAD_BATCH_SIZE; return bs > maxBatchSize ? maxBatchSize : bs > 0 ? bs : getDefaultBatchSize(bulkApi); } public int getDefaultBatchSize(boolean bulkApi) { return bulkApi ? DEFAULT_BULK_API_BATCH_SIZE : DEFAULT_LOAD_BATCH_SIZE; } public boolean useBulkAPIForCurrentOperation() { return isBulkAPIEnabled() && isBulkApiOperation(); } public boolean isBulkAPIEnabled() { return getBoolean(BULK_API_ENABLED); } public boolean isBulkV2APIEnabled() { return isBulkAPIEnabled() && getBoolean(BULKV2_API_ENABLED); } private boolean isBulkApiOperation() { return getOperationInfo().bulkAPIEnabled(); } public OperationInfo getOperationInfo() { return getEnum(OperationInfo.class, OPERATION); } private static final Charset UTF8 = Charset.forName("UTF-8"); public String getCsvEncoding(boolean isWrite) { // charset is for CSV read unless isWrite is set to true String configProperty = READ_UTF8; if (isWrite) { configProperty = WRITE_UTF8; logger.debug("Getting charset for writing to CSV"); } else { logger.debug("Getting charset for reading from CSV"); } if (getBoolean(configProperty)) { logger.debug("Using UTF8 charset because '" + configProperty +"' is set to true"); return UTF8.name(); } String charset = getDefaultCharsetForCsvReadWrite(); logger.debug("Using charset " + charset); return charset; } private static String defaultCharsetForCsvReadWrite = null; private synchronized static String getDefaultCharsetForCsvReadWrite() { if (defaultCharsetForCsvReadWrite != null) { return defaultCharsetForCsvReadWrite; } String fileEncodingStr = System.getProperty("file.encoding"); if (fileEncodingStr != null && !fileEncodingStr.isBlank()) { for (String charsetName : Charset.availableCharsets().keySet()) { if (fileEncodingStr.equalsIgnoreCase(charsetName)) { logger.debug("Setting the default charset for CSV read and write to the value of file.encoding system property: " + fileEncodingStr); defaultCharsetForCsvReadWrite = charsetName; return charsetName; } } logger.debug("Unable to find the charset '" + fileEncodingStr + "' specified in file.encoding system property among available charsets for the Java VM." ); } logger.debug("Using JVM default charset as the default charset for CSV read and write : " + Charset.defaultCharset().name()); defaultCharsetForCsvReadWrite = Charset.defaultCharset().name(); return defaultCharsetForCsvReadWrite; } private final List<ConfigListener> listeners = new ArrayList<ConfigListener>(); public synchronized void addListener(ConfigListener l) { listeners.add(l); } private synchronized void configChanged(String key, String oldValue, String newValue) { for (ConfigListener l : this.listeners) { l.configValueChanged(key, oldValue, newValue); } } public String getOAuthEnvironmentString(String environmentName, String name) { return getString(OAUTH_PREFIX + environmentName + "." + name); } public void setOAuthEnvironmentString(String environmentName, String name, String... values) { setValue(OAUTH_PREFIX + environmentName + "." + name, values); } public void setOAuthEnvironment(String environment) { String clientId; if (getBoolean(BULK_API_ENABLED)) { clientId = getOAuthEnvironmentString(environment, OAUTH_PARTIAL_BULK_CLIENTID); } else { clientId = getOAuthEnvironmentString(environment, OAUTH_PARTIAL_PARTNER_CLIENTID); } if (clientId == null || clientId.isEmpty()) { clientId = getOAuthEnvironmentString(environment, OAUTH_PARTIAL_CLIENTID); } setValue(OAUTH_ENVIRONMENT, environment); setValue(OAUTH_SERVER, getOAuthEnvironmentString(environment, OAUTH_PARTIAL_SERVER)); setValue(OAUTH_CLIENTID, clientId); setValue(OAUTH_CLIENTSECRET, getOAuthEnvironmentString(environment, OAUTH_PARTIAL_CLIENTSECRET)); setValue(OAUTH_REDIRECTURI, getOAuthEnvironmentString(environment, OAUTH_PARTIAL_REDIRECTURI)); } /** * Create directory provided from the parameter * * @param dirPath - directory to be created * @return True if directory was created successfully or directory already existed False if * directory was failed to create */ private static boolean createDir(File dirPath) { boolean isSuccessful = true; if (!dirPath.exists() || !dirPath.isDirectory()) { isSuccessful = dirPath.mkdirs(); if (isSuccessful) { logger.info("Created config directory: " + dirPath); } else { logger.info("Unable to create config directory: " + dirPath); } } else { logger.info("Config directory already exists: " + dirPath); } return isSuccessful; } /** * Get the current config.properties and load it into the config bean. * @throws ConfigInitializationException */ public static synchronized Config getInstance(String lastRunFilePrefix, Map<String, String> argMap) throws ConfigInitializationException { AppUtil.setConfigurationsDir(argMap); String configurationsDirPath = AppUtil.getConfigurationsDir(); File configurationsDir; final String DEFAULT_CONFIG_FILE = "defaultConfig.properties"; //$NON-NLS-1$ configurationsDir = new File(configurationsDirPath); // Create dir if it doesn't exist boolean isMkdirSuccessfulOrExisting = createDir(configurationsDir); if (!isMkdirSuccessfulOrExisting) { String errorMsg = Messages.getMessage(Config.class, "errorCreatingOutputDir", configurationsDirPath); logger.error(errorMsg); throw new ConfigInitializationException(errorMsg); } // check if the config file exists File configFile = new File(configurationsDir.getAbsolutePath(), CONFIG_FILE); String configFilePath = configFile.getAbsolutePath(); logger.info("Looking for file in config path: " + configFilePath); if (!configFile.exists()) { File defaultConfigFile = new File(configurationsDir, DEFAULT_CONFIG_FILE); logger.debug("Looking for file in config file " + defaultConfigFile.getAbsolutePath()); // If default config exists, copy the default to user config // If doesn't exist, create a blank user config if (defaultConfigFile.exists()) { try { // Copy default config to user config logger.info(String.format("User config file does not exist in '%s' Default config file is copied from '%s'", configFilePath, defaultConfigFile.getAbsolutePath())); Files.copy(defaultConfigFile.toPath(), configFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { String errorMsg = String.format("Failed to copy '%s' to '%s'", defaultConfigFile.getAbsolutePath(), configFile); logger.warn(errorMsg, e); throw new ConfigInitializationException(errorMsg, e); } } else { // extract from the jar AppUtil.extractFromJar("/" + CONFIG_FILE, configFile); } configFile.setWritable(true); configFile.setReadable(true); } else { logger.info("User config is found in " + configFile.getAbsolutePath()); } Config config = null; try { config = new Config(configFilePath, lastRunFilePrefix, argMap); logger.info(Messages.getMessage(Config.class, "configInit")); //$NON-NLS-1$ } catch (IOException | ProcessInitializationException e) { throw new ConfigInitializationException(Messages.getMessage(Config.class, "errorConfigLoad", configFilePath), e); } return config; } public static interface ConfigListener { void configValueChanged(String key, String oldValue, String newValue); } }
package com.softserveinc.tender.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import java.math.BigDecimal; @Entity @Table(name = "proposal") public class Proposal { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Integer id; @ManyToOne @JoinColumn(name = "seller_id", nullable = false) private User seller; @ManyToOne @JoinColumn(name = "tender_id", nullable = false) private Tender tender; @Column(name = "discount_percentage") private Integer discountPercentage; @Column(name = "discount_currency") private BigDecimal discountCurrency; @Column(name = "description") private String description; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public User getSeller() { return seller; } public void setSeller(User seller) { this.seller = seller; } public Tender getTender() { return tender; } public void setTender(Tender tender) { this.tender = tender; } public Integer getDiscountPercentage() { return discountPercentage; } public void setDiscountPercentage(Integer discountPercentage) { this.discountPercentage = discountPercentage; } public BigDecimal getDiscountCurrency() { return discountCurrency; } public void setDiscountCurrency(BigDecimal discountCurrency) { this.discountCurrency = discountCurrency; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
package loci.formats.in; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import ome.xml.model.primitives.Timestamp; import loci.common.DataTools; import loci.common.DateTools; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.meta.MetadataStore; public class BrukerReader extends FormatReader { // -- Constants -- private static final String DATE_FORMAT = "HH:mm:ss d MMM yyyy"; // -- Fields -- private ArrayList<String> pixelsFiles = new ArrayList<String>(); private ArrayList<String> allFiles = new ArrayList<String>(); // -- Constructor -- /** Constructs a new Bruker reader. */ public BrukerReader() { super("Bruker", ""); suffixSufficient = false; domains = new String[] {FormatTools.MEDICAL_DOMAIN}; hasCompanionFiles = true; datasetDescription = "One 'fid' and one 'acqp' plus several other " + "metadata files and a 'pdata' directory"; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isSingleFile(String) */ public boolean isSingleFile(String id) throws FormatException, IOException { return false; } /* @see loci.formats.IFormatReader#isThisType(String, boolean) */ public boolean isThisType(String name, boolean open) { Location file = new Location(name).getAbsoluteFile(); return file.getName().equals("fid") || file.getName().equals("acqp"); } /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { return false; } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); RandomAccessInputStream s = new RandomAccessInputStream(pixelsFiles.get(getSeries())); s.seek(no * FormatTools.getPlaneSize(this)); readPlane(s, x, y, w, h, buf); s.close(); return buf; } /* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */ public String[] getSeriesUsedFiles(boolean noPixels) { FormatTools.assertId(currentId, true, 1); String dir = pixelsFiles.get(getSeries()); Location realDir = new Location(dir).getParentFile(); realDir = realDir.getParentFile(); realDir = realDir.getParentFile(); dir = realDir.getAbsolutePath(); ArrayList<String> files = new ArrayList<String>(); for (String f : allFiles) { if (f.startsWith(dir) && (!f.endsWith("2dseq") || !noPixels)) { files.add(f); } } return files.toArray(new String[files.size()]); } /* @see loci.formats.IFormatReader#fileGroupOption(String) */ public int fileGroupOption(String id) throws FormatException, IOException { return FormatTools.MUST_GROUP; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { pixelsFiles.clear(); allFiles.clear(); } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); Location originalFile = new Location(id).getAbsoluteFile(); Location parent = originalFile.getParentFile().getParentFile(); String[] acquisitionDirs = parent.list(true); Comparator<String> comparator = new Comparator<String>() { public int compare(String s1, String s2) { Integer i1 = 0; try { i1 = new Integer(s1); } catch (NumberFormatException e) { } Integer i2 = 0; try { i2 = new Integer(s2); } catch (NumberFormatException e) { } return i1.compareTo(i2); } }; Arrays.sort(acquisitionDirs, comparator); ArrayList<String> acqpFiles = new ArrayList<String>(); ArrayList<String> recoFiles = new ArrayList<String>(); for (String f : acquisitionDirs) { Location dir = new Location(parent, f); if (dir.isDirectory()) { String[] files = dir.list(true); for (String file : files) { Location child = new Location(dir, file); if (!child.isDirectory()) { allFiles.add(child.getAbsolutePath()); if (file.equals("acqp")) { acqpFiles.add(child.getAbsolutePath()); } } else { Location grandchild = new Location(child, "1"); if (grandchild.exists()) { String[] moreFiles = grandchild.list(true); for (String m : moreFiles) { Location ggc = new Location(grandchild, m); if (!ggc.isDirectory()) { allFiles.add(ggc.getAbsolutePath()); if (m.equals("2dseq")) { pixelsFiles.add(ggc.getAbsolutePath()); } else if (m.equals("reco")) { recoFiles.add(ggc.getAbsolutePath()); } } } } } } if (acqpFiles.size() > pixelsFiles.size()) { acqpFiles.remove(acqpFiles.size() - 1); } if (recoFiles.size() > pixelsFiles.size()) { recoFiles.remove(recoFiles.size() - 1); } } } core = new CoreMetadata[pixelsFiles.size()]; String[] imageNames = new String[pixelsFiles.size()]; String[] timestamps = new String[pixelsFiles.size()]; String[] institutions = new String[pixelsFiles.size()]; String[] users = new String[pixelsFiles.size()]; for (int series=0; series<pixelsFiles.size(); series++) { setSeries(series); core[series] = new CoreMetadata(); String acqData = DataTools.readFile(acqpFiles.get(series)); String[] lines = acqData.split("\n"); String[] sizes = null; String[] ordering = null; int ni = 0, nr = 0, ns = 0; int bits = 0; boolean signed = false; boolean isFloat = false; for (int i=0; i<lines.length; i++) { String line = lines[i]; int index = line.indexOf("="); if (index >= 0) { String key = line.substring(0, index); String value = line.substring(index + 1); if (value.startsWith("(")) { value = lines[i + 1].trim(); if (value.startsWith("<")) { value = value.substring(1, value.length() - 1); } } if (key.length() < 4) { continue; } addSeriesMeta(key.substring(3), value); if (key.equals(" ni = Integer.parseInt(value); } else if (key.equals(" nr = Integer.parseInt(value); } else if (key.equals("##$ACQ_word_size")) { bits = Integer.parseInt(value.substring(1, value.lastIndexOf("_"))); } else if (key.equals("##$BYTORDA")) { core[series].littleEndian = value.toLowerCase().equals("little"); } else if (key.equals("##$ACQ_size")) { sizes = value.split(" "); } else if (key.equals("##$ACQ_obj_order")) { ordering = value.split(" "); } else if (key.equals("##$ACQ_time")) { timestamps[series] = value; } else if (key.equals("##$ACQ_institution")) { institutions[series] = value; } else if (key.equals("##$ACQ_operator")) { users[series] = value; } else if (key.equals("##$ACQ_scan_name")) { imageNames[series] = value; } else if (key.equals("##$ACQ_ns_list_size")) { ns = Integer.parseInt(value); } } } String recoData = DataTools.readFile(recoFiles.get(series)); lines = recoData.split("\n"); for (int i=0; i<lines.length; i++) { String line = lines[i]; int index = line.indexOf("="); if (index >= 0) { String key = line.substring(0, index); String value = line.substring(index + 1); if (value.startsWith("(")) { value = lines[i + 1].trim(); if (value.startsWith("<")) { value = value.substring(1, value.length() - 1); } } if (key.length() < 4) { continue; } addSeriesMeta(key.substring(3), value); if (key.equals("##$RECO_size")) { sizes = value.split(" "); } else if (key.equals("##$RECO_wordtype")) { bits = Integer.parseInt(value.substring(1, value.indexOf("BIT"))); signed = value.indexOf("_SGN_") >= 0; isFloat = !value.endsWith("_INT"); } } } int td = Integer.parseInt(sizes[0]); int ys = sizes.length > 1 ? Integer.parseInt(sizes[1]) : 0; int zs = sizes.length > 2 ? Integer.parseInt(sizes[2]) : 0; if (sizes.length == 2) { if (ni == 1) { core[series].sizeY = ys; core[series].sizeZ = nr; } else { core[series].sizeY = ys; core[series].sizeZ = ni; } } else if (sizes.length == 3) { core[series].sizeY = ni * ys; core[series].sizeZ = nr * zs; } core[series].sizeX = td; core[series].sizeZ /= ns; core[series].sizeT = ns * nr; core[series].sizeC = 1; core[series].imageCount = getSizeZ() * getSizeC() * getSizeT(); core[series].dimensionOrder = "XYCTZ"; core[series].rgb = false; core[series].interleaved = false; core[series].pixelType = FormatTools.pixelTypeFromBytes(bits / 8, signed, isFloat); } MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); for (int series=0; series<getSeriesCount(); series++) { store.setImageName(imageNames[series] + " #" + (series + 1), series); String date = DateTools.formatDate(timestamps[series], DATE_FORMAT); if (date != null) { store.setImageAcquisitionDate(new Timestamp(date), series); } String expID = MetadataTools.createLSID("Experimenter", series); store.setExperimenterID(expID, series); store.setExperimenterLastName(users[series], series); store.setExperimenterInstitution(institutions[series], series); store.setImageExperimenterRef(expID, series); } } }
package com.sung.hee.user.dao; import com.sung.hee.ent.model.SHEnt; import com.sung.hee.help.EncryptUtil; import com.sung.hee.user.model.SHUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service public class SHUserServiceImpl implements SHUserService { @Autowired private SHUserDAO shUserDAO; @Transactional public void regi(SHUser user) throws Exception { shUserDAO.regi(user); } @Override public boolean pwdFindCerti(String id, String en) { boolean result = false; if (EncryptUtil.getMD5(id).equals(en)) { SHUser shUser = new SHUser(); shUser.setId(id); shUser.setPwd("0000"); pwdUpdate(shUser); result = true; } else { } return result; } @Transactional(readOnly = true) public SHUser login(SHUser user) { String shaPwd = EncryptUtil.getSHA256(user.getPwd()); user.setPwd(shaPwd); return shUserDAO.login(user); } @Transactional(readOnly = true) public String getPWD(SHUser user) { return shUserDAO.getPWD(user); } @Transactional(readOnly = true) public int getID(SHUser user) { return shUserDAO.getID(user); } @Transactional public boolean emailCerti(String id, String en) { boolean result = false; if (EncryptUtil.getMD5(id).equals(en)) { SHUser user = new SHUser(); user.setId(id); shUserDAO.emailCerti(user); result = true; } else { } return result; } @Override public List<SHUser> userlist() { return shUserDAO.userlist(); } @Transactional(readOnly = true) public List<SHUser> getEntUserlist(SHEnt ent) { return shUserDAO.getEntUserlist(ent); } @Transactional public void inPoint(SHUser user) throws Exception { shUserDAO.inPoint(user); } @Transactional public void dePoint(SHUser user) throws Exception { shUserDAO.dePoint(user); } @Transactional public void pwdUpdate(SHUser shUser) { shUserDAO.pwdUpdate(shUser); } @Transactional(readOnly = true) public SHUser getIsSnS(SHUser shUser) { return shUserDAO.getIsSnS(shUser); } }
package com.tterrag.k9.mappings.mcp; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.regex.Matcher; import java.util.stream.Collectors; import java.util.zip.ZipFile; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ArrayUtils; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.tterrag.k9.mappings.AbstractMappingDatabase; import com.tterrag.k9.mappings.FastIntLookupDatabase; import com.tterrag.k9.mappings.Mapping; import com.tterrag.k9.mappings.MappingDatabase; import com.tterrag.k9.mappings.MappingType; import com.tterrag.k9.mappings.NameType; import com.tterrag.k9.mappings.NoSuchVersionException; import com.tterrag.k9.mappings.mcp.McpMapping.Side; import com.tterrag.k9.util.NonNull; import com.tterrag.k9.util.NullHelper; import com.tterrag.k9.util.Nullable; import com.tterrag.k9.util.Patterns; import clojure.asm.Type; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Value; import lombok.experimental.Delegate; public class McpDatabase extends FastIntLookupDatabase<McpMapping> { @RequiredArgsConstructor private static class ParamMapping implements McpMapping { interface Excludes { MappingType getType(); String getOwner(); String getMemberClass(); } private final Mapping method; @Delegate(excludes = Excludes.class) private final Mapping parent; private final int paramID; private final Type type; @Getter(onMethod = @__(@Override)) private final String comment; @Getter(onMethod = @__(@Override)) private final Side side; public ParamMapping(IntermediateMapping method, Mapping parent, int paramID, String comment, Side side) { this(method, parent, paramID, findType(method, paramID), comment, side); } public static Type findType(IntermediateMapping method, int param) { if (!method.isStatic()) { if (param == 0) { throw new IllegalArgumentException("Cannot use param 0 for non-static method: " + method + " param: " + param); } param--; // "this" counts as param 0 } String desc = method.getDesc(); List<Type> args = Lists.newArrayList(Type.getArgumentTypes(desc)); // double and long count twice....because java for (int i = 0; i < args.size(); i++) { Type type = args.get(i); if (type.getSort() == Type.DOUBLE || type.getSort() == Type.LONG) { args.add(i++, type); // duplicate this parameter for easy lookup } } if (param >= args.size()) { throw new IllegalArgumentException("Could not find type name. Method: " + method + " param: " + param); } return args.get(param); } @Override public MappingType getType() { return MappingType.PARAM; } @Override public @Nullable String getOwner() { String name = method.getName(); return method.getOwner() + "." + (name == null ? method.getIntermediate() : name); } @Override public @Nullable String getMemberClass() { return type.getClassName(); } @Override public Mapping getParent() { return method; } } @Value private static class CsvMapping implements McpMapping { @Getter(onMethod = @__(@Override)) MappingType type; @Getter(onMethod = @__(@Override)) String original = "\u2603"; @Getter(onMethod = @__(@Override)) String intermediate, name; @Getter(onMethod = @__(@Override)) String comment; @Getter(onMethod = @__(@Override)) Side side; } public McpDatabase(String mcver) throws NoSuchVersionException { super(mcver); } private final SrgDatabase srgs = new SrgDatabase(getMinecraftVersion()); @Override protected List<McpMapping> parseMappings() throws NoSuchVersionException, IOException { srgs.reload(); File folder = McpDownloader.INSTANCE.getDataFolder().resolve(Paths.get(getMinecraftVersion(), "mappings")).toFile(); if (!folder.exists()) { throw new NoSuchVersionException(getMinecraftVersion()); } File zip = folder.listFiles()[0]; ZipFile zipfile = new ZipFile(zip); try { MappingDatabase<CsvMapping> tempDb = new AbstractMappingDatabase<CsvMapping>(getMinecraftVersion()) { @Override protected List<CsvMapping> parseMappings() throws NoSuchVersionException, IOException { return NullHelper.notnullJ(Arrays.stream(MappingType.values()) .filter(type -> type.getCsvName() != null) .flatMap(type -> { List<String> lines; try { lines = IOUtils.readLines(zipfile.getInputStream(zipfile.getEntry(type.getCsvName() + ".csv")), Charsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } lines.remove(0); // Remove header line return lines.stream() .map(line -> { String[] info = line.split(",", -1); String comment = info.length > 3 ? Joiner.on(',').join(ArrayUtils.subarray(info, 3, info.length)) : ""; return new CsvMapping(type, info[0], info[1], comment, Side.values()[Integer.valueOf(info[2])]); }); }) .collect(Collectors.toList()), "Stream#collect"); } }; tempDb.reload(); // Add all srg mappings to this, if unmapped just use null/defaults for (MappingType type : MappingType.values()) { Collection<com.tterrag.k9.mappings.mcp.SrgMapping> byType = srgs.lookup(NameType.INTERMEDIATE, type); for (SrgMapping srg : byType) { McpMapping mapping; Optional<@NonNull CsvMapping> csv = tempDb.lookup(NameType.INTERMEDIATE, type, srg.getIntermediate()).stream().sorted(Comparator.comparingInt(m -> m.getIntermediate().length())).findFirst(); mapping = new McpMapping.Impl(type, srg.getOriginal(), srg.getIntermediate(), csv.map(CsvMapping::getName).orElse(null), srg.getDesc(), srg.getOwner(), srg.isStatic(), csv.map(CsvMapping::getComment).orElse(""), csv.map(CsvMapping::getSide).orElse(Side.BOTH)); addMapping(mapping); } } // Params are not part of srgs, so add them after the fact using the merged data as a source for (CsvMapping csv : tempDb.lookup(NameType.INTERMEDIATE, MappingType.PARAM)) { Matcher m = Patterns.SRG_PARAM.matcher(csv.getIntermediate()); if (m.matches()) { lookup(NameType.INTERMEDIATE, MappingType.METHOD, m.replaceAll("$1")).stream().findFirst().ifPresent(method -> { m.reset(); m.matches(); addMapping(new ParamMapping(method, csv, Integer.parseInt(m.group(2)), csv.getComment(), csv.getSide())); }); } else { addMapping(new McpMapping.Impl(MappingType.PARAM, "", csv.getIntermediate(), csv.getName(), null, null, csv.isStatic(), csv.getComment(), csv.getSide())); } } } finally { zipfile.close(); } return Collections.emptyList(); // We must add the mappings as we go so that params can find methods, so this return is not needed } private boolean matches(McpMapping m, String lookup) { String[] byUnderscores = m.getIntermediate().split("_"); if (byUnderscores.length > 1 && byUnderscores[1].equals(lookup)) { return true; } else { return m.getIntermediate().equals(lookup) || (m.getName() != null && m.getName().equals(lookup)); } } private boolean checkOwner(String ownerMatch, McpMapping mapping) { String owner = mapping.getOwner(); if (owner == null) { return false; } for (NameType type : NameType.values()) { String name = type.get(mapping); if (name != null) { String fullOwner = owner + "." + name; if (fullOwner.endsWith(ownerMatch)) { return true; } } } return false; } private int[] getParamIds(boolean isStatic, Type[] params) { int[] ret = new int[params.length]; int id = isStatic ? 0 : 1; for (int i = 0; i < params.length; i++) { ret[i] = id; Type arg = params[i]; if (arg.getSort() == Type.DOUBLE || arg.getSort() == Type.LONG) { id++; } id++; } return ret; } private McpMapping getSyntheticParam(McpMapping method, String id, int param) { return new ParamMapping(method, new CsvMapping(MappingType.PARAM, "p_" + id + "_" + param + "_", null, "", method.getSide()), param, "", method.getSide()); } @Override public Collection<McpMapping> lookup(NameType by, MappingType type, String name) { if (by != NameType.INTERMEDIATE || type != MappingType.PARAM) { return super.lookup(by, type, name); } Collection<McpMapping> matchingParams = super.lookup(by, type, name); final String ownerMatch; int lastDot = name.lastIndexOf('.'); if (lastDot != -1) { ownerMatch = name.substring(0, lastDot); name = name.substring(lastDot + 1); } else { ownerMatch = null; } // Special case for unmapped params Matcher matcher = Patterns.SRG_PARAM_FUZZY.matcher(name); if (matchingParams.isEmpty() && matcher.matches()) { matchingParams = new ArrayList<>(matchingParams); Collection<McpMapping> matchingMethods = super.lookup(NameType.INTERMEDIATE, MappingType.METHOD, matcher.group(1)).stream() .filter(m -> ownerMatch == null || checkOwner(ownerMatch, m)) .collect(Collectors.toList()); for (McpMapping method : matchingMethods) { String paramIdMatch = matcher.group(2); Integer paramId = paramIdMatch == null ? null : Integer.parseInt(paramIdMatch); String desc = method.getDesc(); Type[] params = Type.getArgumentTypes(desc); int[] ids = getParamIds(method.isStatic(), params); if (paramId == null) { for (int id : ids) { matchingParams.add(getSyntheticParam(method, matcher.group(1), id)); } } else if (ArrayUtils.contains(ids, paramId)) { matchingParams.add(getSyntheticParam(method, matcher.group(1), paramId)); } } } return matchingParams; } }
package de.tblsoft.solr.pipeline; import com.google.common.base.Strings; import de.tblsoft.solr.pipeline.bean.Document; import de.tblsoft.solr.pipeline.bean.Filter; import de.tblsoft.solr.util.DateUtils; import org.apache.commons.lang3.text.StrSubstitutor; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public abstract class AbstractFilter implements FilterIF { protected FilterIF nextFilter; protected Filter filter; private String baseDir; protected Map<String,String> variables = new HashMap<String, String>(); @Override public void setVariables(Map<String,String> variables) { if(variables == null) { return; } for(Map.Entry<String,String> entry: variables.entrySet()) { this.variables.put("variables." + entry.getKey(), entry.getValue()); } } @Override public void init() { nextFilter.init(); } @Override public void setFilterConfig(Filter filter) { this.filter = filter; } @Override public void document(Document document) { nextFilter.document(document); } @Override public void end() { nextFilter.end(); } @Override public void setNextFilter(FilterIF filter){ this.nextFilter=filter; } public String getProperty(String name, String defaultValue) { if(filter.getProperty() == null) { return defaultValue; } String value = (String) filter.getProperty().get(name); if(value != null) { StrSubstitutor strSubstitutor = new StrSubstitutor(variables); value = strSubstitutor.replace(value); return value; } return defaultValue; } public Boolean getPropertyAsBoolean(String name, Boolean defaultValue) { String value = getProperty(name,null); if(value == null) { return defaultValue; } return Boolean.valueOf(value); } public List<String> getPropertyAsList(String name, List<String> defaultValue) { if(filter.getProperty() == null) { return defaultValue; } List<String> value = (List<String>) filter.getProperty().get(name); if(value != null) { return value; } return defaultValue; } public int getPropertyAsInt(String name, int defaultValue) { String value = getProperty(name,null); if(value != null) { return Integer.valueOf(value).intValue(); } return defaultValue; } public float getPropertyAsFloat(String name, float defaultValue) { String value = getProperty(name,null); if(value != null) { return Float.valueOf(value); } return defaultValue; } public Date getPropertyAsDate(String name, Date defaultValue) { String value = getProperty(name,null); if(value != null) { return DateUtils.getDate(value); } return defaultValue; } public void verify(String value, String message) { if(Strings.isNullOrEmpty(value)) { throw new RuntimeException(message); } } public void verify(List<String> value, String message) { if(value == null) { throw new RuntimeException(message); } } public String[] getPropertyAsArray(String name, String[] defaultValue) { List<String> list = getPropertyAsList(name, null); if(list == null) { return defaultValue; } return list.toArray(new String[list.size()]); } public String getBaseDir() { return baseDir; } public void setBaseDir(String baseDir) { this.baseDir = baseDir; } public String getId() { return this.filter.getId(); } }
package gov.hhs.onc.dcdt.mail.decrypt; import gov.hhs.onc.dcdt.startup.ConfigInfo; import java.io.BufferedReader; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.log4j.Logger; /** * DecryptDirect handler. * Decrypts email message with openSSL command line tool using given certificate * files. Checks certificates for possible failure reasons. * @author joelamy * */ public class Decryptor implements DecryptDirectHandler { private final Logger log = Logger.getLogger("emailMessageLogger"); /** * Attempts to decrypt message with openSSL. On failure, cycles through * possible failure certificate options for explanation. Adds result to * bean class. * Implements DecryptDirectHandler execute method. * @param emailInfo * @return EmailBean * @throws Exception */ public EmailBean execute(EmailBean emailInfo) throws Exception { log.debug("before decrypt for message."); boolean result = false; LookupTestCertInfo goodCertInfo = emailInfo.getThisTest().getGoodCertInfo(); StringBuffer resultFromGoodCertString = new StringBuffer(""); if (goodCertInfo != null) { result = decryptEmail(emailInfo, goodCertInfo, resultFromGoodCertString); if (result) { emailInfo.setPasses(true); emailInfo.setResults(resultFromGoodCertString.toString()); return emailInfo; } } for (LookupTestCertInfo badPathInfo : emailInfo.getThisTest().getBadCertInfoList()) { StringBuffer resultString = new StringBuffer(""); result = decryptEmail(emailInfo, badPathInfo, resultString); if (result) { emailInfo.setPasses(false); emailInfo.setResults(resultString.toString()); return emailInfo; } } emailInfo.setPasses(false); emailInfo.setResults(resultFromGoodCertString.toString()); return emailInfo; } /** * Decpypts email using openSSL command line tool. * @param emailInfo * @param testPathInfo * @param resultString * @return boolean */ private boolean decryptEmail(EmailBean emailInfo, LookupTestCertInfo testPathInfo, StringBuffer resultString) { boolean result = false; final String CERT_PATH = ConfigInfo.getConfigProperty("CertLocation"); final String EMAIL_PATH = ConfigInfo.getConfigProperty("EmlLocation"); final String PUBLIC_CERT = testPathInfo.getCertFilename(); final String PRIVATE_CERT = testPathInfo.getPrivateKeyFilename(); System.out.println("Cert path: " + CERT_PATH); System.out.println("Public cert: " + PUBLIC_CERT); System.out.println("Private cert: " + PRIVATE_CERT); log.info("CERT PATH: " + CERT_PATH + "\n" + "PUBLIC CERT: " + PUBLIC_CERT + "\n" + "PRIVATE CERT: " + PRIVATE_CERT); String[] decryptCommand = new String[] { "openssl", "cms", "-decrypt", "-in", new File(EMAIL_PATH, emailInfo.getFileLocation()).toString(), "-recip", new File(CERT_PATH, PUBLIC_CERT).toString(), "-inkey", new File(CERT_PATH, PRIVATE_CERT).toString() }; log.info("Decrypt Command Line Statement: " + decryptCommand); try { StringBuffer errorString = new StringBuffer(""); result = runCommand(decryptCommand, errorString); if (result) { resultString.append(testPathInfo.getResultStringIfThisDecrypts()); } else { resultString.append(errorString.toString()); } } catch (Exception e) { // TODO We will probably want to better format this result string resultString.append(e.toString()); log.error("SSL Command Exception: " + e.getMessage() + " ,Caused By " + e.getCause() + "\n" + e.getStackTrace()); } log.info("Decrypt Command Result: " + resultString.toString()); return result; } /** * Runs the openSSL on command line using StreamGobbler to process and * flush the err and input streams. Returns boolean on success / * failure of the command. Logs error. * @param command * @param errorString * @return * @throws Exception */ private boolean runCommand(String[] command, StringBuffer errorString) throws Exception { Runtime rt = Runtime.getRuntime(); Process commandProcess = rt.exec(command); StreamGobbler errorGobbler = new StreamGobbler(commandProcess.getErrorStream(), "ERROR", false); StreamGobbler outputGobbler = new StreamGobbler(commandProcess.getInputStream(), "OUTPUT", false); errorGobbler.start(); outputGobbler.start(); int result = commandProcess.waitFor(); errorGobbler.join(); outputGobbler.join(); if (result == 0) { return true; } else { errorString.append("The command: "); for (int i = 0; i < command.length; i++) { errorString.append(" " + command[i]); } errorString.append("\nfailed with result code: " + result); errorString.append("\nError details: " + errorGobbler.getBufferedOutput().toString()); log.error(errorString); return false; } } /** * Handles input and error stream for calling command line executable. * */ class StreamGobbler extends Thread { private InputStream is; private String type; private boolean print; private StringBuffer buffer = new StringBuffer(""); public StreamGobbler(InputStream is, String type, boolean print) { this.is = is; this.type = type; this.print = print; } @Override public void run() { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); try { String line = null; while ((line = br.readLine()) != null) { buffer.append(type + ">" + line + "\n"); if (print) { System.out.println(type + ">" + line); } } }catch (IOException ioe) { log.error("Error with openSSL stream gobbler <IO Exception> /n" + ioe.getStackTrace()); }finally { closeStream(br); closeStream(isr); closeStream(this.is); } } public StringBuffer getBufferedOutput() { return buffer; } private void closeStream(Closeable stream){ try{ stream.close(); }catch(IOException ex){ log.error(ex.getMessage()); } } } }
package guru.haun.hackery.items; import guru.haun.hackery.HackeryMod; import java.util.Set; import com.google.common.collect.Sets; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; public class GlitchHarvester extends ItemTool { private static float speed = 200; private static Set mineable = Sets.newHashSet(new Block []{ (Block)HackeryMod.blockGlitch}); public GlitchHarvester(float speedOnProper, ToolMaterial creationMaterial, Set properBlocks) { super(speedOnProper, creationMaterial, properBlocks); setMaxDamage(3); setNoRepair(); setMaxStackSize(1); setUnlocalizedName("glitchHarvester"); setHarvestLevel("GlitchHarvester", 0); } public Set<String> getToolClasses(ItemStack stack){ return Sets.newHashSet(new String[] {"GlitchHarvester"}); } public GlitchHarvester(){ this(speed,ToolMaterial.EMERALD,mineable); } }
package hudson.remoting; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.io.ObjectOutputStream; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * Sits behind a proxy object and implements the proxy logic. * * @author Kohsuke Kawaguchi */ final class RemoteInvocationHandler implements InvocationHandler, Serializable { /** * This proxy acts as a proxy to the object of * Object ID on the remote {@link Channel}. */ private final int oid; /** * Represents the connection to the remote {@link Channel}. * * <p> * This field is null when a {@link RemoteInvocationHandler} is just * created and not working as a remote proxy. Once tranferred to the * remote system, this field is set to non-null. */ private transient Channel channel; /** * True if we are proxying an user object. */ private final boolean userProxy; /** * If true, this proxy is automatically unexported by the calling {@link Channel}, * so this object won't release the object at {@link #finalize()}. * <p> * This ugly distinction enables us to keep the # of exported objects low for * the typical situation where the calls are synchronous (thus end of the call * signifies full unexport of all involved objects.) */ private final boolean autoUnexportByCaller; /** * If true, indicates that this proxy object is being sent back * to where it came from. If false, indicates that this proxy * is being sent to the remote peer. * * Only used in the serialized form of this class. */ private boolean goingHome; /** * Creates a proxy that wraps an existing OID on the remote. */ RemoteInvocationHandler(Channel channel, int id, boolean userProxy, boolean autoUnexportByCaller) { this.channel = channel; this.oid = id; this.userProxy = userProxy; this.autoUnexportByCaller = autoUnexportByCaller; } /** * Wraps an OID to the typed wrapper. */ public static <T> T wrap(Channel channel, int id, Class<T> type, boolean userProxy, boolean autoUnexportByCaller) { ClassLoader cl = type.getClassLoader(); // if the type is a JDK-defined type, classloader should be for IReadResolve if(cl==null || cl==ClassLoader.getSystemClassLoader()) cl = IReadResolve.class.getClassLoader(); return type.cast(Proxy.newProxyInstance(cl, new Class[]{type,IReadResolve.class}, new RemoteInvocationHandler(channel,id,userProxy,autoUnexportByCaller))); } /** * If the given object is a proxy to a remote object in the specified channel, * return its object ID. Otherwise return -1. * <p> * This method can be used to get back the original reference when * a proxy is sent back to the channel it came from. */ public static int unwrap(Object proxy, Channel src) { InvocationHandler h = Proxy.getInvocationHandler(proxy); if (h instanceof RemoteInvocationHandler) { RemoteInvocationHandler rih = (RemoteInvocationHandler) h; if(rih.channel==src) return rih.oid; } return -1; } /** * If the given object is a proxy object, return the {@link Channel} * object that it's associated with. Otherwise null. */ public static Channel unwrap(Object proxy) { InvocationHandler h = Proxy.getInvocationHandler(proxy); if (h instanceof RemoteInvocationHandler) { RemoteInvocationHandler rih = (RemoteInvocationHandler) h; return rih.channel; } return null; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(method.getDeclaringClass()==IReadResolve.class) { // readResolve on the proxy. // if we are going back to where we came from, replace the proxy by the real object if(goingHome) return channel.getExportedObject(oid); else return proxy; } if(channel==null) throw new IllegalStateException("proxy is not connected to a channel"); if(args==null) args = EMPTY_ARRAY; Class<?> dc = method.getDeclaringClass(); if(dc ==Object.class) { // handle equals and hashCode by ourselves try { return method.invoke(this,args); } catch (InvocationTargetException e) { throw e.getTargetException(); } } // delegate the rest of the methods to the remote object boolean async = method.isAnnotationPresent(Asynchronous.class); RPCRequest req = new RPCRequest(oid, method, args, userProxy ? dc.getClassLoader() : null); try { if(userProxy) { if (async) channel.callAsync(req); else return channel.call(req); } else { if (async) req.callAsync(channel); else return req.call(channel); } return null; } catch (Throwable e) { for (Class exc : method.getExceptionTypes()) { if (exc.isInstance(e)) throw e; // signature explicitly lists this exception } if (e instanceof RuntimeException || e instanceof Error) throw e; // these can be thrown from any methods // if the thrown exception type isn't compatible with the method signature // wrap it to RuntimeException to avoid UndeclaredThrowableException throw new RemotingSystemException(e); } } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { channel = Channel.current(); ois.defaultReadObject(); } private void writeObject(ObjectOutputStream oos) throws IOException { goingHome = channel!=null; oos.defaultWriteObject(); } /** * Two proxies are the same iff they represent the same remote object. */ public boolean equals(Object o) { if(Proxy.isProxyClass(o.getClass())) o = Proxy.getInvocationHandler(o); if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RemoteInvocationHandler that = (RemoteInvocationHandler) o; return this.oid==that.oid && this.channel==that.channel; } public int hashCode() { return oid; } protected void finalize() throws Throwable { // unexport the remote object if(channel!=null && !autoUnexportByCaller) channel.send(new UnexportCommand(oid)); super.finalize(); } private static final long serialVersionUID = 1L; /** * Executes the method call remotely. * * If used as {@link Request}, this can be used to provide a lower-layer * for the use inside remoting, to implement the classloader delegation, and etc. * The downside of this is that the classes used as a parameter/return value * must be available to both JVMs. * * If used as {@link Callable} in conjunction with {@link UserRequest}, * this can be used to send a method call to user-level objects, and * classes for the parameters and the return value are sent remotely if needed. */ static final class RPCRequest extends Request<Serializable,Throwable> implements DelegatingCallable<Serializable,Throwable> { /** * Target object id to invoke. */ private final int oid; private final String methodName; /** * Type name of the arguments to invoke. They are names because * neither {@link Method} nor {@link Class} is serializable. */ private final String[] types; /** * Arguments to invoke the method with. */ private final Object[] arguments; /** * If this is used as {@link Callable}, we need to remember what classloader * to be used to serialize the request and the response. */ private transient ClassLoader classLoader; public RPCRequest(int oid, Method m, Object[] arguments) { this(oid,m,arguments,null); } public RPCRequest(int oid, Method m, Object[] arguments, ClassLoader cl) { this.oid = oid; this.arguments = arguments; this.methodName = m.getName(); this.classLoader = cl; this.types = new String[arguments.length]; Class<?>[] params = m.getParameterTypes(); for( int i=0; i<arguments.length; i++ ) types[i] = params[i].getName(); assert types.length == arguments.length; } public Serializable call() throws Throwable { return perform(Channel.current()); } public ClassLoader getClassLoader() { if(classLoader!=null) return classLoader; else return getClass().getClassLoader(); } protected Serializable perform(Channel channel) throws Throwable { Object o = channel.getExportedObject(oid); if(o==null) throw new IllegalStateException("Unable to call "+methodName+". Invalid object ID "+oid); try { Method m = choose(o); if(m==null) throw new IllegalStateException("Unable to call "+methodName+". No matching method found on "+o.getClass()); m.setAccessible(true); // in case the class is not public Object r = m.invoke(o, arguments); if (r==null || r instanceof Serializable) return (Serializable) r; else throw new RemotingSystemException(new ClassCastException(r.getClass()+" is returned from "+m+" on "+o.getClass()+" but it's not serializable")); } catch (InvocationTargetException e) { throw e.getTargetException(); } } /** * Chooses the method to invoke. */ private Method choose(Object o) { OUTER: for(Method m : o.getClass().getMethods()) { if(!m.getName().equals(methodName)) continue; Class<?>[] paramTypes = m.getParameterTypes(); if(paramTypes.length!=arguments.length) continue; for( int i=0; i<types.length; i++ ) { if(!types[i].equals(paramTypes[i].getName())) continue OUTER; } return m; } return null; } Object[] getArguments() { // for debugging return arguments; } public String toString() { return "RPCRequest("+oid+","+methodName+")"; } private static final long serialVersionUID = 1L; } private static final Object[] EMPTY_ARRAY = new Object[0]; }
package info.faceland.strife.util; import info.faceland.strife.StrifePlugin; import info.faceland.strife.data.StrifeMob; import info.faceland.strife.util.DamageUtil.OriginLocation; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import org.bukkit.Bukkit; import org.bukkit.FluidCollisionMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Mob; import org.bukkit.entity.Player; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.util.RayTraceResult; import org.bukkit.util.Vector; public class TargetingUtil { public static void filterFriendlyEntities(Set<LivingEntity> targets, StrifeMob caster, boolean friendly) { Set<LivingEntity> friendlyEntities = getFriendlyEntities(caster, targets); if (friendly) { targets.clear(); targets.addAll(friendlyEntities); } else { targets.removeAll(friendlyEntities); } } public static Set<LivingEntity> getFriendlyEntities(StrifeMob caster, Set<LivingEntity> targets) { return targets.stream().filter(target -> isFriendly(caster, target)).collect(Collectors.toSet()); } public static boolean isFriendly(StrifeMob caster, LivingEntity target) { if (caster.getEntity() == target) { return true; } if (caster.getEntity() instanceof Player && target instanceof Player) { return !DamageUtil.canAttack((Player) caster.getEntity(), (Player) target); } for (StrifeMob mob : caster.getMinions()) { if (target == mob.getEntity()) { return true; } } // for (StrifeMob mob : getPartyMembers { return false; } public static Set<LivingEntity> getEntitiesInArea(LivingEntity caster, double radius) { Collection<Entity> targetList = caster.getWorld() .getNearbyEntities(caster.getLocation(), radius, radius, radius); Set<LivingEntity> validTargets = new HashSet<>(); for (Entity e : targetList) { if (!e.isValid() || e instanceof ArmorStand || !(e instanceof LivingEntity)) { continue; } if (caster.hasLineOfSight(e)) { validTargets.add((LivingEntity) e); } } return validTargets; } public static boolean isDetectionStand(LivingEntity le) { return le instanceof ArmorStand && le.hasMetadata("STANDO"); } public static ArmorStand buildAndRemoveDetectionStand(Location location) { ArmorStand stando = location.getWorld().spawn(location, ArmorStand.class, e -> e.setVisible(false)); stando.setSmall(true); stando.setMetadata("STANDO", new FixedMetadataValue(StrifePlugin.getInstance(), "")); Bukkit.getScheduler().runTaskLater(StrifePlugin.getInstance(), stando::remove, 1L); return stando; } public static Set<LivingEntity> getTempStandTargetList(Location loc, float groundCheckRange) { Set<LivingEntity> targets = new HashSet<>(); if (groundCheckRange < 1) { targets.add(TargetingUtil.buildAndRemoveDetectionStand(loc)); return targets; } else { for (int i = 0; i < groundCheckRange; i++) { if (loc.getBlock().getType().isSolid()) { loc.setY(loc.getBlockY() + 1.1); targets.add(TargetingUtil.buildAndRemoveDetectionStand(loc)); return targets; } loc.add(0, -1, 0); } return targets; } } public static Set<LivingEntity> getEntitiesInLine(LivingEntity caster, double range) { Set<LivingEntity> targets = new HashSet<>(); Location eyeLoc = caster.getEyeLocation(); Vector direction = caster.getEyeLocation().getDirection(); ArrayList<Entity> entities = (ArrayList<Entity>) caster.getNearbyEntities(range, range, range); for (double incRange = 0; incRange <= range; incRange += 1) { Location loc = eyeLoc.clone().add(direction.clone().multiply(incRange)); if (loc.getBlock().getType() != Material.AIR) { if (!loc.getBlock().getType().isTransparent()) { break; } } for (Entity entity : entities) { if (entityWithinBounds(entity, loc)) { targets.add((LivingEntity) entity); } } } return targets; } public static LivingEntity getFirstEntityInLine(LivingEntity caster, double range) { RayTraceResult result = caster.getWorld() .rayTraceEntities(caster.getEyeLocation(), caster.getEyeLocation().getDirection(), range, entity -> entity instanceof LivingEntity && entity != caster); if (result == null || result.getHitEntity() == null) { return null; } return (LivingEntity) result.getHitEntity(); } private static boolean entityWithinBounds(Entity entity, Location loc) { if (!(entity instanceof LivingEntity) || !entity.isValid()) { return false; } double ex = entity.getLocation().getX(); double ey = entity.getLocation().getY() + ((LivingEntity) entity).getEyeHeight() / 2; double ez = entity.getLocation().getZ(); return Math.abs(loc.getX() - ex) < 0.85 && Math.abs(loc.getZ() - ez) < 0.85 && Math.abs(loc.getY() - ey) < 3; } public static LivingEntity selectFirstEntityInSight(LivingEntity caster, double range) { LivingEntity mobTarget = TargetingUtil.getMobTarget(caster); return mobTarget != null ? mobTarget : getFirstEntityInLine(caster, range); } public static Location getTargetLocation(LivingEntity caster, LivingEntity target, double range, boolean targetEntities) { return getTargetLocation(caster, target, range, OriginLocation.CENTER, targetEntities); } public static Location getTargetLocation(LivingEntity caster, LivingEntity target, double range, OriginLocation originLocation, boolean targetEntities) { if (target != null) { return getOriginLocation(target, originLocation); } RayTraceResult result; if (targetEntities) { result = caster.getWorld() .rayTrace(caster.getEyeLocation(), caster.getEyeLocation().getDirection(), range, FluidCollisionMode.NEVER, true, 0.2, entity -> entity instanceof LivingEntity && entity != caster); } else { result = caster.getWorld() .rayTraceBlocks(caster.getEyeLocation(), caster.getEyeLocation().getDirection(), range, FluidCollisionMode.NEVER, true); } if (result == null) { LogUtil.printDebug(" - Using MAX RANGE location calculation"); return caster.getEyeLocation().add( caster.getEyeLocation().getDirection().multiply(Math.max(0, range - 1))); } if (result.getHitEntity() != null) { LogUtil.printDebug(" - Using ENTITY location calculation"); return getOriginLocation((LivingEntity) result.getHitEntity(), originLocation); } if (result.getHitBlock() != null) { LogUtil.printDebug(" - Using BLOCK location calculation"); return result.getHitBlock().getLocation().add(0.5, 0.8, 0.5) .add(result.getHitBlockFace().getDirection()); } LogUtil.printDebug(" - Using HIT RANGE location calculation"); return new Location(caster.getWorld(), result.getHitPosition().getX(), result.getHitPosition().getBlockY(), result.getHitPosition().getZ()); } public static LivingEntity getMobTarget(StrifeMob strifeMob) { return getMobTarget(strifeMob.getEntity()); } public static LivingEntity getMobTarget(LivingEntity livingEntity) { if (!(livingEntity instanceof Mob)) { return null; } if (((Mob) livingEntity).getTarget() == null || !((Mob) livingEntity).getTarget().isValid()) { return null; } return ((Mob) livingEntity).getTarget(); } public static Location getOriginLocation(LivingEntity le, OriginLocation origin) { switch (origin) { case HEAD: return le.getEyeLocation(); case BELOW_HEAD: return le.getEyeLocation().clone().add(0, -0.35, 0); case CENTER: Location location = le.getEyeLocation().clone(); location.setY(location.getY() - le.getEyeHeight() / 2); return location; case GROUND: default: return le.getLocation(); } } }
package io.mycat.server.packet.util; import io.mycat.MycatServer; import io.mycat.backend.PhysicalDBPool; import io.mycat.backend.PhysicalDatasource; import io.mycat.server.config.node.DBHostConfig; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.SystemUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSON; import com.google.common.util.concurrent.ListenableFuture; /** * fix collationIndex charset * utf8mb4 collationIndex 45, 46 4546 * mysqld(my.cnf)collation_server=utf8mb4_bin * 45'java.lang.RuntimeException: Unknown charsetIndex:46' * collation_server=utf8mb4_bincollation_server * 4645,46 * MycatServer.startup() config.initDatasource(); * CharsetUtil.initCharsetAndCollation(config.getDataHosts()); * mysqldinformation_schema.collations collationIndex charset * mysqld(mysqldcollationIndex charset ) * @author mycat */ public class CharsetUtil { public static final Logger logger = LoggerFactory.getLogger(CharsetUtil.class); /** collationIndex charsetName */ private static final Map<Integer,String> INDEX_TO_CHARSET = new HashMap<>(); /** charsetName collationIndex */ private static final Map<String, Integer> CHARSET_TO_INDEX = new HashMap<>(); /** collationName CharsetCollation */ private static final Map<String, CharsetCollation> COLLATION_TO_CHARSETCOLLATION = new HashMap<>(); /** * charset collation( mycat.xml dataHosts mysqld charset collation ) * ConcurrentHashMap * @param charsetConfigMap mycat.xml charset-config collationIndex --> charsetName */ public static void asynLoad(Map<String, PhysicalDBPool> dataHosts, Map<String, Object> charsetConfigMap){ MycatServer.getInstance().getListeningExecutorService().execute(new Runnable() { public void run() { CharsetUtil.load(dataHosts, charsetConfigMap); } }); } /** * charset collation( mycat.xml dataHosts mysqld charset collation ) * @param charsetConfigMap mycat.xml charset-config collationIndex charsetName */ public static void load(Map<String, PhysicalDBPool> dataHosts, Map<String, Object> charsetConfigMap){ try { if(dataHosts != null && dataHosts.size() > 0) CharsetUtil.initCharsetAndCollation(dataHosts); // mysqld charset collation else logger.debug("param dataHosts is null"); // collationIndex --> charsetName for (String index : charsetConfigMap.keySet()){ int collationIndex = Integer.parseInt(index); String charsetName = INDEX_TO_CHARSET.get(collationIndex); if(StringUtils.isNotBlank(charsetName)){ INDEX_TO_CHARSET.put(collationIndex, charsetName); CHARSET_TO_INDEX.put(charsetName, collationIndex); } logger.debug("load charset and collation from mycat.xml."); } } catch (Exception e) { logger.error(e.getMessage()); } } private static void initCharsetAndCollation(Map<String, PhysicalDBPool> dataHosts){ if(COLLATION_TO_CHARSETCOLLATION.size() > 0){ logger.debug(" charset and collation has already init ..."); return; } // mycat.xml heartbeat()CharsetCollation // mycat.xml dataHostCharsetCollation; DBHostConfig dBHostconfig = getConfigByDataHostName(dataHosts, "jdbchost"); if(dBHostconfig != null){ if(getCharsetCollationFromMysql(dBHostconfig)){ logger.debug(" init charset and collation success..."); return; } } // mycat.xml dataHost mysqld charset collation for(String key : dataHosts.keySet()){ PhysicalDBPool pool = dataHosts.get(key); if(pool != null && pool.getSource() != null){ PhysicalDatasource ds = pool.getSource(); if(ds != null && ds.getConfig() != null && "mysql".equalsIgnoreCase(ds.getConfig().getDbType())){ DBHostConfig config = ds.getConfig(); while(!getCharsetCollationFromMysql(config)){ getCharsetCollationFromMysql(config); } logger.debug(" init charset and collation success..."); return; // for } } } logger.error(" init charset and collation from mysqld failed, please check datahost in mycat.xml."+ SystemUtils.LINE_SEPARATOR + " if your backend database is not mysqld, please ignore this message."); } public static DBHostConfig getConfigByDataHostName(Map<String, PhysicalDBPool> dataHosts, String hostName){ PhysicalDBPool pool = dataHosts.get(hostName); if(pool != null && pool.getSource() != null){ PhysicalDatasource ds = pool.getSource(); return ds.getConfig(); } return null; } public static final String getCharset(int index) { return INDEX_TO_CHARSET.get(index); } /** * charset collationIndex, collationIndex * indexindex, getIndexByCollationName * getIndexByCharsetNameAndCollationName * @param charset * @return */ public static final int getIndex(String charset) { if (StringUtils.isBlank(charset)) { return 0; } else { Integer i = CHARSET_TO_INDEX.get(charset.toLowerCase()); if(i == null && "Cp1252".equalsIgnoreCase(charset) ) charset = "latin1"; i = CHARSET_TO_INDEX.get(charset.toLowerCase()); return (i == null) ? 0 : i; } } /** * collationName charset collationIndex * @param charset * @param collationName * @return */ public static final int getIndexByCharsetNameAndCollationName(String charset, String collationName) { if (StringUtils.isBlank(collationName)) { return 0; } else { CharsetCollation cc = COLLATION_TO_CHARSETCOLLATION.get(collationName.toLowerCase()); if(cc != null && charset != null && charset.equalsIgnoreCase(cc.getCharsetName())) return cc.getCollationIndex(); else return 0; } } /** * collationName collationIndex, * @param collationName * @return */ public static final int getIndexByCollationName(String collationName) { if (StringUtils.isBlank(collationName)) { return 0; } else { CharsetCollation cc = COLLATION_TO_CHARSETCOLLATION.get(collationName.toLowerCase()); if(cc != null) return cc.getCollationIndex(); else return 0; } } private static boolean getCharsetCollationFromMysql(DBHostConfig config){ String sql = "SELECT ID,CHARACTER_SET_NAME,COLLATION_NAME,IS_DEFAULT FROM INFORMATION_SCHEMA.COLLATIONS"; try(Connection conn = getConnection(config)){ if(conn == null) return false; try(Statement statement = conn.createStatement()){ ResultSet rs = statement.executeQuery(sql); while(rs != null && rs.next()){ int collationIndex = new Long(rs.getLong(1)).intValue(); String charsetName = rs.getString(2); String collationName = rs.getString(3); boolean isDefaultCollation = (rs.getString(4) != null && "Yes".equalsIgnoreCase(rs.getString(4))) ? true : false; INDEX_TO_CHARSET.put(collationIndex, charsetName); if(isDefaultCollation){ // charsetName collationIndexcollationIndex CHARSET_TO_INDEX.put(charsetName, collationIndex); } CharsetCollation cc = new CharsetCollation(charsetName, collationIndex, collationName, isDefaultCollation); COLLATION_TO_CHARSETCOLLATION.put(collationName, cc); } if(COLLATION_TO_CHARSETCOLLATION.size() > 0) return true; return false; } catch (SQLException e) { logger.warn(e.getMessage()); } } catch (SQLException e) { logger.warn(e.getMessage()); } return false; } /** * DBHostConfig cfg (java.sql.Connection) * mysqldmycat-server * mysqlmysqlmysqldhandshake * "serverCharsetIndex":46connection serverCharsetIndex * handshake * {"packetId":0,"packetLength":78,"protocolVersion":10,"restOfScrambleBuff":"OihYY2tvakVadV5Y", * "seed":"YiJ+eWVsb2c=","serverCapabilities":63487, * "serverCharsetIndex":46,"serverStatus":2,"serverVersion":"NS42LjI3LWxvZw==","threadId":65} * mysqlmysqldJDBCurlJDBC * @param cfg * @return * @throws SQLException */ public static Connection getConnection(DBHostConfig cfg){ long millisecondsBegin = System.currentTimeMillis(); if(cfg == null) return null; String url = new StringBuffer("jdbc:mysql://").append(cfg.getUrl()) .append("/mysql").append("?characterEncoding=UTF-8").toString(); Connection connection = null; long millisecondsEnd2 = System.currentTimeMillis(); try { Class.forName("com.mysql.jdbc.Driver"); logger.debug(" function Class.forName cost milliseconds: " + (millisecondsEnd2 - millisecondsBegin)); connection = DriverManager.getConnection(url, cfg.getUser(), cfg.getPassword()); } catch (ClassNotFoundException | SQLException e) { if(e instanceof ClassNotFoundException) logger.error(e.getMessage()); else logger.warn(e.getMessage() + " " + JSON.toJSONString(cfg)); } long millisecondsEnd = System.currentTimeMillis(); logger.debug(" function getConnection cost milliseconds: " + (millisecondsEnd - millisecondsEnd2)); return connection; } } /** * mysqld collationcollationindex collation * ()collation collation collationindex, * collationName collationIndex collationIndexcollationIndex * collationIndex index( collationindex) * collationIndex * mysqld collation index * @author Administrator * */ class CharsetCollation { // mysqldjavaunicode // jarcom.mysql.jdbc.CharsetMapping private String charsetName; private int collationIndex; // collation private String collationName; // collation private boolean isDefaultCollation = false; // collationcollation public CharsetCollation(String charsetName, int collationIndex, String collationName, boolean isDefaultCollation){ this.charsetName = charsetName; this.collationIndex = collationIndex; this.collationName = collationName; this.isDefaultCollation = isDefaultCollation; } public String getCharsetName() { return charsetName; } public void setCharsetName(String charsetName) { this.charsetName = charsetName; } public int getCollationIndex() { return collationIndex; } public void setCollationIndex(int collationIndex) { this.collationIndex = collationIndex; } public String getCollationName() { return collationName; } public void setCollationName(String collationName) { this.collationName = collationName; } public boolean isDefaultCollation() { return isDefaultCollation; } public void setDefaultCollation(boolean isDefaultCollation) { this.isDefaultCollation = isDefaultCollation; } }
package io.vertx.ext.consul; import io.vertx.codegen.annotations.DataObject; import io.vertx.codegen.annotations.GenIgnore; import io.vertx.core.VertxException; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.Http2Settings; import io.vertx.core.http.HttpClientOptions; import io.vertx.core.http.HttpVersion; import io.vertx.core.json.JsonObject; import io.vertx.core.net.*; import io.vertx.ext.web.client.WebClientOptions; import java.net.URI; import java.net.URLDecoder; import java.util.*; /** * Options used to create Consul client. * * @author <a href="mailto:ruslan.sennov@gmail.com">Ruslan Sennov</a> */ @DataObject(generateConverter = true) public class ConsulClientOptions extends WebClientOptions { private static final String CONSUL_DEFAULT_HOST = "localhost"; private static final int CONSUL_DEFAULT_PORT = 8500; private String aclToken; private String dc; private long timeoutMs; /** * Default constructor */ public ConsulClientOptions() { super(); setDefaultHost(CONSUL_DEFAULT_HOST); setDefaultPort(CONSUL_DEFAULT_PORT); } /** * Copy constructor * * @param options the one to copy */ public ConsulClientOptions(ConsulClientOptions options) { super(options); setHost(options.getHost()); setPort(options.getPort()); setAclToken(options.getAclToken()); setDc(options.getDc()); setTimeout(options.getTimeout()); } /** * Constructor from JSON * * @param json the JSON */ public ConsulClientOptions(JsonObject json) { super(json); ConsulClientOptionsConverter.fromJson(json, this); if (json.getValue("host") instanceof String) { setHost((String)json.getValue("host")); } else { setHost(CONSUL_DEFAULT_HOST); } if (json.getValue("port") instanceof Number) { setPort(((Number)json.getValue("port")).intValue()); } else { setPort(CONSUL_DEFAULT_PORT); } } /** * Constructor from {@link URI}. * The datacenter and the acl token can be defined in the query; the scheme will be ignored. * * For example: * <p><code> * consul://consul.example.com/?dc=dc1&amp;acl=00000000-0000-0000-0000-000000000000 * </code></p> * @param uri the URI */ public ConsulClientOptions(URI uri) { setHost(uri.getHost()); setPort(uri.getPort() < 0 ? CONSUL_DEFAULT_PORT : uri.getPort()); Map<String, List<String>> params = params(uri); setDc(getParam(params, "dc")); setAclToken(getParam(params, "acl", "aclToken")); } private static String getParam(Map<String, List<String>> params, String... keyVariants) { for (String key : keyVariants) { if (params.containsKey(key)) { List<String> values = params.get(key); return values.get(0); } } return null; } private static Map<String, List<String>> params(URI uri) { if (uri.getQuery() == null || uri.getQuery().isEmpty()) { return Collections.emptyMap(); } final Map<String, List<String>> queryPairs = new LinkedHashMap<>(); final String[] pairs = uri.getQuery().split("&"); for (String pair : pairs) { try { final int idx = pair.indexOf("="); final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair; final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null; List<String> list = queryPairs.computeIfAbsent(key, k -> new ArrayList<>()); list.add(value); } catch (Exception e) { throw new VertxException(e); } } return queryPairs; } /** * Convert to JSON * * @return the JSON */ public JsonObject toJson() { JsonObject json = super.toJson(); ConsulClientOptionsConverter.toJson(this, json); if (getHost() != null) { json.put("host", getHost()); } json.put("port", getPort()); return json; } /** * Get Consul host. * * @return consul host */ @GenIgnore public String getHost() { return getDefaultHost(); } /** * Get Consul HTTP API port. * * @return consul port */ @GenIgnore public int getPort() { return getDefaultPort(); } /** * Get the ACL token. * * @return the ACL token. */ public String getAclToken() { return aclToken; } /** * Get the datacenter name * * @return the datacenter name */ public String getDc() { return dc; } /** * Get timeout in milliseconds * * @return timeout in milliseconds */ public long getTimeout() { return timeoutMs; } /** * Set Consul host. Defaults to `localhost` * * @param host consul host * @return reference to this, for fluency */ @GenIgnore public ConsulClientOptions setHost(String host) { setDefaultHost(host); return this; } /** * Set Consul HTTP API port. Defaults to `8500` * * @param port Consul HTTP API port * @return reference to this, for fluency */ @GenIgnore public ConsulClientOptions setPort(int port) { setDefaultPort(port); return this; } /** * Set the ACL token. When provided, the client will use this token when making requests to the Consul * by providing the "?token" query parameter. When not provided, the empty token, which maps to the 'anonymous' * ACL policy, is used. * * @param aclToken the ACL token * @return reference to this, for fluency */ public ConsulClientOptions setAclToken(String aclToken) { this.aclToken = aclToken; return this; } /** * Set the datacenter name. When provided, the client will use it when making requests to the Consul * by providing the "?dc" query parameter. When not provided, the datacenter of the consul agent is queried. * * @param dc the datacenter name * @return reference to this, for fluency */ public ConsulClientOptions setDc(String dc) { this.dc = dc; return this; } /** * Sets the amount of time (in milliseconds) after which if the request does not return any data * within the timeout period an failure will be passed to the handler and the request will be closed. * * @param timeoutMs timeout in milliseconds * @return reference to this, for fluency */ public ConsulClientOptions setTimeout(long timeoutMs) { this.timeoutMs = timeoutMs; return this; } /** * Set the TCP send buffer size * * @param sendBufferSize the buffers size, in bytes * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setSendBufferSize(int sendBufferSize) { return (ConsulClientOptions) super.setSendBufferSize(sendBufferSize); } /** * Set the TCP receive buffer size * * @param receiveBufferSize the buffers size, in bytes * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setReceiveBufferSize(int receiveBufferSize) { return (ConsulClientOptions) super.setReceiveBufferSize(receiveBufferSize); } /** * Set the value of reuse address * @param reuseAddress the value of reuse address * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setReuseAddress(boolean reuseAddress) { return (ConsulClientOptions) super.setReuseAddress(reuseAddress); } /** * Set the value of reuse port. * <p/> * This is only supported by native transports. * * @param reusePort the value of reuse port * @return a reference to this, so the API can be used fluently */ public ConsulClientOptions setReusePort(boolean reusePort) { return (ConsulClientOptions) super.setReusePort(reusePort); } /** * Set the value of traffic class * * @param trafficClass the value of traffic class * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setTrafficClass(int trafficClass) { return (ConsulClientOptions) super.setTrafficClass(trafficClass); } /** * Set whether TCP no delay is enabled * * @param tcpNoDelay true if TCP no delay is enabled (Nagle disabled) * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setTcpNoDelay(boolean tcpNoDelay) { return (ConsulClientOptions) super.setTcpNoDelay(tcpNoDelay); } /** * Set whether TCP keep alive is enabled * * @param tcpKeepAlive true if TCP keep alive is enabled * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setTcpKeepAlive(boolean tcpKeepAlive) { return (ConsulClientOptions) super.setTcpKeepAlive(tcpKeepAlive); } /** * Enable the {@code TCP_CORK} option - only with linux native transport. * * @param tcpCork the cork value * @return a reference to this, so the API can be used fluently */ public ConsulClientOptions setTcpCork(boolean tcpCork) { return (ConsulClientOptions) super.setTcpCork(tcpCork); } /** * Enable the {@code TCP_QUICKACK} option - only with linux native transport. * * @param tcpQuickAck the quick ack value * @return a reference to this, so the API can be used fluently */ public ConsulClientOptions setTcpQuickAck(boolean tcpQuickAck) { return (ConsulClientOptions) super.setTcpQuickAck(tcpQuickAck); } /** * Enable the {@code TCP_FASTOPEN} option - only with linux native transport. * * @param tcpFastOpen the fast open value * @return a reference to this, so the API can be used fluently */ public ConsulClientOptions setTcpFastOpen(boolean tcpFastOpen) { return (ConsulClientOptions) super.setTcpFastOpen(tcpFastOpen); } /** * Set whether SO_linger keep alive is enabled * * @param soLinger true if SO_linger is enabled * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setSoLinger(int soLinger) { return (ConsulClientOptions) super.setSoLinger(soLinger); } /** * Set whether Netty pooled buffers are enabled * * @param usePooledBuffers true if pooled buffers enabled * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setUsePooledBuffers(boolean usePooledBuffers) { return (ConsulClientOptions) super.setUsePooledBuffers(usePooledBuffers); } /** * Set the idle timeout, in seconds. zero means don't timeout. * This determines if a connection will timeout and be closed if no data is received within the timeout. * * @param idleTimeout the timeout, in seconds * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setIdleTimeout(int idleTimeout) { return (ConsulClientOptions) super.setIdleTimeout(idleTimeout); } /** * Set whether SSL/TLS is enabled * * @param ssl true if enabled * @return reference to this, for fluency */ public ConsulClientOptions setSsl(boolean ssl) { super.setSsl(ssl); return this; } /** * Set the key/cert options. * * @param options the key store options * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setKeyCertOptions(KeyCertOptions options) { return (ConsulClientOptions) super.setKeyCertOptions(options); } /** * Set the key/cert options in jks format, aka Java keystore. * @param options the key store in jks format * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setKeyStoreOptions(JksOptions options) { return (ConsulClientOptions) super.setKeyStoreOptions(options); } /** * Set the key/cert options in pfx format. * @param options the key cert options in pfx format * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setPfxKeyCertOptions(PfxOptions options) { return (ConsulClientOptions) super.setPfxKeyCertOptions(options); } /** * Set the trust options. * @param options the trust options * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setTrustOptions(TrustOptions options) { return (ConsulClientOptions) super.setTrustOptions(options); } /** * Set the key/cert store options in pem format. * @param options the options in pem format * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setPemKeyCertOptions(PemKeyCertOptions options) { return (ConsulClientOptions) super.setPemKeyCertOptions(options); } /** * Set the trust options in jks format, aka Java truststore * @param options the trust options in jks format * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setTrustStoreOptions(JksOptions options) { return (ConsulClientOptions) super.setTrustStoreOptions(options); } /** * Set the trust options in pfx format * @param options the trust options in pfx format * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setPfxTrustOptions(PfxOptions options) { return (ConsulClientOptions) super.setPfxTrustOptions(options); } /** * Set whether all server certificates should be trusted * * @param trustAll true if all should be trusted * @return reference to this, for fluency */ public ConsulClientOptions setTrustAll(boolean trustAll) { super.setTrustAll(trustAll); return this; } /** * Set the trust options. * * @param pemTrustOptions the trust options * @return reference to this, for fluency */ public ConsulClientOptions setPemTrustOptions(PemTrustOptions pemTrustOptions) { super.setPemTrustOptions(pemTrustOptions); return this; } /** * Set the connect timeout * * @param connectTimeout connect timeout, in ms * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setConnectTimeout(int connectTimeout) { return (ConsulClientOptions) super.setConnectTimeout(connectTimeout); } /** * Set the maximum pool size for connections * * @param maxPoolSize the maximum pool size * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setMaxPoolSize(int maxPoolSize) { return (ConsulClientOptions) super.setMaxPoolSize(maxPoolSize); } /** * Set a client limit of the number concurrent streams for each HTTP/2 connection, this limits the number * of streams the client can create for a connection. The effective number of streams for a * connection is the min of this value and the server's initial settings. * <p/> * Setting the value to {@code -1} means to use the value sent by the server's initial settings. * {@code -1} is the default value. * * @param limit the maximum concurrent for an HTTP/2 connection * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setHttp2MultiplexingLimit(int limit) { return (ConsulClientOptions) super.setHttp2MultiplexingLimit(limit); } /** * Set the maximum pool size for HTTP/2 connections * * @param max the maximum pool size * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setHttp2MaxPoolSize(int max) { return (ConsulClientOptions) super.setHttp2MaxPoolSize(max); } /** * Set the default HTTP/2 connection window size. It overrides the initial window * size set by {@link Http2Settings#getInitialWindowSize}, so the connection window size * is greater than for its streams, in order the data throughput. * <p/> * A value of {@code -1} reuses the initial window size setting. * * @param http2ConnectionWindowSize the window size applied to the connection * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setHttp2ConnectionWindowSize(int http2ConnectionWindowSize) { return (ConsulClientOptions) super.setHttp2ConnectionWindowSize(http2ConnectionWindowSize); } /** * Set whether keep alive is enabled on the client * * @param keepAlive true if enabled * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setKeepAlive(boolean keepAlive) { return (ConsulClientOptions) super.setKeepAlive(keepAlive); } /** * Set whether pipe-lining is enabled on the client * * @param pipelining true if enabled * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setPipelining(boolean pipelining) { return (ConsulClientOptions) super.setPipelining(pipelining); } /** * Set the limit of pending requests a pipe-lined HTTP/1 connection can send. * * @param limit the limit of pending requests * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setPipeliningLimit(int limit) { return (ConsulClientOptions) super.setPipeliningLimit(limit); } /** * Set whether hostname verification is enabled * * @param verifyHost true if enabled * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setVerifyHost(boolean verifyHost) { return (ConsulClientOptions) super.setVerifyHost(verifyHost); } /** * Set whether compression is enabled * * @param tryUseCompression true if enabled * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setTryUseCompression(boolean tryUseCompression) { return (ConsulClientOptions) super.setTryUseCompression(tryUseCompression); } /** * Set true when the client wants to skip frame masking. * You may want to set it true on server by server websocket communication: In this case you are by passing RFC6455 protocol. * It's false as default. * * @param sendUnmaskedFrames true if enabled * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setSendUnmaskedFrames(boolean sendUnmaskedFrames) { return (ConsulClientOptions) super.setSendUnmaskedFrames(sendUnmaskedFrames); } /** * Set the max websocket frame size * * @param maxWebsocketFrameSize the max frame size, in bytes * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setMaxWebsocketFrameSize(int maxWebsocketFrameSize) { return (ConsulClientOptions) super.setMaxWebsocketFrameSize(maxWebsocketFrameSize); } /** * Set the default host name to be used by this client in requests if none is provided when making the request. * * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setDefaultHost(String defaultHost) { return (ConsulClientOptions) super.setDefaultHost(defaultHost); } /** * Set the default port to be used by this client in requests if none is provided when making the request. * * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setDefaultPort(int defaultPort) { return (ConsulClientOptions) super.setDefaultPort(defaultPort); } /** * Set the protocol version. * * @param protocolVersion the protocol version * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setProtocolVersion(HttpVersion protocolVersion) { return (ConsulClientOptions) super.setProtocolVersion(protocolVersion); } /** * Set the maximum HTTP chunk size * @param maxChunkSize the maximum chunk size * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setMaxChunkSize(int maxChunkSize) { return (ConsulClientOptions) super.setMaxChunkSize(maxChunkSize); } /** * Set the maximum length of the initial line for HTTP/1.x (e.g. {@code "HTTP/1.1 200 OK"}) * * @param maxInitialLineLength the new maximum initial length * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setMaxInitialLineLength(int maxInitialLineLength) { return (ConsulClientOptions) super.setMaxInitialLineLength(maxInitialLineLength); } /** * Set the maximum length of all headers for HTTP/1.x . * * @param maxHeaderSize the new maximum length * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setMaxHeaderSize(int maxHeaderSize) { return (ConsulClientOptions) super.setMaxHeaderSize(maxHeaderSize); } /** * Set the maximum requests allowed in the wait queue, any requests beyond the max size will result in * a ConnectionPoolTooBusyException. If the value is set to a negative number then the queue will be unbounded. * @param maxWaitQueueSize the maximum number of waiting requests * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setMaxWaitQueueSize(int maxWaitQueueSize) { return (ConsulClientOptions) super.setMaxWaitQueueSize(maxWaitQueueSize); } /** * Set the HTTP/2 connection settings immediately sent by to the server when the client connects. * * @param settings the settings value * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setInitialSettings(Http2Settings settings) { return (ConsulClientOptions) super.setInitialSettings(settings); } /** * Set the ALPN usage. * * @param useAlpn true when Application-Layer Protocol Negotiation should be used */ @Override public ConsulClientOptions setUseAlpn(boolean useAlpn) { return (ConsulClientOptions) super.setUseAlpn(useAlpn); } /** * Set to use SSL engine implementation to use. * * @param sslEngineOptions the ssl engine to use * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setSslEngineOptions(SSLEngineOptions sslEngineOptions) { return (ConsulClientOptions) super.setSslEngineOptions(sslEngineOptions); } @Override public ConsulClientOptions setJdkSslEngineOptions(JdkSSLEngineOptions sslEngineOptions) { return (ConsulClientOptions) super.setJdkSslEngineOptions(sslEngineOptions); } @Override public ConsulClientOptions setOpenSslEngineOptions(OpenSSLEngineOptions sslEngineOptions) { return (ConsulClientOptions) super.setOpenSslEngineOptions(sslEngineOptions); } /** * Set the list of protocol versions to provide to the server during the Application-Layer Protocol Negotiation. * When the list is empty, the client provides a best effort list according to {@link #setProtocolVersion}: * * <ul> * <li>{@link HttpVersion#HTTP_2}: [ "h2", "http/1.1" ]</li> * <li>otherwise: [{@link #getProtocolVersion()}]</li> * </ul> * * @param alpnVersions the versions * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setAlpnVersions(List<HttpVersion> alpnVersions) { return (ConsulClientOptions) super.setAlpnVersions(alpnVersions); } /** * Set to {@code true} when an <i>h2c</i> connection is established using an HTTP/1.1 upgrade request, and {@code false} * when an <i>h2c</i> connection is established directly (with prior knowledge). * * @param value the upgrade value * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setHttp2ClearTextUpgrade(boolean value) { return (ConsulClientOptions) super.setHttp2ClearTextUpgrade(value); } /** * Set to {@code maxRedirects} the maximum number of redirection a request can follow. * * @param maxRedirects the maximum number of redirection * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setMaxRedirects(int maxRedirects) { return (ConsulClientOptions) super.setMaxRedirects(maxRedirects); } /** * Set the metrics name identifying the reported metrics, useful for grouping metrics * with the same name. * * @param metricsName the metrics name * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setMetricsName(String metricsName) { return (ConsulClientOptions) super.setMetricsName(metricsName); } /** * Set proxy options for connections via CONNECT proxy (e.g. Squid) or a SOCKS proxy. * * @param proxyOptions proxy options object * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setProxyOptions(ProxyOptions proxyOptions) { return (ConsulClientOptions) super.setProxyOptions(proxyOptions); } /** * Set the local interface to bind for network connections. When the local address is null, * it will pick any local address, the default local address is null. * * @param localAddress the local address * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setLocalAddress(String localAddress) { return (ConsulClientOptions) super.setLocalAddress(localAddress); } /** * Set to true to enabled network activity logging: Netty's pipeline is configured for logging on Netty's logger. * * @param logActivity true for logging the network activity * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setLogActivity(boolean logActivity) { return (ConsulClientOptions) super.setLogActivity(logActivity); } /** * Sets whether the Web Client should send a user agent header. Defaults to true. * * @param userAgentEnabled true to send a user agent header, false otherwise * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setUserAgentEnabled(boolean userAgentEnabled) { return (ConsulClientOptions) super.setUserAgentEnabled(userAgentEnabled); } /** * Sets the Web Client user agent header. Defaults to Vert.x-WebClient/&lt;version&gt;. * * @param userAgent user agent header value * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setUserAgent(String userAgent) { return (ConsulClientOptions) super.setUserAgent(userAgent); } /** * Configure the default behavior of the client to follow HTTP {@code 30x} redirections. * * @param followRedirects true when a redirect is followed * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setFollowRedirects(boolean followRedirects) { return (ConsulClientOptions) super.setFollowRedirects(followRedirects); } /** * Set the max websocket message size * * @param maxWebsocketMessageSize the max message size, in bytes * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setMaxWebsocketMessageSize(int maxWebsocketMessageSize) { return (ConsulClientOptions) super.setMaxWebsocketMessageSize(maxWebsocketMessageSize); } /** * Add an enabled cipher suite, appended to the ordered suites. * * @param suite the suite * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions addEnabledCipherSuite(String suite) { return (ConsulClientOptions) super.addEnabledCipherSuite(suite); } /** * Add an enabled SSL/TLS protocols, appended to the ordered protocols. * * @param protocol the SSL/TLS protocol do enabled * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions addEnabledSecureTransportProtocol(String protocol) { return (ConsulClientOptions) super.addEnabledSecureTransportProtocol(protocol); } /** * Add a CRL path * @param crlPath the path * @return a reference to this, so the API can be used fluently * @throws NullPointerException */ @Override public ConsulClientOptions addCrlPath(String crlPath) throws NullPointerException { return (ConsulClientOptions) super.addCrlPath(crlPath); } /** * Add a CRL value * * @param crlValue the value * @return a reference to this, so the API can be used fluently * @throws NullPointerException */ @Override public ConsulClientOptions addCrlValue(Buffer crlValue) throws NullPointerException { return (ConsulClientOptions) super.addCrlValue(crlValue); } /** * By default, the server name is only sent for Fully Qualified Domain Name (FQDN), setting * this property to {@code true} forces the server name to be always sent. * * @param forceSni true when the client should always use SNI on TLS/SSL connections * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setForceSni(boolean forceSni) { return (ConsulClientOptions) super.setForceSni(forceSni); } /** * set to {@code initialBufferSizeHttpDecoder} the initial buffer of the HttpDecoder. * @param decoderInitialBufferSize the initial buffer size * @return a reference to this, so the API can be used fluently */ @Override public ConsulClientOptions setDecoderInitialBufferSize(int decoderInitialBufferSize) { return (ConsulClientOptions) super.setDecoderInitialBufferSize(decoderInitialBufferSize); } @Override public ConsulClientOptions removeEnabledSecureTransportProtocol(String protocol) { return (ConsulClientOptions) super.removeEnabledSecureTransportProtocol(protocol); } @Override public ConsulClientOptions setHttp2KeepAliveTimeout(int keepAliveTimeout) { return (ConsulClientOptions) super.setHttp2KeepAliveTimeout(keepAliveTimeout); } @Override public ConsulClientOptions setKeepAliveTimeout(int keepAliveTimeout) { return (ConsulClientOptions) super.setKeepAliveTimeout(keepAliveTimeout); } @Override public ConsulClientOptions setPoolCleanerPeriod(int poolCleanerPeriod) { return (ConsulClientOptions) super.setPoolCleanerPeriod(poolCleanerPeriod); } @Override public ConsulClientOptions setEnabledSecureTransportProtocols(Set<String> enabledSecureTransportProtocols) { return (ConsulClientOptions) super.setEnabledSecureTransportProtocols(enabledSecureTransportProtocols); } }
package me.nallar.javapatcher.mappings; import java.util.*; /** * Maps method/field/class names in patches to allow obfuscated code to be patched. */ public abstract class Mappings { /** * Takes a list of Class/Method/FieldDescriptions and maps them all using the appropriate map(*Description) * * @param list List of Class/Method/FieldDescriptions * @return Mapped List */ @SuppressWarnings("unchecked") public final <T> List<T> map(List<T> list) { List<T> mappedThings = new ArrayList<T>(); for (Object thing : list) { // TODO - cleaner way of doing this? if (thing instanceof MethodDescription) { mappedThings.add((T) map((MethodDescription) thing)); } else if (thing instanceof ClassDescription) { mappedThings.add((T) map((ClassDescription) thing)); } else if (thing instanceof FieldDescription) { mappedThings.add((T) map((FieldDescription) thing)); } else { throw new IllegalArgumentException("Must be mappable: " + thing + "isn't!"); } } return mappedThings; } public abstract MethodDescription map(MethodDescription methodDescription); public abstract ClassDescription map(ClassDescription classDescription); public abstract FieldDescription map(FieldDescription fieldDescription); public abstract MethodDescription unmap(MethodDescription methodDescription); public abstract String obfuscate(String code); }
package me.tsukanov.counter.ui; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.widget.Toast; import me.tsukanov.counter.CounterApplication; import me.tsukanov.counter.R; public class SettingsActivity extends PreferenceActivity implements OnPreferenceChangeListener { private SharedPreferences sharedPref; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings); sharedPref = PreferenceManager.getDefaultSharedPreferences(this); String version; try { version = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName; } catch (NameNotFoundException e) { version = getResources().getString(R.string.unknown); } Preference versionPref = findPreference("version"); versionPref.setSummary(version); getPreferenceManager().findPreference("removeCounters") .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { showWipeDialog(); return true; } }); } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { return false; } private void showWipeDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.settings_wipe_confirmation); builder.setPositiveButton(R.string.settings_wipe_confirmation_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { CounterApplication app = (CounterApplication) getApplication(); app.removeCounters(); SharedPreferences.Editor settingsEditor = sharedPref.edit(); if (app.counters.isEmpty()) { settingsEditor.putString(MainActivity.STATE_ACTIVE_COUNTER, getString(R.string.default_counter_name)); } else { settingsEditor.putString(MainActivity.STATE_ACTIVE_COUNTER, app.counters.keySet().iterator().next()); } settingsEditor.commit(); Toast.makeText( getBaseContext(), getResources().getText(R.string.toast_wipe_success), Toast.LENGTH_SHORT ).show(); } }); builder.setNegativeButton(R.string.dialog_button_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.create().show(); } }
package me.zero.client.api.value.type; import me.zero.client.api.util.ClientUtils; import me.zero.client.api.value.Value; import org.apache.commons.lang3.ArrayUtils; import java.lang.reflect.Field; /** * A value that can have a specific set of values * * @author Brady * @since 2/24/2017 12:00 PM */ public final class MultiType extends Value<String> { /** * Different values */ private final String[] values; public MultiType(String name, String id, String description, Object object, Field field, String[] values) { super(name, id, description, object, field); this.values = values; this.setValue(values[0]); } @Override public final void setValue(String value) { super.setValue(ClientUtils.objectFrom(value, values)); } /** * Sets value to the next one in the set */ public final void next() { int index = ArrayUtils.indexOf(values, getValue()); if (++index >= values.length) index = 0; this.setValue(values[index]); } /** * Sets value to the last one in the set */ public final void last() { int index = ArrayUtils.indexOf(values, getValue()); if (--index < 0) index = values.length - 1; this.setValue(values[index]); } /** * @return All possible values for this MultiType */ public final String[] getValues() { return this.values; } }
package me.zford.jobs.bukkit; import java.util.concurrent.LinkedBlockingQueue; public class PlayerLoginManager extends Thread { private JobsPlugin plugin; private LinkedBlockingQueue<JobsLogin> queue = new LinkedBlockingQueue<JobsLogin>(); private volatile boolean running = true; public PlayerLoginManager(JobsPlugin plugin) { super("Jobs-PlayerLoginTask"); this.plugin = plugin; } public void addPlayer(String playerName) { queue.add(new JobsLogin(playerName, LoginType.LOGIN)); } public void removePlayer(String playerName) { queue.add(new JobsLogin(playerName, LoginType.LOGOUT)); } @Override public void run() { plugin.getLogger().info("Login manager started"); while (running) { JobsLogin login = null; try { login = queue.take(); } catch (InterruptedException e) {} if (login == null) continue; try { if (login.getType().equals(LoginType.LOGIN)) { plugin.getPlayerManager().addPlayer(login.getPlayer()); } else if (login.getType().equals(LoginType.LOGOUT)) { plugin.getPlayerManager().removePlayer(login.getPlayer()); } } catch (Throwable t) { t.printStackTrace(); } } plugin.getLogger().info("Login manager shutdown"); } public void shutdown() { this.running = false; interrupt(); } public enum LoginType { LOGIN, LOGOUT, } public class JobsLogin { private String playerName; private LoginType type; public JobsLogin(String playerName, LoginType type) { this.playerName = playerName; this.type = type; } public String getPlayer() { return playerName; } public LoginType getType() { return type; } } }
package net.addradio.codec.mpeg.audio; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.addradio.codec.id3.model.ID3Tag; import net.addradio.codec.mpeg.audio.codecs.MPEGAudioCodecException; import net.addradio.codec.mpeg.audio.model.MPEGAudioContent; import net.addradio.codec.mpeg.audio.model.MPEGAudioFrame; import net.addradio.codec.mpeg.audio.tools.MPEGAudioContentCollectorHandler; import net.addradio.codec.mpeg.audio.tools.MPEGAudioContentFilter; import net.addradio.codec.mpeg.audio.tools.MPEGAudioContentHandler; import net.addradio.codec.mpeg.audio.tools.MPEGAudioFirstContentOnlyHandler; /** * MPEGAudio. */ public class MPEGAudio { /** {@link Logger} LOG. */ private final static Logger LOG = LoggerFactory.getLogger(MPEGAudio.class); /** * decode. * @param file {@link File} * @return {@link List}{@code <}{@link MPEGAudioContent}{@code >} or {@code null} if file could not be opened. */ public static final List<MPEGAudioContent> decode(final File file) { return decode(file, MPEGAudioContentFilter.ACCEPT_ALL); } /** * decode. * @param file {@link File} * @param filter {@link MPEGAudioContentFilter} * @return {@link List}{@code <}{@link MPEGAudioContent}{@code >} or {@code null} if file could not be opened. */ public static List<MPEGAudioContent> decode(final File file, final MPEGAudioContentFilter filter) { try (final InputStream is = new FileInputStream(file)) { return decode(is, filter); } catch (final IOException e1) { MPEGAudio.LOG.error(e1.getLocalizedMessage(), e1); } return null; } /** * decode. * @param is {@link InputStream} * @param filter {@link MPEGAudioContentFilter} * @return {@link List}{@code <}{@link MPEGAudioContent}{@code >} */ public static final List<MPEGAudioContent> decode(final InputStream is) { return decode(is, MPEGAudioContentFilter.ACCEPT_ALL); } /** * decode. * @param is {@link InputStream} * @param filter {@link MPEGAudioContentFilter} * @return {@link List}{@code <}{@link MPEGAudioContent}{@code >} */ public static List<MPEGAudioContent> decode(final InputStream is, final MPEGAudioContentFilter filter) { final MPEGAudioContentCollectorHandler handler = new MPEGAudioContentCollectorHandler(); decode(is, filter, handler); return handler.getContents(); } /** * decode. * @param is {@link InputStream} * @param filter {@link MPEGAudioContentFilter} * @param handler {@link MPEGAudioContentHandler} */ public static void decode(final InputStream is, final MPEGAudioContentFilter filter, final MPEGAudioContentHandler handler) { try (final MPEGAudioFrameInputStream mafis = new MPEGAudioFrameInputStream(is)) { MPEGAudioContent frame = null; while ((frame = mafis.readFrame()) != null) { if (filter.accept(frame)) { if (handler.handle(frame)) { break; } } } } catch (final IOException e) { MPEGAudio.LOG.error(e.getLocalizedMessage(), e); } } /** * decode. * @param fileName {@link String} * @return {@link List}{@code <}{@link MPEGAudioContent}{@code >} or {@code null} if file could not be opened. */ public static final List<MPEGAudioContent> decode(final String fileName) { return decode(fileName != null ? new File(fileName) : null); } /** * decodeFirstID3Tag. * @param is {@link InputStream} * @return {@link ID3Tag} */ public static ID3Tag decodeFirstID3Tag(final InputStream is) { return (ID3Tag) decodeFirstMPEGAudioContent(is, MPEGAudioContentFilter.ID3_TAGS); } /** * decodeFirstMPEGAudioContent. * @param is {@link InputStream} * @param filter {@link MPEGAudioContentFilter} * @return {@link MPEGAudioContent} first content decoded from stream matching the filter's criteria or {@code null} if no adequate content will be found. */ public static MPEGAudioContent decodeFirstMPEGAudioContent(final InputStream is, final MPEGAudioContentFilter filter) { final MPEGAudioFirstContentOnlyHandler handler = new MPEGAudioFirstContentOnlyHandler(); decode(is, filter, handler); return handler.getFirstContent(); } /** * decodeFirstMPEGAudioFrame. * @param buffer {@code byte[]} * @return {@link MPEGAudioFrame} or {@code null} if nothing could be decoded. */ public static MPEGAudioFrame decodeFirstMPEGAudioFrame(final byte[] buffer) { return decodeFirstMPEGAudioFrame(new ByteArrayInputStream(buffer)); } /** * decodeFirstMPEGAudioFrame. * @param is {@link InputStream} * @return {@link MPEGAudioFrame} */ public static MPEGAudioFrame decodeFirstMPEGAudioFrame(final InputStream is) { return (MPEGAudioFrame) decodeFirstMPEGAudioContent(is, MPEGAudioContentFilter.MPEG_AUDIO_FRAMES); } /** * encode. * @param frames {@link List}{@code <}{@link MPEGAudioContent}{@code >} * @return {@code byte[]} or {@code null} if an error occurred. */ public static byte[] encode(final List<? extends MPEGAudioContent> frames) { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { encode(frames, baos); return baos.toByteArray(); } catch (final IOException e) { MPEGAudio.LOG.error(e.getLocalizedMessage(), e); } return null; } /** * encode. * @param frames {@link List}{@code <}{@link MPEGAudioContent}{@code >} * @param os {@link OutputStream} * @throws IOException due to IO problems. */ public static void encode(final List<? extends MPEGAudioContent> frames, final OutputStream os) throws IOException { try (MPEGAudioFrameOutputStream mafos = new MPEGAudioFrameOutputStream(os)) { for (final MPEGAudioContent mpegAudioFrame : frames) { try { mafos.writeFrame(mpegAudioFrame); } catch (final MPEGAudioCodecException e) { MPEGAudio.LOG.error(e.getLocalizedMessage(), e); } } } } }
package net.caseif.ttt.listeners; import net.caseif.ttt.Body; import net.caseif.ttt.TTTCore; import net.caseif.ttt.scoreboard.ScoreboardManager; import net.caseif.ttt.util.Constants.Color; import net.caseif.ttt.util.Constants.Role; import net.caseif.ttt.util.Constants.Stage; import net.caseif.ttt.util.MiscUtil; import net.caseif.ttt.util.helper.ConfigHelper; import net.caseif.ttt.util.helper.InventoryHelper; import net.caseif.ttt.util.helper.KarmaHelper; import net.caseif.ttt.util.helper.LocationHelper; import net.caseif.ttt.util.helper.NmsHelper; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import net.caseif.flint.challenger.Challenger; import net.caseif.flint.util.physical.Location3D; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.Chest; import org.bukkit.block.DoubleChest; import org.bukkit.entity.Arrow; import org.bukkit.entity.EntityType; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityRegainHealthEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class PlayerListener implements Listener { private final ImmutableList<String> disabledCommands = ImmutableList.of("kit", "msg", "pm", "r", "me"); private static Field fieldRbHelper; private static Method logBlockChange; @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.HIGHEST) //TODO: fix the crazy nesting in this method public void onPlayerInteract(PlayerInteractEvent event) { if (TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).isPresent()) { // check if player is in TTT round Challenger ch = TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).get(); if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { // disallow cheating/bed setting if (event.getClickedBlock().getType() == Material.ENDER_CHEST || event.getClickedBlock().getType() == Material.BED_BLOCK) { event.setCancelled(true); return; } // handle body checking Location3D clicked = new Location3D( event.getClickedBlock().getX(), event.getClickedBlock().getY(), event.getClickedBlock().getZ()); if (event.getClickedBlock().getType() == Material.CHEST) { if (ch.isSpectating()) { event.setCancelled(true); for (Body b : TTTCore.bodies) { if (b.getLocation().equals(clicked)) { Inventory chestInv = ((Chest) event.getClickedBlock().getState()).getInventory(); Inventory inv = TTTCore.getInstance().getServer().createInventory(chestInv.getHolder(), chestInv.getSize()); inv.setContents(chestInv.getContents()); event.getPlayer().openInventory(inv); TTTCore.locale.getLocalizable("info.personal.status.discreet-search") .withPrefix(Color.INFO.toString()).sendTo(event.getPlayer()); break; } } } else { int index = -1; for (int i = 0; i < TTTCore.bodies.size(); i++) { if (TTTCore.bodies.get(i).getLocation() .equals(clicked)) { index = i; break; } } if (index != -1) { boolean found = false; for (Body b : TTTCore.foundBodies) { if (b.getLocation().equals(clicked)) { found = true; break; } } if (!found) { // it's a new body Body b = TTTCore.bodies.get(index); Optional<Challenger> bodyPlayer = TTTCore.mg.getChallenger(TTTCore.bodies.get(index).getPlayer()); //TODO: make this DRYer switch (b.getRole()) { case Role.INNOCENT: { for (Challenger c : b.getRound().getChallengers()) { Player pl = Bukkit.getPlayer(c.getUniqueId()); pl.sendMessage(Color.INNOCENT + TTTCore.locale .getLocalizable("info.global.round.event.body-find") .withReplacements(event.getPlayer().getName(), b.getPlayer().toString()).localizeFor(pl) + " " + TTTCore.locale .getLocalizable("info.global.round.event.body-find.innocent") .localizeFor(pl)); } break; } case Role.TRAITOR: { for (Challenger c : b.getRound().getChallengers()) { Player pl = Bukkit.getPlayer(c.getUniqueId()); pl.sendMessage(Color.TRAITOR + TTTCore.locale .getLocalizable("info.global.round.event.body-find") .withReplacements(event.getPlayer().getName(), b.getPlayer().toString()).localizeFor(pl) + " " + TTTCore.locale .getLocalizable("info.global.round.event.body-find.traitor") .localizeFor(pl)); } break; } case Role.DETECTIVE: { for (Challenger c : b.getRound().getChallengers()) { Player pl = Bukkit.getPlayer(c.getUniqueId()); pl.sendMessage(Color.DETECTIVE + TTTCore.locale .getLocalizable("info.global.round.event.body-find") .withReplacements(event.getPlayer().getName(), b.getPlayer().toString()).localizeFor(pl) + " " + TTTCore.locale .getLocalizable("info.global.round.event.body-find.detective") .localizeFor(pl)); } break; } default: { event.getPlayer().sendMessage("Something's gone terribly wrong inside the TTT " + "plugin. Please notify an admin."); // eh, may as well tell the player throw new AssertionError("Failed to determine role of found body. " + "Report this immediately."); } } TTTCore.foundBodies.add(TTTCore.bodies.get(index)); if (bodyPlayer.isPresent() && bodyPlayer.get().getRound().equals(TTTCore.bodies.get(index).getRound())) { //TODO: no Flint equivalent for this //bodyPlayer.setPrefix(Config.SB_ALIVE_PREFIX); bodyPlayer.get().getMetadata().set("bodyFound", true); if (ScoreboardManager.get(bodyPlayer.get().getRound()).isPresent()) { ScoreboardManager.get(bodyPlayer.get().getRound()).get() .update(bodyPlayer.get()); } } } if (ch.getMetadata().has(Role.DETECTIVE)) { // handle DNA scanning if (event.getPlayer().getItemInHand() != null && event.getPlayer().getItemInHand().getType() == Material.COMPASS && event.getPlayer().getItemInHand().getItemMeta() != null && event.getPlayer().getItemInHand().getItemMeta().getDisplayName() != null && event.getPlayer().getItemInHand().getItemMeta().getDisplayName().endsWith( TTTCore.locale.getLocalizable("item.dna-scanner.name").localize())) { event.setCancelled(true); Body body = TTTCore.bodies.get(index); if (body.getKiller().isPresent()) { Player killer = Bukkit.getPlayer(body.getKiller().get()); if (killer != null) { if (TTTCore.mg.getChallenger(killer.getUniqueId()).isPresent()) { if (!TTTCore.mg.getChallenger(killer.getUniqueId()).get() .isSpectating()) { ch.getMetadata().set("tracking", killer.getName()); } TTTCore.locale.getLocalizable("info.personal.status.collect-dna") .withPrefix(Color.INFO.toString()) .withReplacements(Bukkit.getPlayer(TTTCore.bodies.get(index) .getPlayer()).getName()) .sendTo(event.getPlayer()); } else { TTTCore.locale.getLocalizable("error.round.killer-left") .withPrefix(Color.ERROR.toString()).sendTo(event.getPlayer()); } } else { TTTCore.locale.getLocalizable("error.round.killer-left") .withPrefix(Color.ERROR.toString()).sendTo(event.getPlayer()); } } return; } } } } } } } // guns if (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR) { if (event.getPlayer().getItemInHand() != null) { if (event.getPlayer().getItemInHand().getItemMeta() != null) { if (event.getPlayer().getItemInHand().getItemMeta().getDisplayName() != null) { if (event.getPlayer().getItemInHand().getItemMeta().getDisplayName() .endsWith(TTTCore.locale.getLocalizable("item.gun.name").localize())) { if ((TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).isPresent() && !TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).get().isSpectating() && (TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).get().getRound() .getLifecycleStage() == Stage.PLAYING) || ConfigHelper.GUNS_OUTSIDE_ARENAS)) { event.setCancelled(true); if (event.getPlayer().getInventory().contains(Material.ARROW) || !ConfigHelper.REQUIRE_AMMO_FOR_GUNS) { if (ConfigHelper.REQUIRE_AMMO_FOR_GUNS) { InventoryHelper.removeArrow(event.getPlayer().getInventory()); event.getPlayer().updateInventory(); } event.getPlayer().launchProjectile(Arrow.class); } else { TTTCore.locale.getLocalizable("info.personal.status.no-ammo") .withPrefix(Color.ERROR.toString()).sendTo(event.getPlayer()); } } } } } } } } @EventHandler(priority = EventPriority.HIGHEST) public void onEntityDamage(EntityDamageEvent event) { if (event.getEntityType() == EntityType.PLAYER) { Optional<Challenger> victim = TTTCore.mg.getChallenger(event.getEntity().getUniqueId()); if (victim.isPresent() && victim.get().getRound().getLifecycleStage() != Stage.PLAYING) { if (event.getCause() == DamageCause.VOID) { Bukkit.getPlayer(victim.get().getUniqueId()); } else { event.setCancelled(true); } } if (event instanceof EntityDamageByEntityEvent) { EntityDamageByEntityEvent ed = (EntityDamageByEntityEvent) event; if (ed.getDamager().getType() == EntityType.PLAYER || (ed.getDamager() instanceof Projectile && ((Projectile) ed.getDamager()).getShooter() instanceof Player)) { Player damager = ed.getDamager().getType() == EntityType.PLAYER ? (Player) ed.getDamager() : (Player) ((Projectile) ed.getDamager()).getShooter(); if (TTTCore.mg.getChallenger(damager.getUniqueId()).isPresent()) { Challenger mgDamager = TTTCore.mg.getChallenger(damager.getUniqueId()).get(); if (mgDamager.getRound().getLifecycleStage() != Stage.PLAYING || !victim.isPresent()) { event.setCancelled(true); return; } if (damager.getItemInHand() != null) { if (damager.getItemInHand().getItemMeta() != null) { if (damager.getItemInHand().getItemMeta().getDisplayName() != null) { if (damager.getItemInHand().getItemMeta().getDisplayName() .endsWith(TTTCore.locale.getLocalizable("item.crowbar.name") .localize())) { event.setDamage(ConfigHelper.CROWBAR_DAMAGE); } } } } Optional<Double> reduc = mgDamager.getMetadata().get("damageRed"); if (reduc.isPresent()) { event.setDamage((int) (event.getDamage() * reduc.get())); } KarmaHelper.applyDamageKarma(mgDamager, victim.get(), event.getDamage()); } } } } } @EventHandler public void onPlayerPickupItem(PlayerPickupItemEvent event) { if (TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).isPresent()) { event.setCancelled(true); } } @EventHandler public void onPlayerDropItem(PlayerDropItemEvent event) { if (TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).isPresent()) { event.setCancelled(true); TTTCore.locale.getLocalizable("info.personal.status.no-drop").withPrefix(Color.ERROR.toString()) .sendTo(event.getPlayer()); } } @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { if (!ConfigHelper.KARMA_PERSISTENCE) { KarmaHelper.resetKarma(event.getPlayer().getUniqueId()); } } @EventHandler public void onHealthRegenerate(EntityRegainHealthEvent event) { if (event.getEntity() instanceof Player) { Player p = (Player) event.getEntity(); if (TTTCore.mg.getChallenger(p.getUniqueId()).isPresent()) { event.setCancelled(true); } } } @EventHandler(priority = EventPriority.HIGHEST) public void onInventoryClick(InventoryClickEvent event) { for (HumanEntity he : event.getViewers()) { Player p = (Player) he; if (TTTCore.mg.getChallenger(p.getUniqueId()).isPresent()) { if (event.getInventory().getType() == InventoryType.CHEST) { Block block; Block block2 = null; if (event.getInventory().getHolder() instanceof Chest) { block = ((Chest) event.getInventory().getHolder()).getBlock(); } else if (event.getInventory().getHolder() instanceof DoubleChest) { block = ((Chest) ((DoubleChest) event.getInventory().getHolder()).getLeftSide()).getBlock(); block2 = ((Chest) ((DoubleChest) event.getInventory().getHolder()).getRightSide()).getBlock(); } else { return; } Location3D l1 = LocationHelper.convert(block.getLocation()); Location3D l2 = block2 != null ? LocationHelper.convert(block2.getLocation()) : null; for (Body b : TTTCore.bodies) { if (b.getLocation().equals(l1) || b.getLocation().equals(l2)) { event.setCancelled(true); return; } } } } } } //TODO: probably split this up a little @EventHandler public void onPlayerDeath(PlayerDeathEvent event) { Player pl = event.getEntity(); // admittedly not the best way of doing this, but easiest for the purpose of porting Optional<Challenger> chOpt = TTTCore.mg.getChallenger(pl.getUniqueId()); if (chOpt.isPresent()) { Challenger ch = chOpt.get(); event.setDeathMessage(""); event.getDrops().clear(); Location loc = pl.getLocation(); // sending the packet resets the location NmsHelper.sendRespawnPacket(pl); pl.teleport(loc); ch.setSpectating(true); //ch.setPrefix(Config.SB_MIA_PREFIX); //TODO pl.setHealth(pl.getMaxHealth()); if (ScoreboardManager.get(ch.getRound()).isPresent()) { ScoreboardManager.get(ch.getRound()).get().update(ch); } Optional<Challenger> killer = event.getEntity().getKiller() != null ? TTTCore.mg.getChallenger(event.getEntity().getKiller().getUniqueId()) : Optional.<Challenger>absent(); if (killer.isPresent()) { // set killer's karma KarmaHelper.applyKillKarma(killer.get(), ch); ch.getMetadata().set("killer", killer.get().getUniqueId()); } Block block = loc.getBlock(); //TTTCore.mg.getRollbackManager().logBlockChange(block, ch.getArena()); //TODO (probably Flint 1.1) //TODO: Add check for doors and such //TODO: move this code to another method try { //TODO: temporary hack (I'm still a terrible person for even writing this) if (fieldRbHelper == null) { fieldRbHelper = ch.getRound().getArena().getClass().getDeclaredField("rbHelper"); fieldRbHelper.setAccessible(true); } Object rbHelper = fieldRbHelper.get(ch.getRound().getArena()); if (logBlockChange == null) { logBlockChange = rbHelper.getClass().getDeclaredMethod("logBlockChange", Location.class, BlockState.class); logBlockChange.setAccessible(true); } logBlockChange.invoke(rbHelper, loc, loc.getBlock().getState()); } catch (IllegalAccessException | InvocationTargetException | NoSuchFieldException | NoSuchMethodException ex) { TTTCore.log.severe("Failed to log body for rollback"); ex.printStackTrace(); } block.setType(((loc.getBlockX() + loc.getBlockY()) % 2 == 0) ? Material.TRAPPED_CHEST : Material.CHEST); Chest chest = (Chest) block.getState(); // player identifier ItemStack id = new ItemStack(Material.PAPER, 1); ItemMeta idMeta = id.getItemMeta(); idMeta.setDisplayName(TTTCore.locale.getLocalizable("item.id.name").localize()); List<String> idLore = new ArrayList<>(); idLore.add(TTTCore.locale.getLocalizable("corpse.of").withReplacements(ch.getName()).localize()); idLore.add(ch.getName()); idMeta.setLore(idLore); id.setItemMeta(idMeta); // role identifier ItemStack ti = new ItemStack(Material.WOOL, 1); ItemMeta tiMeta = ti.getItemMeta(); short durability; String roleId = ""; if (ch.getMetadata().has(Role.DETECTIVE)) { durability = 11; roleId = "detective"; } else if (!MiscUtil.isTraitor(ch)) { durability = 5; roleId = "innocent"; } else { durability = 14; roleId = "traitor"; } ti.setDurability(durability); tiMeta.setDisplayName(TTTCore.locale.getLocalizable("fragment." + roleId) .withPrefix(Color.DETECTIVE.toString()).localize()); tiMeta.setLore(Collections.singletonList(TTTCore.locale.getLocalizable("item.id." + roleId).localize())); ti.setItemMeta(tiMeta); chest.getInventory().addItem(id, ti); TTTCore.bodies.add( new Body( ch.getRound(), LocationHelper.convert(block.getLocation()), ch.getUniqueId(), killer.isPresent() ? killer.get().getUniqueId() : null, ch.getMetadata().has(Role.DETECTIVE) ? Role.DETECTIVE : (ch.getTeam().isPresent() ? ch.getTeam().get().getId() : null), System.currentTimeMillis() ) ); } } @EventHandler public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { String label = event.getMessage().split(" ")[0].substring(1); if (disabledCommands.contains(label)) { if (TTTCore.mg.getChallenger(event.getPlayer().getUniqueId()).isPresent()) { event.setCancelled(true); TTTCore.locale.getLocalizable("error.round.disabled-command").withPrefix(Color.ERROR.toString()) .sendTo(event.getPlayer()); } } } }
package net.redborder.utils.types.impl; import net.redborder.utils.types.MappedType; import net.redborder.utils.types.Type; import net.redborder.utils.types.TypeManager; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; public class JsonType implements Type { Map<String, Type> types = new HashMap<>(); public JsonType(Map<String, Object> params) { Map<String, Map<String, Object>> components = (Map<String, Map<String, Object>>) params.get("components"); for (Map.Entry<String, Map<String, Object>> component : components.entrySet()) { Type type = TypeManager.newType(component.getValue()); types.put(component.getKey(), type); } } @Override public Object get() { Map<String, Object> typeValue = new HashMap<>(); for (Map.Entry<String, Type> type : types.entrySet()) { if (type.getValue() instanceof MappedType) { typeValue.putAll((Map<String, Object>) type.getValue().get()); } else { typeValue.put(type.getKey(), type.getValue().get()); } } return typeValue; } }
package net.vexelon.bgrates.db; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import net.vexelon.bgrates.Defs; import net.vexelon.bgrates.db.models.CurrencyData; public class SQLiteDataSource implements DataSource { private static final String[] ALL_COLUMNS = { Defs.COLUMN_ID, Defs.COLUMN_GOLD, Defs.COLUMN_NAME, Defs.COLUMN_CODE, Defs.COLUMN_RATIO, Defs.COLUMN_REVERSERATE, Defs.COLUMN_RATE, Defs.COLUMN_EXTRAINFO, Defs.COLUMN_CURR_DATE, Defs.COLUMN_TITLE, Defs.COLUMN_F_STAR }; // Database fields private SQLiteDatabase database; private CurrenciesSQLiteDB dbHelper; @Override public void connect(Context context) throws DataSourceException { try { dbHelper = new CurrenciesSQLiteDB(context); database = dbHelper.getWritableDatabase(); } catch (SQLException e) { throw new DataSourceException("Could not open SQLite database!", e); } } @Override public void close() { if (dbHelper != null) { dbHelper.close(); } } private Date parseStringToDate(String date, String format) throws ParseException { SimpleDateFormat formatter = new SimpleDateFormat(format); return formatter.parse(date); } private String parseDateToString(Date date, String dateFormat) { DateFormat formatter = new SimpleDateFormat(dateFormat); return formatter.format(date); } @Override public void addRates(List<CurrencyData> rates) throws DataSourceException { ContentValues values = new ContentValues(); for (int i = 0; i < rates.size(); i++) { values.put(Defs.COLUMN_GOLD, rates.get(i).getGold()); values.put(Defs.COLUMN_NAME, rates.get(i).getName()); values.put(Defs.COLUMN_CODE, rates.get(i).getCode()); values.put(Defs.COLUMN_RATIO, rates.get(i).getRatio()); values.put(Defs.COLUMN_REVERSERATE, rates.get(i).getReverseRate()); values.put(Defs.COLUMN_RATE, rates.get(i).getRate()); values.put(Defs.COLUMN_EXTRAINFO, rates.get(i).getExtraInfo()); values.put(Defs.COLUMN_CURR_DATE, parseDateToString(rates.get(i).getCurrDate(), "yyyy-MM-dd")); values.put(Defs.COLUMN_TITLE, rates.get(i).getTitle()); values.put(Defs.COLUMN_F_STAR, rates.get(i).getfStar()); database.insert(Defs.TABLE_CURRENCY, null, values); values = new ContentValues(); } } @Override public List<Date> getAvailableRatesDates() throws DataSourceException { List<Date> resultCurrency = new ArrayList<Date>(); String[] tableColumns = new String[] { Defs.COLUMN_CURR_DATE }; Cursor cursor = database.query(true, Defs.TABLE_CURRENCY, tableColumns, null, null, null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { try { resultCurrency.add(parseStringToDate(cursor.getString(cursor.getColumnIndex(Defs.COLUMN_CURR_DATE)), "yyyy-MM-dd")); } catch (ParseException e) { // TODO Auto-generated catch block throw new DataSourceException(e); } cursor.moveToNext(); } // make sure to close the cursor cursor.close(); return resultCurrency; } @Override public List<CurrencyData> getRates(Date dateOfCurrency) { List<CurrencyData> resultCurrency = new ArrayList<CurrencyData>(); String whereClause = "curr_date = ? "; String[] whereArgs = new String[] { parseDateToString(dateOfCurrency, "yyyy-MM-dd") }; Cursor cursor = database.query(Defs.TABLE_CURRENCY, ALL_COLUMNS, whereClause, whereArgs, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { CurrencyData comment = cursorToCurrency(cursor); resultCurrency.add(comment); cursor.moveToNext(); } // make sure to close the cursor cursor.close(); return resultCurrency; } @Override public List<CurrencyData> getRates() { List<CurrencyData> currencies = new ArrayList<CurrencyData>(); Cursor cursor = database.query(Defs.TABLE_CURRENCY, ALL_COLUMNS, null, null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { CurrencyData comment = cursorToCurrency(cursor); currencies.add(comment); cursor.moveToNext(); } // make sure to close the cursor cursor.close(); return currencies; } private CurrencyData cursorToCurrency(Cursor cursor) { CurrencyData currency = new CurrencyData(); currency.setGold(cursor.getInt(cursor.getColumnIndex(Defs.COLUMN_GOLD))); currency.setName(cursor.getString(cursor.getColumnIndex(Defs.COLUMN_NAME))); currency.setCode(cursor.getString(cursor.getColumnIndex(Defs.COLUMN_CODE))); currency.setRatio(cursor.getInt(cursor.getColumnIndex(Defs.COLUMN_RATIO))); currency.setReverseRate(cursor.getFloat(cursor.getColumnIndex(Defs.COLUMN_REVERSERATE))); currency.setRate(cursor.getFloat(cursor.getColumnIndex(Defs.COLUMN_RATE))); currency.setExtraInfo(cursor.getString(cursor.getColumnIndex(Defs.COLUMN_EXTRAINFO))); try { currency.setCurrDate( parseStringToDate(cursor.getString(cursor.getColumnIndex(Defs.COLUMN_CURR_DATE)), "yyyy-MM-dd")); } catch (ParseException e) { e.printStackTrace(); } currency.setTitle(cursor.getString(cursor.getColumnIndex(Defs.COLUMN_TITLE))); currency.setfStar(cursor.getInt(cursor.getColumnIndex(Defs.COLUMN_F_STAR))); return currency; } }
package orca.nodeagent2.oscarslib.driver; import java.util.Date; import java.util.List; import java.util.concurrent.locks.ReentrantLock; import net.es.oscars.api.soap.gen.v06.CancelResContent; import net.es.oscars.api.soap.gen.v06.CancelResReply; import net.es.oscars.api.soap.gen.v06.CreatePathContent; import net.es.oscars.api.soap.gen.v06.CreatePathResponseContent; import net.es.oscars.api.soap.gen.v06.CreateReply; import net.es.oscars.api.soap.gen.v06.Layer2Info; import net.es.oscars.api.soap.gen.v06.ListReply; import net.es.oscars.api.soap.gen.v06.ListRequest; import net.es.oscars.api.soap.gen.v06.ModifyResContent; import net.es.oscars.api.soap.gen.v06.ModifyResReply; import net.es.oscars.api.soap.gen.v06.OSCARS; import net.es.oscars.api.soap.gen.v06.PathInfo; import net.es.oscars.api.soap.gen.v06.QueryResContent; import net.es.oscars.api.soap.gen.v06.QueryResReply; import net.es.oscars.api.soap.gen.v06.ResCreateContent; import net.es.oscars.api.soap.gen.v06.ResDetails; import net.es.oscars.api.soap.gen.v06.TeardownPathContent; import net.es.oscars.api.soap.gen.v06.TeardownPathResponseContent; import net.es.oscars.api.soap.gen.v06.UserRequestConstraintType; import net.es.oscars.api.soap.gen.v06.VlanTag; import net.es.oscars.common.soap.gen.OSCARSFaultMessage; import net.es.oscars.common.soap.gen.OSCARSFaultReport; /** * createReservationPoll creates a reservation for the path and polls for success or failure. * Path is provisioned when start time arrives, unless * pathSetupMode field in the createReservtion message set to to signal-xml. Then need to use createPath call to * activate provisioning * * createPath() and teardownPath() can be used to provision/unprovision the path (only if signal-xml option is set * on reservation) * * cancelReservation() cancels the reservation and tears down path if provisioned. * * @author ibaldin * */ public class Driver { private OSCARS client = null; private String serverUrl = null; private String keyAlias = null; private ReentrantLock fairLock = new ReentrantLock(true); public Driver(String url, String certFile, String keyFile, String alias, String passWord, boolean logging) { String serviceUrl = url; ClientConfigHolder cch = ClientConfigHolder.getInstance(); ClientConfig cc = new ClientConfig(); cc.setKeyPassword(passWord); cch.addClientConfig(serviceUrl, cc); cch.setActiveClientConfig(serviceUrl); client = ClientUtil.getInstance().getOSCARSPort(serviceUrl, certFile, keyFile, alias, passWord, logging); } /** * Get OSCARS reservations * @return * @throws OSCARSFaultMessage * @throws OSCARSClientException * @throws Exception */ public List<ResDetails> getReservations() throws OSCARSFaultMessage, Exception { //Build request that asks for all ACTIVE, RESERVED and FINISHED reservations ListRequest request = new ListRequest(); request.getResStatus().add(ResvStatus.STATUS_ACTIVE); request.getResStatus().add(ResvStatus.STATUS_RESERVED); request.getResStatus().add(ResvStatus.STATUS_FINISHED); request.getResStatus().add(ResvStatus.STATUS_FAILED); request.getResStatus().add(ResvStatus.STATUS_CANCELLED); //send request ListReply reply = client.listReservations(request); return reply.getResDetails(); } /** * List the desired states of interest. Dangerous function because these are just strings, * no easy way to test what is allowed. * @param states * @return * @throws OSCARSFaultMessage * @throws Exception */ public List<ResDetails> getReservations(String ... states) throws OSCARSFaultMessage, Exception { ListRequest request = new ListRequest(); for(String s: states) { if (s != null) request.getResStatus().add(s); } //send request ListReply reply = client.listReservations(request); return reply.getResDetails(); } /** * List only active reservations * @return * @throws OSCARSFaultMessage * @throws OSCARSClientException * @throws Exception */ public List<ResDetails> getActiveReservations() throws OSCARSFaultMessage, Exception { //Build request that asks for all ACTIVE, RESERVED and FINISHED reservations ListRequest request = new ListRequest(); request.getResStatus().add(ResvStatus.STATUS_ACTIVE); //send request ListReply reply = client.listReservations(request); return reply.getResDetails(); } /** * Get details of the reservation * @param gri * @return * @throws OSCARSFaultMessage * @throws OSCARSClientException * @throws Exception */ public ResDetails queryReservation(String gri) throws OSCARSFaultMessage, Exception { QueryResContent queryRequest = new QueryResContent(); queryRequest.setGlobalReservationId(gri); QueryResReply queryResponse = client.queryReservation(queryRequest); ResDetails rd = queryResponse.getReservationDetails(); return rd; } /** * Create a reservation for a path between A and Z with specific tags * * @param desc - description * @param start - start date * @param end - end date * @param bw - bandwidth in Mbps * @param pointA - interface urn * @param tagA - vlan tag * @param pointZ - interface urn * @param tagZ - vlan tag * @param pollInterval - poll interval in seconds * @throws OSCARSFaultMessage * @throws OSCARSClientException * @throws Exception */ public String createReservationPoll(String desc, Date start, Date end, int bw, String pointA, int tagA, String pointZ, int tagZ, int pollInterval) throws OSCARSFaultMessage, Exception { ResCreateContent request = new ResCreateContent(); request.setDescription(desc); UserRequestConstraintType userConstraint = new UserRequestConstraintType(); if (end.getTime() <= start.getTime()) throw new Exception("End date before start date in creating OSCARS reservation"); userConstraint.setStartTime(start.getTime()/1000); userConstraint.setEndTime(end.getTime()/1000); if (bw > 0) userConstraint.setBandwidth(bw); PathInfo pathInfo = new PathInfo(); Layer2Info layer2Info = new Layer2Info(); // src layer2Info.setSrcEndpoint(pointA); VlanTag vtA = new VlanTag(); vtA.setTagged(true); vtA.setValue(tagA + ""); layer2Info.setSrcVtag(vtA); // dst layer2Info.setDestEndpoint(pointZ); VlanTag vtZ = new VlanTag(); vtZ.setTagged(true); vtZ.setValue(tagZ + ""); layer2Info.setDestVtag(vtZ); pathInfo.setLayer2Info(layer2Info ); userConstraint.setPathInfo(pathInfo); request.setUserRequestConstraint(userConstraint); String gri; //send request fairLock.lock(); try { CreateReply reply = client.createReservation(request); if (!reply.getStatus().equals(ResvStatus.STATUS_OK)) { fairLock.unlock(); throw new Exception("OSCARS returned non-OK status " + reply.getStatus()); } // poll until circuit is ACTIVE String resvStatus = ""; gri = reply.getGlobalReservationId(); while (!resvStatus.equals(ResvStatus.STATUS_ACTIVE)) { //sleep for an interval try { Thread.sleep(pollInterval * 1000); } catch (InterruptedException e) { fairLock.unlock(); throw new Exception("OSCARS reservation query sleep interrupted"); } //send query QueryResContent queryRequest = new QueryResContent(); queryRequest.setGlobalReservationId(gri); QueryResReply queryResponse = client.queryReservation(queryRequest); //check status resvStatus = queryResponse.getReservationDetails().getStatus(); if (resvStatus.equals(ResvStatus.STATUS_FAILED)) { List<OSCARSFaultReport> errors = queryResponse.getErrorReport(); StringBuilder esb = new StringBuilder(); for (OSCARSFaultReport err : errors) { esb.append(err.getErrorMsg()); esb.append(" "); } fairLock.unlock(); throw new Exception("OSCARS reservation query failed with status " + resvStatus + " due to " + esb.toString()); } } } finally { fairLock.unlock(); } return gri; } /** * Create a reservation with unspecified VLAN tags * @param desc * @param start * @param end * @param bw * @param pointA * @param pointZ * @param pollInterval * @throws OSCARSFaultMessage * @throws OSCARSClientException * @throws Exception */ public String createReservationPoll(String desc, Date start, Date end, int bw, String pointA, String pointZ, int pollInterval) throws OSCARSFaultMessage, Exception { if (end.getTime() <= start.getTime()) throw new Exception("End date before start date in creating OSCARS reservation"); ResCreateContent request = new ResCreateContent(); request.setDescription(desc); UserRequestConstraintType userConstraint = new UserRequestConstraintType(); userConstraint.setStartTime(start.getTime()/1000); userConstraint.setEndTime(end.getTime()/1000); userConstraint.setBandwidth(bw); PathInfo pathInfo = new PathInfo(); Layer2Info layer2Info = new Layer2Info(); // src layer2Info.setSrcEndpoint(pointA); // dst layer2Info.setDestEndpoint(pointZ); pathInfo.setLayer2Info(layer2Info ); userConstraint.setPathInfo(pathInfo); request.setUserRequestConstraint(userConstraint); String gri; //send request fairLock.lock(); try { CreateReply reply = client.createReservation(request); if (!reply.getStatus().equals(ResvStatus.STATUS_OK)) { fairLock.unlock(); throw new Exception("OSCARS returned non-OK status " + reply.getStatus()); } // poll until circuit is ACTIVE String resvStatus = ""; gri = reply.getGlobalReservationId(); while (!resvStatus.equals(ResvStatus.STATUS_ACTIVE)) { //sleep for an interval try { Thread.sleep(pollInterval * 1000); } catch (InterruptedException e) { fairLock.unlock(); throw new Exception("Sleep interrupted"); } //send query QueryResContent queryRequest = new QueryResContent(); queryRequest.setGlobalReservationId(gri); QueryResReply queryResponse = client.queryReservation(queryRequest); //check status resvStatus = queryResponse.getReservationDetails().getStatus(); if (resvStatus.equals(ResvStatus.STATUS_FAILED)) { List<OSCARSFaultReport> errors = queryResponse.getErrorReport(); StringBuilder esb = new StringBuilder(); for (OSCARSFaultReport err : errors) { esb.append(err.getErrorMsg()); esb.append(" "); } fairLock.unlock(); throw new Exception("OSCARS reservation failed with status " + resvStatus + " due to " + esb.toString()); } } } finally { fairLock.unlock(); } return gri; } /** * Modify the end date of the reservation * @param gri * @param newDate * @param pollInterval * @throws OSCARSFaultMessage * @throws OSCARSClientException * @throws Exception */ public void extendReservation(String gri, Date newEnd, int pollInterval) throws OSCARSFaultMessage, Exception { Date now = new Date(); if (newEnd.getTime() <= now.getTime()) throw new Exception("Extend date before current date in extending OSCARS reservation"); //create modify request ModifyResContent request = new ModifyResContent(); request.setGlobalReservationId(gri); UserRequestConstraintType userConstraint = new UserRequestConstraintType(); userConstraint.setEndTime(newEnd.getTime()/1000); request.setUserRequestConstraint(userConstraint); //send modify request fairLock.lock(); try { ModifyResReply response = client.modifyReservation(request); // poll until circuit is ACTIVE String resvStatus = ""; while (!resvStatus.equals(ResvStatus.STATUS_ACTIVE)) { //sleep for an interval try { Thread.sleep(pollInterval * 1000); } catch (InterruptedException e) { fairLock.unlock(); throw new Exception("Sleep interrupted"); } //send query QueryResContent queryRequest = new QueryResContent(); queryRequest.setGlobalReservationId(gri); QueryResReply queryResponse = client.queryReservation(queryRequest); //check status resvStatus = queryResponse.getReservationDetails().getStatus(); if (resvStatus.equals(ResvStatus.STATUS_FAILED)) { List<OSCARSFaultReport> errors = queryResponse.getErrorReport(); StringBuilder esb = new StringBuilder(); for (OSCARSFaultReport err : errors) { esb.append(err.getErrorMsg()); esb.append(" "); } fairLock.unlock(); throw new Exception("OSCARS extend for " + gri + " failed with status " + resvStatus + " due to " + esb.toString()); } } } finally { fairLock.unlock(); } } /** * Provision a path in existing reservation * @param gri * @param pollInterval * @throws OSCARSFaultMessage * @throws OSCARSClientException * @throws Exception */ public void createPath(String gri, int pollInterval) throws OSCARSFaultMessage, Exception { //create request CreatePathContent request = new CreatePathContent(); request.setGlobalReservationId(gri); String resvStatus = ""; fairLock.lock(); try { CreatePathResponseContent response = client.createPath(request); //display result if (!ResvStatus.STATUS_OK.equals(response.getStatus())) { fairLock.unlock(); throw new Exception("The create request for " + gri + " returned status " + response.getStatus()); } //poll until reservation is setup while (resvStatus.equals(ResvStatus.STATUS_INSETUP)) { //send query QueryResContent queryRequest = new QueryResContent(); queryRequest.setGlobalReservationId(gri); QueryResReply queryResponse = client.queryReservation(queryRequest); resvStatus = queryResponse.getReservationDetails().getStatus(); try { Thread.sleep(pollInterval * 1000); } catch (InterruptedException e) { fairLock.unlock(); throw new Exception("Sleep interrupted"); } } } finally { fairLock.unlock(); } if (ResvStatus.STATUS_ACTIVE.equals(resvStatus)){ return; }else{ throw new Exception("Creat path of gri " + gri + " failed"); } } /** * Teardown a previously established path * @param gri * @param pollInterval * @throws OSCARSFaultMessage * @throws OSCARSClientException * @throws Exception */ public void teardownPath(String gri, int pollInterval) throws OSCARSFaultMessage, Exception { //create request TeardownPathContent request = new TeardownPathContent(); request.setGlobalReservationId(gri); String resvStatus = ""; fairLock.lock(); try { TeardownPathResponseContent response = client.teardownPath(request); //display result if (!ResvStatus.STATUS_OK.equals(response.getStatus())) { fairLock.unlock(); throw new Exception("The teardown request for " + gri + " returned status " + response.getStatus()); } //poll until reservation is down while (resvStatus.equals(ResvStatus.STATUS_INTEARDOWN)) { //send query QueryResContent queryRequest = new QueryResContent(); queryRequest.setGlobalReservationId(gri); QueryResReply queryResponse = client.queryReservation(queryRequest); resvStatus = queryResponse.getReservationDetails().getStatus(); try { Thread.sleep(pollInterval * 1000); } catch (InterruptedException e) { fairLock.unlock(); throw new Exception("Sleep interrupted"); } } } finally { fairLock.unlock(); } if(ResvStatus.STATUS_RESERVED.equals(resvStatus) || ResvStatus.STATUS_FINISHED.equals(resvStatus)) { return; } else { throw new Exception("Teardown of gri " + gri + " failed"); } } public void cancelReservation(String gri, int pollInterval) throws OSCARSFaultMessage, Exception { //create cancel request CancelResContent request = new CancelResContent(); request.setGlobalReservationId(gri); String resvStatus = ""; //send cancel request fairLock.lock(); try { CancelResReply response = client.cancelReservation(request); //display result if (!ResvStatus.STATUS_OK.equals(response.getStatus())) { fairLock.unlock(); throw new Exception("The cancel request for " + gri + " returned status " + response.getStatus()); } //poll until reservation is canceled while (resvStatus.equals(ResvStatus.STATUS_ACTIVE) || resvStatus.equals(ResvStatus.STATUS_INCANCEL) || (resvStatus.length() == 0)) { try { Thread.sleep(pollInterval * 1000); } catch (InterruptedException e) { fairLock.unlock(); throw new Exception("Sleep interrupted"); } //send query QueryResContent queryRequest = new QueryResContent(); queryRequest.setGlobalReservationId(gri); QueryResReply queryResponse = client.queryReservation(queryRequest); resvStatus = queryResponse.getReservationDetails().getStatus(); } } finally { fairLock.unlock(); } if (ResvStatus.STATUS_CANCELLED.equals(resvStatus)) { return; } else { throw new Exception("Cancel of gri " + gri + " failed " + resvStatus); } } /** * Query and print * @param activeOnly * @return */ public String printReservations(boolean activeOnly) { try { List<ResDetails> ret; if (activeOnly) ret = getActiveReservations(); else ret = getReservations(); return printReservations(ret); } catch (OSCARSFaultMessage ofm) { return "OSCARS Fault Message: " + ofm.getMessage(); } catch (Exception e) { e.printStackTrace(); return "Generic exception: " + e.getMessage(); } } /** * Print results of prior query * @param l * @param activeOnly * @return */ public String printReservations(List<ResDetails> l) { if ((l == null) || (l.size() == 0)) { return "No reservations were returnd by " + serverUrl + " for key alias " + keyAlias; } StringBuilder resp = new StringBuilder(); for (ResDetails r: l) { resp.append(detailsToString(r)); resp.append("\n"); } return resp.toString(); } /** * Scan the list of reservations to see if a circuit between two given endpoints is present, returning the GRI. * Parameters are expected to be non-null * @param l * @param epA * @param epZ * @param tagA * @param tagZ * @return */ public String findActiveReservation(List<ResDetails> l, String epA, String epZ, String tagA, String tagZ) { if ((l == null) || (l.size() == 0)) { return null; } for(ResDetails r: l) { UserRequestConstraintType urc = r.getUserRequestConstraint(); if (urc == null) continue; PathInfo pi = urc.getPathInfo(); if (pi == null) continue; Layer2Info l2i = pi.getLayer2Info(); if (l2i == null) continue; String rEpA = l2i.getSrcEndpoint(); String rEpZ = l2i.getDestEndpoint(); VlanTag rTagA = l2i.getSrcVtag(); VlanTag rTagZ = l2i.getDestVtag(); if ((rTagA == null) || (rTagZ == null)) continue; if ((epA != null) && (epA.equals(rEpA))) { if ((epZ != null) && (epZ.equals(rEpZ))) { if ((tagA != null) && (tagA.equals(rTagA.getValue()))) { if ((tagZ != null) && (tagZ.equals(rTagZ.getValue()))) { return r.getGlobalReservationId(); } } } } } return null; } /** * Query for active and try to locate a matching reservation returning the GRI. If not found or exceptions * encountered, returns null * @param activeOnly * @param epA * @param epZ * @param tagA * @param tagZ * @return * @throws OSCARSFaultMessage * @throws Exception */ public String findActiveReservation(boolean activeOnly, String epA, String epZ, String tagA, String tagZ) throws OSCARSFaultMessage, Exception { try { List<ResDetails> ret; if (activeOnly) ret = getActiveReservations(); else ret = getReservations(); return findActiveReservation(ret, epA, epZ, tagA, tagZ); } catch (OSCARSFaultMessage ofm) { return null; } catch (Exception e) { e.printStackTrace(); return null; } } private static String detailsToString(ResDetails d) { StringBuilder sb = new StringBuilder(); sb.append(d.getGlobalReservationId() + "\t"); sb.append(d.getLogin() + "\t"); sb.append(d.getStatus() + "\t"); sb.append(new Date(d.getUserRequestConstraint().getStartTime()*1000L) + "\t"); sb.append(new Date(d.getUserRequestConstraint().getEndTime()*1000L) + "\t"); sb.append(d.getUserRequestConstraint().getBandwidth() + "Mbps"); return sb.toString(); } public static void main(String[] argv) { //Driver d = new Driver(OSCARS_URL, OSCARS_CERT_FILE, OSCARS_KEYSTORE_FILE, OSCARS_KEY_ALIAS, PASSWORD, true); //System.out.println(d.printReservations(false)); System.out.println(new Date(1447092034*1000L)); System.out.println(new Date().getTime()); } }
package org.apdplat.superword.rule; import org.apdplat.superword.model.Word; import org.apdplat.superword.tools.HtmlFormatter; import org.apdplat.superword.tools.WordSources; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; /** * 22 * @author */ public class CompoundWord { private CompoundWord(){} public static Map<Word, Map<Integer, List<Word>>> find(Set<Word> words){ return find(words, words); } public static Map<Word, Map<Integer, List<Word>>> find(Set<Word> words, Set<Word> target){ Map<Word, Map<Integer, List<Word>>> data = new HashMap<>(); target.forEach(word -> { Map<Integer, List<Word>> compound = find(words, word); if(!compound.isEmpty()) { data.put(word, compound); } }); return data; } public static Map<Integer, List<Word>> find(Set<Word> words, String word){ return find(words, new Word(word, "")); } public static Map<Integer, List<Word>> find(Set<Word> words, Word word){ Map<Integer, List<Word>> data = new HashMap<>(); String w = word.getWord(); for(int i=1; i<w.length(); i++){ check(w, i, data, words); } return data; } private static void check(String word, int position, Map<Integer, List<Word>> data, Set<Word> words){ if(position < 3 || word.length() - position < 3){ return; } String one = word.substring(0, position); String two = word.substring(position, word.length()); if(words.contains(new Word(one, "")) && words.contains(new Word(two, ""))){ data.put(position, new ArrayList<>()); data.get(position).add(new Word(one, "")); data.get(position).add(new Word(two, "")); } } public static void main(String[] args) throws Exception { Set<Word> words = WordSources.getSyllabusVocabulary(); //Set<Word> target = new HashSet<>(); //target.add(new Word("pendent", "")); //target.add(new Word("abhorrent", "")); Set<Word> target = WordSources.getSyllabusVocabulary(); Map<Word, Map<Integer, List<Word>>> data = CompoundWord.find(words, target); String htmlFragment = HtmlFormatter.toHtmlForCompoundWord(data, 5); Files.write(Paths.get("src/main/resources/compound_word.txt"), htmlFragment.getBytes("utf-8")); System.out.println(htmlFragment); } }
package org.commonmark.internal; import org.commonmark.internal.util.Parsing; import org.commonmark.node.Block; import org.commonmark.node.Node; import org.commonmark.node.Paragraph; import org.commonmark.node.SourcePosition; public class ParagraphParser extends AbstractBlockParser { private final Paragraph block = new Paragraph(); // TODO: Can this be inlined? private BlockContent content = new BlockContent(); public ParagraphParser(SourcePosition pos) { block.setSourcePosition(pos); } @Override public ContinueResult continueBlock(String line, int nextNonSpace, int offset, boolean blank) { if (!blank) { return blockMatched(offset); } else { return blockDidNotMatch(); } } @Override public boolean acceptsLine() { return true; } @Override public void addLine(String line) { content.add(line); } @Override public void finalizeBlock(InlineParser inlineParser) { int pos; String contentString = content.getString(); // try parsing the beginning as link reference definitions: while (contentString.charAt(0) == '[' && (pos = inlineParser.parseReference(contentString)) != 0) { contentString = contentString.substring(pos); if (Parsing.isBlank(contentString)) { block.unlink(); break; } } content = new BlockContent(contentString); } @Override public void processInlines(InlineParser inlineParser) { inlineParser.parse(block, content.getString()); } @Override public boolean canContain(Block block) { return false; } @Override public boolean shouldTryBlockStarts() { return true; } @Override public Block getBlock() { return block; } public boolean hasSingleLine() { return content.hasSingleLine(); } public boolean hasLines() { return content.hasLines(); } public String getContentString() { return content.getString(); } }
package org.dannil.simpletexteditor.event; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ResourceBundle; import org.dannil.simpletexteditor.utility.LanguageUtility; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Shell; public class Event { private final String[] FILTER_NAMES = { "Text (*.txt)", "HTML (*.html, *.xhtml)" }; private final String[] FILTER_EXT = { "*.txt", "*.html;*.xhtml"/*"*.doc", ".rtf", "*.*"*/ }; ResourceBundle languageBundle; public Event() { this.languageBundle = LanguageUtility.getDefault(); } public String openFile(Shell shell) throws IOException { FileDialog fd = new FileDialog(shell, SWT.OPEN); fd.setText(this.languageBundle.getString("open.file")); fd.setFilterPath("C:/"); fd.setFilterNames(this.FILTER_NAMES); fd.setFilterExtensions(this.FILTER_EXT); String path = fd.open(); if (path != null) { File file = new File(path); BufferedReader br = new BufferedReader(new FileReader(file)); String content = ""; String line = null; while ((line = br.readLine()) != null) { content += line; content += System.getProperty("line.separator"); } br.close(); return content; } return ""; //System.out.println("File non-existant."); //return ""; } }
package org.embulk.output.solr; import java.io.IOException; import java.util.Date; import java.util.LinkedList; import java.util.List; import com.google.common.base.Throwables; import com.google.inject.Inject; import org.embulk.config.TaskReport; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.common.SolrInputDocument; import org.embulk.config.Config; import org.embulk.config.ConfigDefault; import org.embulk.config.ConfigDiff; import org.embulk.config.ConfigSource; import org.embulk.config.Task; import org.embulk.config.TaskSource; import org.embulk.spi.Column; import org.embulk.spi.ColumnVisitor; import org.embulk.spi.Exec; import org.embulk.spi.OutputPlugin; import org.embulk.spi.Page; import org.embulk.spi.PageReader; import org.embulk.spi.Schema; import org.embulk.spi.TransactionalPageOutput; import org.embulk.spi.time.Timestamp; import org.msgpack.value.Value; import org.slf4j.Logger; public class SolrOutputPlugin implements OutputPlugin { public interface PluginTask extends Task { @Config("host") public String getHost(); @Config("port") @ConfigDefault("8983") public int getPort(); @Config("collection") public String getCollection(); @Config("maxRetry") @ConfigDefault("5") public int getMaxRetry(); @Config("bulkSize") @ConfigDefault("1000") public int getBulkSize(); } private final Logger logger; @Inject public SolrOutputPlugin() { logger = Exec.getLogger(getClass()); } @Override public ConfigDiff transaction(ConfigSource config, Schema schema, int taskCount, OutputPlugin.Control control) { PluginTask task = config.loadConfig(PluginTask.class); control.run(task.dump()); return Exec.newConfigDiff(); } @Override public ConfigDiff resume(TaskSource taskSource, Schema schema, int taskCount, OutputPlugin.Control control) { // TODO return Exec.newConfigDiff(); } @Override public void cleanup(TaskSource taskSource, Schema schema, int taskCount, List<TaskReport> successTaskReports) { } @Override public TransactionalPageOutput open(TaskSource taskSource, Schema schema, int taskIndex) { PluginTask task = taskSource.loadTask(PluginTask.class); SolrClient client = createSolrClient(task); TransactionalPageOutput pageOutput = new SolrPageOutput(client, schema, task); return pageOutput; } /** * create Solr Client. <br> * this method has not been supporting SolrCloud client using zookeeper * Host, yet. * * @param task * @return SolrClient instance. */ private SolrClient createSolrClient(PluginTask task) { HttpSolrClient solr = new HttpSolrClient( "http://" + task.getHost() + ":" + task.getPort() + "/solr/" + task.getCollection()); solr.setConnectionTimeout(10000); // 10 seconds for timeout. return solr; } public static class SolrPageOutput implements TransactionalPageOutput { private Logger logger; private SolrClient client; private final PageReader pageReader; private final Schema schema; private PluginTask task; private final int bulkSize; private final int maxRetry; List<SolrInputDocument> documentList = new LinkedList<SolrInputDocument>(); public SolrPageOutput(SolrClient client, Schema schema, PluginTask task) { this.logger = Exec.getLogger(getClass()); this.client = client; this.pageReader = new PageReader(schema); this.schema = schema; this.task = task; this.bulkSize = task.getBulkSize(); this.maxRetry = task.getMaxRetry(); } @Override public void add(Page page) { logger.info("start sending document to Solr."); int totalCount = 0; pageReader.setPage(page); while (pageReader.nextRecord()) { final SolrInputDocument doc = new SolrInputDocument(); totalCount ++; schema.visitColumns(new ColumnVisitor() { @Override public void booleanColumn(Column column) { if (pageReader.isNull(column)) { // do nothing. } else { boolean value = pageReader.getBoolean(column); doc.addField(column.getName(), value); } } @Override public void longColumn(Column column) { if (pageReader.isNull(column)) { // do nothing. } else { long value = pageReader.getLong(column); doc.addField(column.getName(), value); } } @Override public void doubleColumn(Column column) { if (pageReader.isNull(column)) { // do nothing. } else { double value = pageReader.getDouble(column); doc.addField(column.getName(), value); } } @Override public void stringColumn(Column column) { if (pageReader.isNull(column)) { // do nothing. } else { String value = pageReader.getString(column); doc.addField(column.getName(), value); } } @Override public void timestampColumn(Column column) { if (pageReader.isNull(column)) { // do nothing. } else { Timestamp value = pageReader.getTimestamp(column); Date dateValue = new Date(value.getEpochSecond() * 1000); doc.addField(column.getName(), dateValue); } } @Override public void jsonColumn(Column column) { if (pageReader.isNull(column)) { // do nothing. } else { Value value = pageReader.getJson(column); // send json as a string. doc.addField(column.getName(), value.toString()); } } }); documentList.add(doc); if (documentList.size() >= bulkSize) { sendDocumentToSolr(); } } logger.info("Done sending document to Solr ! total count : " + totalCount); } private void sendDocumentToSolr() { int retrycount = 0; while(true) { try { client.add(documentList); client.commit(); logger.info("success fully load a bunch of documents to solr. batch count : " + documentList.size()); documentList.clear(); // when successfully add and commit, clear list. break; } catch (SolrServerException | IOException e) { if (retrycount < maxRetry) { retrycount++; logger.debug("RETRYing : " + retrycount); continue; } else { logger.error("failed to send document to solr. ", e); Throwables.propagate(e); // TODO error handling documentList.clear(); break; } } } } @Override public void finish() { // send rest of all documents. sendDocumentToSolr(); } @Override public void close() { try { client.close(); client = null; } catch (IOException e) { Throwables.propagate(e); // TODO error handling } } @Override public void abort() { } @Override public TaskReport commit() { TaskReport report = Exec.newTaskReport(); return report; } } }
package org.ihtsdo.snomed.util.mrcm; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.ihtsdo.snomed.util.pojo.Concept; import org.ihtsdo.snomed.util.pojo.GroupShape; import org.ihtsdo.snomed.util.pojo.Relationship; import org.ihtsdo.snomed.util.pojo.RelationshipGroup; import org.ihtsdo.snomed.util.rf2.GraphLoader; import org.ihtsdo.snomed.util.rf2.schema.RF2SchemaConstants.CHARACTERISTIC; import org.ihtsdo.util.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Sets; public class MrcmBuilder { private static final Logger LOGGER = LoggerFactory.getLogger(GraphLoader.class); public static int mb = 1024 * 1024; private static void doHelp() { LOGGER.info("Usage: <concept file location> <stated relationship file location> <inferred realtionship file location>"); System.exit(-1); } public static void main(String[] args) throws Exception { if (args.length < 2) { doHelp(); } reportMemory(); GraphLoader g = new GraphLoader(args[0], args[1], args[2]); g.loadRelationships(); reportMemory(); // long conceptToExamine = 128927009L; // Procedure by Method long conceptToExamine = 362958002L; // Procedure by Site // long conceptToExamine = 285579008L; //Taking swab from body site CHARACTERISTIC hierarchyToExamine = CHARACTERISTIC.INFERRED; // CHARACTERISTIC hierarchyToExamine = CHARACTERISTIC.STATED; LOGGER.info("Examining Siblings of {} in the {} hierarchy to Determine MRCM Rules...", conceptToExamine, hierarchyToExamine); // Lets start with children of "Procedure by site" Concept c = Concept.getConcept(conceptToExamine, hierarchyToExamine); determineMRCM(c); } private static void determineMRCM(Concept c) throws UnsupportedEncodingException { Set<Concept> siblings = c.getChildren(); Set<Concept> definedSiblings = c.getFullyDefinedChildren(); LOGGER.info("Examining {} fully defined out of {} children of {}", definedSiblings.size(), siblings.size(), c.getSctId()); final ConcurrentMap<String, AtomicInteger> shapePopularity = new ConcurrentHashMap<String, AtomicInteger>(); final ConcurrentMap<String, AtomicInteger> groupsHashPopularity = new ConcurrentHashMap<String, AtomicInteger>(); for (Concept sibling : definedSiblings) { List<RelationshipGroup> groups = sibling.getGroups(); for (RelationshipGroup g : groups) { String groupShape = g.getGroupShape(); LOGGER.info("{}:{} - {} ", sibling.getSctId(), g.getNumber(), groupShape); shapePopularity.putIfAbsent(groupShape, new AtomicInteger(0)); shapePopularity.get(groupShape).incrementAndGet(); } String groupsShapeHash = sibling.getGroupsShapeHash().toString(); LOGGER.info(" Groups Shape: {}", groupsShapeHash); groupsHashPopularity.putIfAbsent(groupsShapeHash, new AtomicInteger(0)); groupsHashPopularity.get(groupsShapeHash).incrementAndGet(); } LOGGER.info("Shape Popularity:"); CollectionUtils.printSortedMap(shapePopularity); LOGGER.info("Groups Hash Popularity:"); CollectionUtils.printSortedMap(groupsHashPopularity); // Now loop through groups again and see if we can find a better shape by working // with the abstract types (ie the parent of the type) // Calculate a new popularity Map shapePopularity.clear(); for (Concept sibling : definedSiblings) { List<RelationshipGroup> groups = sibling.getGroups(); for (RelationshipGroup g : groups) { String preferredShapeId = g.getGroupShape(); Set<Integer> preferredAbstractCombination = null; // Loop through all the combinations of attributes to express as type ancestors Set<Set<Integer>> allCombinations = CollectionUtils.getIndexCombinations(g.size()); for (Set<Integer> thisCombination : allCombinations) { // Skip the empty set ie no abstractions if (thisCombination.size() == 0) { continue; } String groupAbstractShape = g.getGroupAbstractShape(thisCombination); // If ANY sibling already uses the more abstract model, then that's preferable to have in common if (shapePopularity.containsKey(groupAbstractShape)) { LOGGER.info("Abstract Group Shape better for {}: {} (was {})", sibling.getSctId(), groupAbstractShape, g.getGroupShape()); preferredShapeId = groupAbstractShape; preferredAbstractCombination = thisCombination; } } // Also put the original shape (which might remain zero popular) so we can compare it later shapePopularity.putIfAbsent(g.getGroupShape(), new AtomicInteger(0)); shapePopularity.putIfAbsent(preferredShapeId, new AtomicInteger(0)); int newPopularity = shapePopularity.get(preferredShapeId).incrementAndGet(); GroupShape preferredShape = new GroupShape(preferredShapeId, null, preferredAbstractCombination, newPopularity); g.setMostPopularShape(preferredShape); } } LOGGER.info("Shape Popularity after considering Abstract Shape:"); CollectionUtils.printSortedMap(shapePopularity); // Now loop through groups again and see if we can find a more popular shape by working // with partial group matches for (Concept sibling : definedSiblings) { List<RelationshipGroup> groups = sibling.getGroups(); for (RelationshipGroup g : groups) { // Loop through all the combinations of attributes Set<Set<Integer>> allCombinations = CollectionUtils.getIndexCombinations(g.size()); for (Set<Integer> thisCombination : allCombinations) { // Skip the empty set ie no attributes in group if (thisCombination.size() == 0) { continue; } String groupPartialShape = g.getGroupPartialShape(thisCombination); // If ANY sibling already uses the more abstract model, then that's preferable to have in common if (shapePopularity.containsKey(groupPartialShape) && shapePopularity.get(groupPartialShape).get() > shapePopularity.get(g.getGroupShape()).get()) { LOGGER.info("Partial Group Shape more popular for {}: {} (was {})", sibling.getSctId(), groupPartialShape, g.getGroupShape()); } } } } // Do both and try to find a more popular partial group abstract shape findPartialGroupAbstractShapes(definedSiblings, shapePopularity); } private static void findPartialGroupAbstractShapes(Set<Concept> definedSiblings, ConcurrentMap<String, AtomicInteger> shapePopularity) throws UnsupportedEncodingException { for (Concept sibling : definedSiblings) { List<RelationshipGroup> groups = sibling.getGroups(); for (RelationshipGroup g : groups) { // Loop through all the combinations of attributes Set<Set<Integer>> allAttributeCombinations = CollectionUtils.getIndexCombinations(g.size()); for (Set<Integer> thisAttributeCombination : allAttributeCombinations) { // Skip the empty set ie no attributes in group if (thisAttributeCombination.size() == 0) { continue; } // And also work through all combinations of using the more abstract relationship type Set<Set<Integer>> allAbstractCombinations = Sets.powerSet(thisAttributeCombination); for (Set<Integer> thisAbstractCombination : allAbstractCombinations) { // Skip the empty set ie no attributes replaced with more abstract types if (thisAbstractCombination.size() == 0) { continue; } String groupPartialAbstractShape = g .getGroupPartialAbstractShape(thisAttributeCombination, thisAbstractCombination); // If ANY sibling already uses the more abstract model, then that's preferable to have in common if (shapePopularity.containsKey(groupPartialAbstractShape) && shapePopularity.get(groupPartialAbstractShape).get() > shapePopularity.get(g.getGroupShape()).get()) { LOGGER.info("Partial Group Abstract Shape more popular for {}: {} (was {})", sibling.getSctId(), groupPartialAbstractShape, g.getGroupShape()); } } } } } } private static void reportMemory() { Runtime runtime = Runtime.getRuntime(); LOGGER.info("Used Memory: {} Mb", (runtime.totalMemory() - runtime.freeMemory()) / mb); LOGGER.info("Free Memory: {} Mb", runtime.freeMemory() / mb); } }
package org.lightmare.jpa.datasource; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.ObjectUtils; /** * Configuration with default parameters for c3p0 connection pooling * * @author levan * */ public class PoolConfig { public static enum DefaultConfig { // Data source name property DATA_SOURCE_NAME("dataSourceName"), // Class loader properties CONTEXT_CLASS_LOADER_SOURCE("contextClassLoaderSource", "library"), // loader PRIVILEGED_SPAWNED_THREADS("privilegeSpawnedThreads", "true"), // threads // Pool properties MAX_POOL_SIZE("maxPoolSize", "15"), // max pool size INITIAL_POOL_SIZE("initialPoolSize", "5"), // initial MIN_POOL_SIZE("minPoolSize", "5"), // min pool size MAX_STATEMENTS("maxStatements", "50"), // statements AQUIRE_INCREMENT("acquireIncrement", "5"), // increment // Pool timeout properties MAX_IDLE_TIMEOUT("maxIdleTime", "10000"), // idle MAX_IDLE_TIME_EXCESS_CONN("maxIdleTimeExcessConnections", "0"), // excess CHECK_OUT_TIMEOUT("checkoutTimeout", "1800"), // checkout // Controller properties STAT_CACHE_NUM_DEFF_THREADS("statementCacheNumDeferredCloseThreads", "1"), // Transaction properties AUTOCOMMIT("autoCommit", "false"), // auto commit AUTOCOMMIT_ON_CLOSE("autoCommitOnClose", "false"), // on close URESOLVED_TRANSACTIONS("forceIgnoreUnresolvedTransactions", "true"), // ignore // Connection recovery properties ACQUIRE_RETRY_ATTEMPTS("acquireRetryAttempts", "0"), // retry ACQUIRE_RETRY_DELAY("acquireRetryDelay", "1000"), // delay BREACK_AFTER_ACQUIRE_FAILURE("breakAfterAcquireFailure", "false");// break public String key; public String value; private DefaultConfig(String key) { this.key = key; } private DefaultConfig(String key, Object value) { this(key); if (value instanceof String) { this.value = (String) value; } else { this.value = String.valueOf(value); } } } // Data source name property public static final String DATA_SOURCE_NAME = "dataSourceName"; // Default value for data source properties file private static final String POOL_PATH_DEF_VALUE = "META-INF/pool.properties"; private String poolPath; private Map<Object, Object> poolProperties = new HashMap<Object, Object>(); private boolean pooledDataSource; /** * Enumeration to choose which type connection pool should be in use * * @author levan * */ public static enum PoolProviderType { DBCP, C3P0, TOMCAT; } // Default pool provider type private PoolProviderType poolProviderType = PoolProviderType.C3P0; /** * Sets default connection pooling properties * * @return */ public Map<Object, Object> getDefaultPooling() { Map<Object, Object> c3p0Properties = new HashMap<Object, Object>(); DefaultConfig[] defaults = DefaultConfig.values(); String key; String value; for (DefaultConfig config : defaults) { key = config.key; value = config.value; if (ObjectUtils.available(key) && ObjectUtils.available(value)) { c3p0Properties.put(key, value); } } return c3p0Properties; } private Set<Object> unsopportedKeys() throws IOException { Set<Object> keys = new HashSet<Object>(); DataSourceInitializer.ConnectionProperties[] usdKeys = DataSourceInitializer.ConnectionProperties .values(); String key; for (DataSourceInitializer.ConnectionProperties usdKey : usdKeys) { key = usdKey.property; if (ObjectUtils.available(key)) { keys.add(key); } } return keys; } /** * Add initialized properties to defaults * * @param defaults * @param initial */ private void fillDefaults(Map<Object, Object> defaults, Map<Object, Object> initial) { defaults.putAll(initial); } /** * Generates pooling configuration properties * * @param initial * @return {@link Map}<Object, Object> * @throws IOException */ private Map<Object, Object> configProperties(Map<Object, Object> initial) throws IOException { Map<Object, Object> propertiesMap = getDefaultPooling(); fillDefaults(propertiesMap, initial); Set<Object> keys = unsopportedKeys(); String dataSourceName = null; String property; for (Object key : keys) { property = DataSourceInitializer.ConnectionProperties.NAME_PROPERTY.property; if (key.equals(property)) { dataSourceName = (String) propertiesMap.get(property); } propertiesMap.remove(key); } if (ObjectUtils.available(dataSourceName)) { propertiesMap.put(DATA_SOURCE_NAME, dataSourceName); } return propertiesMap; } /** * Gets property as <code>int</int> value * * @param properties * @param key * @return <code>int</code> */ public static Integer asInt(Map<Object, Object> properties, Object key) { Object property = properties.get(key); Integer propertyInt; if (property == null) { propertyInt = null; } else if (property instanceof Integer) { propertyInt = (Integer) property; } else if (property instanceof String) { propertyInt = Integer.valueOf((String) property); } else { propertyInt = null; } return propertyInt; } /** * Gets property as <code>int</int> value * * @param properties * @param key * @return <code>int</code> */ public static Integer asInt(Map<Object, Object> properties, DefaultConfig config) { String key = config.key; Object property = properties.get(key); Integer propertyInt; if (property == null) { propertyInt = null; } else if (property instanceof Integer) { propertyInt = (Integer) property; } else if (property instanceof String) { propertyInt = Integer.valueOf((String) property); } else { propertyInt = null; } return propertyInt; } /** * Loads {@link Properties} from specific path * * @param path * @return {@link Properties} * @throws IOException */ public Map<Object, Object> load() throws IOException { Map<Object, Object> properties; InputStream stream; if (ObjectUtils.notAvailable(poolPath)) { ClassLoader loader = LibraryLoader.getContextClassLoader(); stream = loader.getResourceAsStream(POOL_PATH_DEF_VALUE); } else { File file = new File(poolPath); stream = new FileInputStream(file); } try { Properties propertiesToLoad; if (ObjectUtils.notNull(stream)) { propertiesToLoad = new Properties(); propertiesToLoad.load(stream); properties = new HashMap<Object, Object>(); properties.putAll(propertiesToLoad); } else { properties = null; } } finally { if (ObjectUtils.notNull(stream)) { stream.close(); } } return properties; } /** * Merges passed properties, startup time passed properties and properties * loaded from file * * @param properties * @return {@link Map}<Object, Object> merged properties map * @throws IOException */ public Map<Object, Object> merge(Map<Object, Object> properties) throws IOException { Map<Object, Object> configMap = configProperties(properties); Map<Object, Object> loaded = load(); if (ObjectUtils.notNull(loaded)) { fillDefaults(configMap, loaded); } if (ObjectUtils.notNull(poolProperties)) { fillDefaults(configMap, poolProperties); } return configMap; } public String getPoolPath() { return poolPath; } public void setPoolPath(String poolPath) { this.poolPath = poolPath; } public Map<Object, Object> getPoolProperties() { return poolProperties; } public void setPoolProperties(Map<Object, Object> poolProperties) { this.poolProperties = poolProperties; } public boolean isPooledDataSource() { return pooledDataSource; } public void setPooledDataSource(boolean pooledDataSource) { this.pooledDataSource = pooledDataSource; } public PoolProviderType getPoolProviderType() { return poolProviderType; } public void setPoolProviderType(PoolProviderType poolProviderType) { this.poolProviderType = poolProviderType; } public void setPoolProviderType(String poolProviderTypeName) { this.poolProviderType = PoolProviderType.valueOf(poolProviderTypeName); } }
package org.mitre.synthea.export; import com.google.common.collect.Table; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.nio.file.Path; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.MissingResourceException; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.lang3.StringUtils; import org.mitre.synthea.helpers.Config; import org.mitre.synthea.helpers.RandomNumberGenerator; import org.mitre.synthea.helpers.SimpleCSV; import org.mitre.synthea.helpers.Utilities; import org.mitre.synthea.world.agents.Clinician; import org.mitre.synthea.world.agents.Payer; import org.mitre.synthea.world.agents.Person; import org.mitre.synthea.world.agents.Provider; import org.mitre.synthea.world.agents.Provider.ProviderType; import org.mitre.synthea.world.concepts.Claim.ClaimEntry; import org.mitre.synthea.world.concepts.ClinicianSpecialty; import org.mitre.synthea.world.concepts.HealthRecord; import org.mitre.synthea.world.concepts.HealthRecord.Code; import org.mitre.synthea.world.concepts.HealthRecord.Device; import org.mitre.synthea.world.concepts.HealthRecord.EncounterType; import org.mitre.synthea.world.concepts.HealthRecord.Entry; import org.mitre.synthea.world.concepts.HealthRecord.Medication; public class BB2RIFExporter { private BeneficiaryWriters beneficiaryWriters; private SynchronizedBBLineWriter beneficiaryHistory; private SynchronizedBBLineWriter outpatient; private SynchronizedBBLineWriter inpatient; private SynchronizedBBLineWriter carrier; private SynchronizedBBLineWriter prescription; private SynchronizedBBLineWriter dme; private SynchronizedBBLineWriter home; private SynchronizedBBLineWriter hospice; private SynchronizedBBLineWriter snf; private SynchronizedBBLineWriter npi; private static AtomicLong beneId = new AtomicLong(Config.getAsLong("exporter.bfd.bene_id_start", -1)); private static AtomicLong claimId = new AtomicLong(Config.getAsLong("exporter.bfd.clm_id_start", -1)); private static AtomicInteger claimGroupId = new AtomicInteger(Config.getAsInteger("exporter.bfd.clm_grp_id_start", -1)); private static AtomicLong pdeId = new AtomicLong(Config.getAsLong("exporter.bfd.pde_id_start", -1)); private static AtomicReference<MBI> mbi = new AtomicReference<>(MBI.parse(Config.get("exporter.bfd.mbi_start", "1S00-A00-AA00"))); private static AtomicReference<HICN> hicn = new AtomicReference<>(HICN.parse(Config.get("exporter.bfd.hicn_start", "T00000000A"))); private final CLIA[] cliaLabNumbers; private List<LinkedHashMap<String, String>> carrierLookup; private CodeMapper conditionCodeMapper; private CodeMapper medicationCodeMapper; private CodeMapper drgCodeMapper; private CodeMapper dmeCodeMapper; private CodeMapper hcpcsCodeMapper; private StateCodeMapper locationMapper; private StaticFieldConfig staticFieldConfig; private static final String BB2_BENE_ID = "BB2_BENE_ID"; private static final String BB2_PARTD_CONTRACTS = "BB2_PARTD_CONTRACTS"; private static final String BB2_HIC_ID = "BB2_HIC_ID"; private static final String BB2_MBI = "BB2_MBI"; /** * Day-Month-Year date format. */ private static final SimpleDateFormat BB2_DATE_FORMAT = new SimpleDateFormat("dd-MMM-yyyy"); /** * Get a date string in the format DD-MMM-YY from the given time stamp. */ private static String bb2DateFromTimestamp(long time) { synchronized (BB2_DATE_FORMAT) { return BB2_DATE_FORMAT.format(new Date(time)); } } /** * Create the output folder and files. Write headers to each file. */ private BB2RIFExporter() { cliaLabNumbers = initCliaLabNumbers(); conditionCodeMapper = new CodeMapper("export/condition_code_map.json"); medicationCodeMapper = new CodeMapper("export/medication_code_map.json"); drgCodeMapper = new CodeMapper("export/drg_code_map.json"); dmeCodeMapper = new CodeMapper("export/dme_code_map.json"); hcpcsCodeMapper = new CodeMapper("export/hcpcs_code_map.json"); locationMapper = new StateCodeMapper(); try { String csv = Utilities.readResourceAndStripBOM("payers/carriers.csv"); carrierLookup = SimpleCSV.parse(csv); staticFieldConfig = new StaticFieldConfig(); prepareOutputFiles(); for (String tsvIssue: staticFieldConfig.validateTSV()) { System.out.println(tsvIssue); } } catch (IOException e) { // wrap the exception in a runtime exception. // the singleton pattern below doesn't work if the constructor can throw // and if these do throw ioexceptions there's nothing we can do anyway throw new RuntimeException(e); } } private static CLIA[] initCliaLabNumbers() { int numLabs = Config.getAsInteger("exporter.bfd.clia_labs_count",1); CLIA[] labNumbers = new CLIA[numLabs]; CLIA labNumber = CLIA.parse(Config.get("exporter.bfd.clia_labs_start", "00A0000000")); for (int i = 0; i < numLabs; i++) { labNumbers[i] = labNumber; labNumber = labNumber.next(); } return labNumbers; } /** * Create the output folder and files. Write headers to each file. */ final void prepareOutputFiles() throws IOException { // Initialize output writers File output = Exporter.getOutputFolder("bfd", null); output.mkdirs(); Path outputDirectory = output.toPath(); beneficiaryWriters = new BeneficiaryWriters(outputDirectory); Path beneficiaryHistoryFile = outputDirectory.resolve("beneficiary_history.csv"); beneficiaryHistory = new SynchronizedBBLineWriter(beneficiaryHistoryFile); beneficiaryHistory.writeHeader(BeneficiaryHistoryFields.class); Path outpatientFile = outputDirectory.resolve("outpatient.csv"); outpatient = new SynchronizedBBLineWriter(outpatientFile); outpatient.writeHeader(OutpatientFields.class); Path inpatientFile = outputDirectory.resolve("inpatient.csv"); inpatient = new SynchronizedBBLineWriter(inpatientFile); inpatient.writeHeader(InpatientFields.class); Path carrierFile = outputDirectory.resolve("carrier.csv"); carrier = new SynchronizedBBLineWriter(carrierFile); carrier.writeHeader(CarrierFields.class); Path prescriptionFile = outputDirectory.resolve("prescription.csv"); prescription = new SynchronizedBBLineWriter(prescriptionFile); prescription.writeHeader(PrescriptionFields.class); Path dmeFile = outputDirectory.resolve("dme.csv"); dme = new SynchronizedBBLineWriter(dmeFile); dme.writeHeader(DMEFields.class); Path homeFile = outputDirectory.resolve("home.csv"); home = new SynchronizedBBLineWriter(homeFile); home.writeHeader(HHAFields.class); Path hospiceFile = outputDirectory.resolve("hospice.csv"); hospice = new SynchronizedBBLineWriter(hospiceFile); hospice.writeHeader(HospiceFields.class); Path snfFile = outputDirectory.resolve("snf.csv"); snf = new SynchronizedBBLineWriter(snfFile); snf.writeHeader(SNFFields.class); Path npiFile = outputDirectory.resolve("npi.tsv"); npi = new SynchronizedBBLineWriter(npiFile, "\t"); npi.writeHeader(NPIFields.class); } /** * Export a manifest file that lists all of the other BFD files (except the NPI file * which is special). * @throws IOException if something goes wrong */ public void exportManifest() throws IOException { File output = Exporter.getOutputFolder("bfd", null); output.mkdirs(); StringWriter manifest = new StringWriter(); manifest.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"); manifest.write("<dataSetManifest xmlns=\"http://cms.hhs.gov/bluebutton/api/schema/ccw-rif/v9\""); manifest.write(String.format(" timestamp=\"%s\" ", java.time.Instant.now() .atZone(java.time.ZoneId.of("Z")) .truncatedTo(java.time.temporal.ChronoUnit.SECONDS) .toString())); manifest.write("sequenceId=\"0\">\n"); for (File file: beneficiaryWriters.getFiles()) { manifest.write(String.format(" <entry name=\"%s\" type=\"BENEFICIARY\"/>\n", file.getName())); } manifest.write(String.format(" <entry name=\"%s\" type=\"INPATIENT\"/>\n", inpatient.getFile().getName())); manifest.write(String.format(" <entry name=\"%s\" type=\"OUTPATIENT\"/>\n", outpatient.getFile().getName())); manifest.write(String.format(" <entry name=\"%s\" type=\"PDE\"/>\n", prescription.getFile().getName())); manifest.write(String.format(" <entry name=\"%s\" type=\"CARRIER\"/>\n", carrier.getFile().getName())); manifest.write(String.format(" <entry name=\"%s\" type=\"DME\"/>\n", dme.getFile().getName())); manifest.write(String.format(" <entry name=\"%s\" type=\"HHA\"/>\n", home.getFile().getName())); manifest.write(String.format(" <entry name=\"%s\" type=\"HOSPICE\"/>\n", hospice.getFile().getName())); manifest.write(String.format(" <entry name=\"%s\" type=\"SNF\"/>\n", snf.getFile().getName())); manifest.write(String.format(" <entry name=\"%s\" type=\"BENEFICIARY_HISTORY\"/>\n", beneficiaryHistory.getFile().getName())); manifest.write("</dataSetManifest>"); Path manifestPath = output.toPath().resolve("manifest.xml"); Exporter.appendToFile(manifestPath, manifest.toString()); } /** * Export NPI writer with synthetic providers. * @throws IOException if something goes horribly wrong. */ public void exportNPIs() throws IOException { HashMap<NPIFields, String> fieldValues = new HashMap<>(); for (Provider h : Provider.getProviderList()) { // filter - exports only those organizations in use Table<Integer, String, AtomicInteger> utilization = h.getUtilization(); int totalEncounters = utilization.column(Provider.ENCOUNTERS).values().stream() .mapToInt(ai -> ai.get()).sum(); if (totalEncounters > 0) { // export organization fieldValues.clear(); fieldValues.put(NPIFields.NPI, h.npi); fieldValues.put(NPIFields.ENTITY_TYPE_CODE, "2"); fieldValues.put(NPIFields.EIN, "<UNAVAIL>"); fieldValues.put(NPIFields.ORG_NAME, h.name); npi.writeValues(NPIFields.class, fieldValues); Map<String, ArrayList<Clinician>> clinicians = h.clinicianMap; for (String specialty : clinicians.keySet()) { ArrayList<Clinician> docs = clinicians.get(specialty); for (Clinician doc : docs) { if (doc.getEncounterCount() > 0) { // export each doc Map<String,Object> attributes = doc.getAttributes(); fieldValues.clear(); fieldValues.put(NPIFields.NPI, doc.npi); fieldValues.put(NPIFields.ENTITY_TYPE_CODE, "1"); fieldValues.put(NPIFields.LAST_NAME, attributes.get(Clinician.LAST_NAME).toString()); fieldValues.put(NPIFields.FIRST_NAME, attributes.get(Clinician.FIRST_NAME).toString()); fieldValues.put(NPIFields.PREFIX, attributes.get(Clinician.NAME_PREFIX).toString()); fieldValues.put(NPIFields.CREDENTIALS, "M.D."); npi.writeValues(NPIFields.class, fieldValues); } } } } } } /** * Export a single person. * @param person the person to export * @param stopTime end time of simulation * @throws IOException if something goes wrong */ public void export(Person person, long stopTime) throws IOException { exportBeneficiary(person, stopTime); exportBeneficiaryHistory(person, stopTime); exportInpatient(person, stopTime); exportOutpatient(person, stopTime); exportCarrier(person, stopTime); exportPrescription(person, stopTime); exportDME(person, stopTime); exportHome(person, stopTime); exportHospice(person, stopTime); exportSNF(person, stopTime); } /** * Export a beneficiary details for single person. * @param person the person to export * @param stopTime end time of simulation * @throws IOException if something goes wrong */ private void exportBeneficiary(Person person, long stopTime) throws IOException { String beneIdStr = Long.toString(BB2RIFExporter.beneId.getAndDecrement()); person.attributes.put(BB2_BENE_ID, beneIdStr); String hicId = BB2RIFExporter.hicn.getAndUpdate((v) -> v.next()).toString(); person.attributes.put(BB2_HIC_ID, hicId); String mbiStr = BB2RIFExporter.mbi.getAndUpdate((v) -> v.next()).toString(); person.attributes.put(BB2_MBI, mbiStr); long deathDate = person.attributes.get(Person.DEATHDATE) == null ? -1 : (long) person.attributes.get(Person.DEATHDATE); // One entry for each year of history or until patient dies int yearsOfHistory = Config.getAsInteger("exporter.years_of_history"); int endYear = Utilities.getYear(stopTime); if (deathDate != -1 && Utilities.getYear(deathDate) < endYear) { endYear = Utilities.getYear(deathDate); // stop after year in which patient dies } PartDContractHistory partDContracts = new PartDContractHistory(person, stopTime); person.attributes.put(BB2_PARTD_CONTRACTS, partDContracts); for (int year = endYear - yearsOfHistory; year <= endYear; year++) { HashMap<BeneficiaryFields, String> fieldValues = new HashMap<>(); staticFieldConfig.setValues(fieldValues, BeneficiaryFields.class, person); if (year > endYear - yearsOfHistory) { // The first year output is set via staticFieldConfig to "INSERT", subsequent years // need to be "UPDATE" fieldValues.put(BeneficiaryFields.DML_IND, "UPDATE"); } fieldValues.put(BeneficiaryFields.RFRNC_YR, String.valueOf(year)); int monthCount = year == endYear ? Utilities.getMonth(stopTime) : 12; String monthCountStr = String.valueOf(monthCount); fieldValues.put(BeneficiaryFields.A_MO_CNT, monthCountStr); fieldValues.put(BeneficiaryFields.B_MO_CNT, monthCountStr); fieldValues.put(BeneficiaryFields.BUYIN_MO_CNT, monthCountStr); fieldValues.put(BeneficiaryFields.RDS_MO_CNT, monthCountStr); fieldValues.put(BeneficiaryFields.PLAN_CVRG_MO_CNT, monthCountStr); fieldValues.put(BeneficiaryFields.BENE_ID, beneIdStr); fieldValues.put(BeneficiaryFields.BENE_CRNT_HIC_NUM, hicId); fieldValues.put(BeneficiaryFields.MBI_NUM, mbiStr); fieldValues.put(BeneficiaryFields.BENE_SEX_IDENT_CD, getBB2SexCode((String)person.attributes.get(Person.GENDER))); String zipCode = (String)person.attributes.get(Person.ZIP); fieldValues.put(BeneficiaryFields.BENE_COUNTY_CD, locationMapper.zipToCountyCode(zipCode)); fieldValues.put(BeneficiaryFields.STATE_CODE, locationMapper.getStateCode((String)person.attributes.get(Person.STATE))); fieldValues.put(BeneficiaryFields.BENE_ZIP_CD, (String)person.attributes.get(Person.ZIP)); fieldValues.put(BeneficiaryFields.BENE_RACE_CD, bb2RaceCode( (String)person.attributes.get(Person.ETHNICITY), (String)person.attributes.get(Person.RACE))); fieldValues.put(BeneficiaryFields.BENE_SRNM_NAME, (String)person.attributes.get(Person.LAST_NAME)); String givenName = (String)person.attributes.get(Person.FIRST_NAME); fieldValues.put(BeneficiaryFields.BENE_GVN_NAME, StringUtils.truncate(givenName, 15)); long birthdate = (long) person.attributes.get(Person.BIRTHDATE); fieldValues.put(BeneficiaryFields.BENE_BIRTH_DT, bb2DateFromTimestamp(birthdate)); fieldValues.put(BeneficiaryFields.AGE, String.valueOf(ageAtEndOfYear(birthdate, year))); fieldValues.put(BeneficiaryFields.BENE_PTA_TRMNTN_CD, "0"); fieldValues.put(BeneficiaryFields.BENE_PTB_TRMNTN_CD, "0"); if (deathDate != -1) { // only add death date for years when it was (presumably) known. E.g. If we are outputting // record for 2005 and patient died in 2007 we don't include the death date. if (Utilities.getYear(deathDate) <= year) { fieldValues.put(BeneficiaryFields.DEATH_DT, bb2DateFromTimestamp(deathDate)); fieldValues.put(BeneficiaryFields.BENE_PTA_TRMNTN_CD, "1"); fieldValues.put(BeneficiaryFields.BENE_PTB_TRMNTN_CD, "1"); } } PartDContractID partDContractID = partDContracts.getContractID(year); if (partDContractID != null) { for (int i = 0; i < monthCount; i++) { fieldValues.put(beneficiaryPartDContractFields[i], partDContractID.toString()); } } beneficiaryWriters.getWriter(year).writeValues(BeneficiaryFields.class, fieldValues); } } private String getBB2SexCode(String sex) { switch (sex) { case "M": return "1"; case "F": return "2"; default: return "0"; } } private static final Comparator<Entry> ENTRY_SORTER = new Comparator<Entry>() { @Override public int compare(Entry o1, Entry o2) { return (int)(o2.start - o1.start); } }; /** * This returns the list of active diagnoses, sorted by most recent first * and oldest last. * @param person patient with the diagnoses. * @return the list of active diagnoses, sorted by most recent first and oldest last. */ private List<String> getDiagnosesCodes(Person person, long time) { // Collect the active diagnoses at the given time, // keeping only those diagnoses that are mappable. List<Entry> diagnoses = new ArrayList<Entry>(); for (HealthRecord.Encounter encounter : person.record.encounters) { if (encounter.start <= time) { for (Entry dx : encounter.conditions) { if (dx.start <= time && (dx.stop == 0L || dx.stop > time)) { if (conditionCodeMapper.canMap(dx.codes.get(0).code)) { String mapped = conditionCodeMapper.map(dx.codes.get(0).code, person, true); // Temporarily add the mapped code... we'll remove it later. Code mappedCode = new Code("ICD10", mapped, dx.codes.get(0).display); dx.codes.add(mappedCode); diagnoses.add(dx); } } } } } // Sort them by date and then return only the mapped codes (not the entire Entry). diagnoses.sort(ENTRY_SORTER); List<String> mappedDiagnosisCodes = new ArrayList<String>(); for (Entry dx : diagnoses) { mappedDiagnosisCodes.add(dx.codes.remove(dx.codes.size() - 1).code); } return mappedDiagnosisCodes; } /** * Export a beneficiary history for single person. Assumes exportBeneficiary * was called first to set up various ID on person * @param person the person to export * @param stopTime end time of simulation * @throws IOException if something goes wrong */ private void exportBeneficiaryHistory(Person person, long stopTime) throws IOException { HashMap<BeneficiaryHistoryFields, String> fieldValues = new HashMap<>(); staticFieldConfig.setValues(fieldValues, BeneficiaryHistoryFields.class, person); String beneIdStr = (String)person.attributes.get(BB2_BENE_ID); fieldValues.put(BeneficiaryHistoryFields.BENE_ID, beneIdStr); String hicId = (String)person.attributes.get(BB2_HIC_ID); fieldValues.put(BeneficiaryHistoryFields.BENE_CRNT_HIC_NUM, hicId); String mbiStr = (String)person.attributes.get(BB2_MBI); fieldValues.put(BeneficiaryHistoryFields.MBI_NUM, mbiStr); fieldValues.put(BeneficiaryHistoryFields.BENE_SEX_IDENT_CD, getBB2SexCode((String)person.attributes.get(Person.GENDER))); long birthdate = (long) person.attributes.get(Person.BIRTHDATE); fieldValues.put(BeneficiaryHistoryFields.BENE_BIRTH_DT, bb2DateFromTimestamp(birthdate)); String zipCode = (String)person.attributes.get(Person.ZIP); fieldValues.put(BeneficiaryHistoryFields.BENE_COUNTY_CD, locationMapper.zipToCountyCode(zipCode)); fieldValues.put(BeneficiaryHistoryFields.STATE_CODE, locationMapper.getStateCode((String)person.attributes.get(Person.STATE))); fieldValues.put(BeneficiaryHistoryFields.BENE_ZIP_CD, (String)person.attributes.get(Person.ZIP)); fieldValues.put(BeneficiaryHistoryFields.BENE_RACE_CD, bb2RaceCode( (String)person.attributes.get(Person.ETHNICITY), (String)person.attributes.get(Person.RACE))); fieldValues.put(BeneficiaryHistoryFields.BENE_SRNM_NAME, (String)person.attributes.get(Person.LAST_NAME)); fieldValues.put(BeneficiaryHistoryFields.BENE_GVN_NAME, (String)person.attributes.get(Person.FIRST_NAME)); String terminationCode = (person.attributes.get(Person.DEATHDATE) == null) ? "0" : "1"; fieldValues.put(BeneficiaryHistoryFields.BENE_PTA_TRMNTN_CD, terminationCode); fieldValues.put(BeneficiaryHistoryFields.BENE_PTB_TRMNTN_CD, terminationCode); beneficiaryHistory.writeValues(BeneficiaryHistoryFields.class, fieldValues); } /** * Calculate the age of a person at the end of the given year. * @param birthdate a person's birthdate specified as number of milliseconds since the epoch * @param year the year * @return the person's age */ private static int ageAtEndOfYear(long birthdate, int year) { return year - Utilities.getYear(birthdate); } /** * Export outpatient claims details for a single person. * @param person the person to export * @param stopTime end time of simulation * @throws IOException if something goes wrong */ private void exportOutpatient(Person person, long stopTime) throws IOException { HashMap<OutpatientFields, String> fieldValues = new HashMap<>(); for (HealthRecord.Encounter encounter : person.record.encounters) { boolean isAmbulatory = encounter.type.equals(EncounterType.AMBULATORY.toString()); boolean isOutpatient = encounter.type.equals(EncounterType.OUTPATIENT.toString()); boolean isUrgent = encounter.type.equals(EncounterType.URGENTCARE.toString()); boolean isWellness = encounter.type.equals(EncounterType.WELLNESS.toString()); boolean isPrimary = (ProviderType.PRIMARY == encounter.provider.type); long claimId = BB2RIFExporter.claimId.getAndDecrement(); int claimGroupId = BB2RIFExporter.claimGroupId.getAndDecrement(); if (isPrimary || !(isAmbulatory || isOutpatient || isUrgent || isWellness)) { continue; } staticFieldConfig.setValues(fieldValues, OutpatientFields.class, person); // The REQUIRED fields fieldValues.put(OutpatientFields.BENE_ID, (String) person.attributes.get(BB2_BENE_ID)); fieldValues.put(OutpatientFields.CLM_ID, "" + claimId); fieldValues.put(OutpatientFields.CLM_GRP_ID, "" + claimGroupId); fieldValues.put(OutpatientFields.CLM_FROM_DT, bb2DateFromTimestamp(encounter.start)); fieldValues.put(OutpatientFields.CLM_THRU_DT, bb2DateFromTimestamp(encounter.stop)); fieldValues.put(OutpatientFields.NCH_WKLY_PROC_DT, bb2DateFromTimestamp(ExportHelper.nextFriday(encounter.stop))); fieldValues.put(OutpatientFields.PRVDR_NUM, encounter.provider.id); fieldValues.put(OutpatientFields.AT_PHYSN_NPI, encounter.clinician.npi); fieldValues.put(OutpatientFields.RNDRNG_PHYSN_NPI, encounter.clinician.npi); fieldValues.put(OutpatientFields.ORG_NPI_NUM, encounter.provider.npi); fieldValues.put(OutpatientFields.OP_PHYSN_NPI, encounter.clinician.npi); fieldValues.put(OutpatientFields.CLM_PMT_AMT, String.format("%.2f", encounter.claim.getTotalClaimCost())); if (encounter.claim.payer == Payer.getGovernmentPayer("Medicare")) { fieldValues.put(OutpatientFields.NCH_PRMRY_PYR_CLM_PD_AMT, "0"); } else { fieldValues.put(OutpatientFields.NCH_PRMRY_PYR_CLM_PD_AMT, String.format("%.2f", encounter.claim.getCoveredCost())); } fieldValues.put(OutpatientFields.PRVDR_STATE_CD, locationMapper.getStateCode(encounter.provider.state)); // PTNT_DSCHRG_STUS_CD: 1=home, 2=transfer, 3=SNF, 20=died, 30=still here String field = null; if (encounter.ended) { field = "1"; } else { field = "30"; // the patient is still here } if (!person.alive(encounter.stop)) { field = "20"; // the patient died before the encounter ended } fieldValues.put(OutpatientFields.PTNT_DSCHRG_STUS_CD, field); fieldValues.put(OutpatientFields.CLM_TOT_CHRG_AMT, String.format("%.2f", encounter.claim.getTotalClaimCost())); fieldValues.put(OutpatientFields.CLM_OP_PRVDR_PMT_AMT, String.format("%.2f", encounter.claim.getTotalClaimCost())); fieldValues.put(OutpatientFields.REV_CNTR_TOT_CHRG_AMT, String.format("%.2f", encounter.claim.getCoveredCost())); fieldValues.put(OutpatientFields.REV_CNTR_NCVRD_CHRG_AMT, String.format("%.2f", encounter.claim.getPatientCost())); fieldValues.put(OutpatientFields.NCH_BENE_PTB_DDCTBL_AMT, String.format("%.2f", encounter.claim.getDeductiblePaid())); fieldValues.put(OutpatientFields.REV_CNTR_CASH_DDCTBL_AMT, String.format("%.2f", encounter.claim.getDeductiblePaid())); fieldValues.put(OutpatientFields.REV_CNTR_COINSRNC_WGE_ADJSTD_C, String.format("%.2f", encounter.claim.getCoinsurancePaid())); fieldValues.put(OutpatientFields.REV_CNTR_PMT_AMT_AMT, String.format("%.2f", encounter.claim.getTotalClaimCost())); fieldValues.put(OutpatientFields.REV_CNTR_PRVDR_PMT_AMT, String.format("%.2f", encounter.claim.getTotalClaimCost())); fieldValues.put(OutpatientFields.REV_CNTR_PTNT_RSPNSBLTY_PMT, String.format("%.2f", encounter.claim.getDeductiblePaid() + encounter.claim.getCoinsurancePaid())); fieldValues.put(OutpatientFields.REV_CNTR_RDCD_COINSRNC_AMT, String.format("%.2f", encounter.claim.getCoinsurancePaid())); if (encounter.reason != null) { // If the encounter has a recorded reason, enter the mapped // values into the principle diagnoses code. if (conditionCodeMapper.canMap(encounter.reason.code)) { String icdCode = conditionCodeMapper.map(encounter.reason.code, person, true); fieldValues.put(OutpatientFields.PRNCPAL_DGNS_CD, icdCode); } } // Use the active condition diagnoses to enter mapped values // into the diagnoses codes. List<String> mappedDiagnosisCodes = getDiagnosesCodes(person, encounter.stop); boolean noDiagnoses = mappedDiagnosisCodes.isEmpty(); if (!noDiagnoses) { int smallest = Math.min(mappedDiagnosisCodes.size(), outpatientDxFields.length); for (int i = 0; i < smallest; i++) { OutpatientFields[] dxField = outpatientDxFields[i]; fieldValues.put(dxField[0], mappedDiagnosisCodes.get(i)); fieldValues.put(dxField[1], "0"); // 0=ICD10 } if (!fieldValues.containsKey(OutpatientFields.PRNCPAL_DGNS_CD)) { fieldValues.put(OutpatientFields.PRNCPAL_DGNS_CD, mappedDiagnosisCodes.get(0)); } } // Use the procedures in this encounter to enter mapped values boolean noProcedures = false; if (!encounter.procedures.isEmpty()) { List<HealthRecord.Procedure> mappableProcedures = new ArrayList<>(); List<String> mappedProcedureCodes = new ArrayList<>(); for (HealthRecord.Procedure procedure : encounter.procedures) { for (HealthRecord.Code code : procedure.codes) { if (conditionCodeMapper.canMap(code.code)) { mappableProcedures.add(procedure); mappedProcedureCodes.add(conditionCodeMapper.map(code.code, person, true)); break; // take the first mappable code for each procedure } } } if (!mappableProcedures.isEmpty()) { int smallest = Math.min(mappableProcedures.size(), outpatientPxFields.length); for (int i = 0; i < smallest; i++) { OutpatientFields[] pxField = outpatientPxFields[i]; fieldValues.put(pxField[0], mappedProcedureCodes.get(i)); fieldValues.put(pxField[1], "0"); // 0=ICD10 fieldValues.put(pxField[2], bb2DateFromTimestamp(mappableProcedures.get(i).start)); } } else { noProcedures = true; } } if (noDiagnoses && noProcedures) { continue; // skip this encounter } synchronized (outpatient) { int claimLine = 1; for (ClaimEntry lineItem : encounter.claim.items) { String hcpcsCode = null; if (lineItem.entry instanceof HealthRecord.Procedure) { for (HealthRecord.Code code : lineItem.entry.codes) { if (hcpcsCodeMapper.canMap(code.code)) { hcpcsCode = hcpcsCodeMapper.map(code.code, person, true); break; // take the first mappable code for each procedure } } fieldValues.remove(OutpatientFields.REV_CNTR_NDC_QTY); fieldValues.remove(OutpatientFields.REV_CNTR_NDC_QTY_QLFR_CD); } else if (lineItem.entry instanceof HealthRecord.Medication) { HealthRecord.Medication med = (HealthRecord.Medication) lineItem.entry; if (med.administration) { hcpcsCode = "T1502"; // Administration of medication fieldValues.put(OutpatientFields.REV_CNTR_NDC_QTY, "1"); // 1 Unit fieldValues.put(OutpatientFields.REV_CNTR_NDC_QTY_QLFR_CD, "UN"); // Unit } } if (hcpcsCode == null) { continue; } fieldValues.put(OutpatientFields.CLM_LINE_NUM, Integer.toString(claimLine++)); fieldValues.put(OutpatientFields.REV_CNTR_DT, bb2DateFromTimestamp(lineItem.entry.start)); fieldValues.put(OutpatientFields.HCPCS_CD, hcpcsCode); fieldValues.put(OutpatientFields.REV_CNTR_RATE_AMT, String.format("%.2f", (lineItem.cost))); fieldValues.put(OutpatientFields.REV_CNTR_PMT_AMT_AMT, String.format("%.2f", lineItem.coinsurance + lineItem.payer)); fieldValues.put(OutpatientFields.REV_CNTR_TOT_CHRG_AMT, String.format("%.2f", lineItem.cost)); fieldValues.put(OutpatientFields.REV_CNTR_NCVRD_CHRG_AMT, String.format("%.2f", lineItem.copay + lineItem.deductible + lineItem.pocket)); outpatient.writeValues(OutpatientFields.class, fieldValues); } if (claimLine == 1) { // If claimLine still equals 1, then no line items were successfully added. // Add a single top-level entry. fieldValues.put(OutpatientFields.CLM_LINE_NUM, Integer.toString(claimLine)); fieldValues.put(OutpatientFields.REV_CNTR_DT, bb2DateFromTimestamp(encounter.start)); // 99241: "Office consultation for a new or established patient" fieldValues.put(OutpatientFields.HCPCS_CD, "99241"); outpatient.writeValues(OutpatientFields.class, fieldValues); } } } } /** * Export inpatient claims details for a single person. * @param person the person to export * @param stopTime end time of simulation * @throws IOException if something goes wrong */ private void exportInpatient(Person person, long stopTime) throws IOException { HashMap<InpatientFields, String> fieldValues = new HashMap<>(); boolean previousEmergency = false; for (HealthRecord.Encounter encounter : person.record.encounters) { boolean isInpatient = encounter.type.equals(EncounterType.INPATIENT.toString()); boolean isEmergency = encounter.type.equals(EncounterType.EMERGENCY.toString()); long claimId = BB2RIFExporter.claimId.getAndDecrement(); int claimGroupId = BB2RIFExporter.claimGroupId.getAndDecrement(); if (!(isInpatient || isEmergency)) { previousEmergency = false; continue; } fieldValues.clear(); staticFieldConfig.setValues(fieldValues, InpatientFields.class, person); // The REQUIRED fields fieldValues.put(InpatientFields.BENE_ID, (String) person.attributes.get(BB2_BENE_ID)); fieldValues.put(InpatientFields.CLM_ID, "" + claimId); fieldValues.put(InpatientFields.CLM_GRP_ID, "" + claimGroupId); fieldValues.put(InpatientFields.CLM_FROM_DT, bb2DateFromTimestamp(encounter.start)); fieldValues.put(InpatientFields.CLM_ADMSN_DT, bb2DateFromTimestamp(encounter.start)); fieldValues.put(InpatientFields.CLM_THRU_DT, bb2DateFromTimestamp(encounter.stop)); fieldValues.put(InpatientFields.NCH_BENE_DSCHRG_DT, bb2DateFromTimestamp(encounter.stop)); fieldValues.put(InpatientFields.NCH_WKLY_PROC_DT, bb2DateFromTimestamp(ExportHelper.nextFriday(encounter.stop))); fieldValues.put(InpatientFields.PRVDR_NUM, encounter.provider.id); fieldValues.put(InpatientFields.AT_PHYSN_NPI, encounter.clinician.npi); fieldValues.put(InpatientFields.ORG_NPI_NUM, encounter.provider.npi); fieldValues.put(InpatientFields.CLM_PMT_AMT, String.format("%.2f", encounter.claim.getTotalClaimCost())); if (encounter.claim.payer == Payer.getGovernmentPayer("Medicare")) { fieldValues.put(InpatientFields.NCH_PRMRY_PYR_CLM_PD_AMT, "0"); } else { fieldValues.put(InpatientFields.NCH_PRMRY_PYR_CLM_PD_AMT, String.format("%.2f", encounter.claim.getCoveredCost())); } fieldValues.put(InpatientFields.PRVDR_STATE_CD, locationMapper.getStateCode(encounter.provider.state)); // PTNT_DSCHRG_STUS_CD: 1=home, 2=transfer, 3=SNF, 20=died, 30=still here String field = null; if (encounter.ended) { field = "1"; // TODO 2=transfer if the next encounter is also inpatient } else { field = "30"; // the patient is still here } if (!person.alive(encounter.stop)) { field = "20"; // the patient died before the encounter ended } fieldValues.put(InpatientFields.PTNT_DSCHRG_STUS_CD, field); fieldValues.put(InpatientFields.CLM_TOT_CHRG_AMT, String.format("%.2f", encounter.claim.getTotalClaimCost())); if (isEmergency) { field = "1"; // emergency } else if (previousEmergency) { field = "2"; // urgent } else { field = "3"; // elective } fieldValues.put(InpatientFields.CLM_IP_ADMSN_TYPE_CD, field); fieldValues.put(InpatientFields.NCH_BENE_IP_DDCTBL_AMT, String.format("%.2f", encounter.claim.getDeductiblePaid())); fieldValues.put(InpatientFields.NCH_BENE_PTA_COINSRNC_LBLTY_AM, String.format("%.2f", encounter.claim.getCoinsurancePaid())); fieldValues.put(InpatientFields.NCH_IP_NCVRD_CHRG_AMT, String.format("%.2f", encounter.claim.getPatientCost())); fieldValues.put(InpatientFields.NCH_IP_TOT_DDCTN_AMT, String.format("%.2f", encounter.claim.getPatientCost())); int days = (int) ((encounter.stop - encounter.start) / (1000 * 60 * 60 * 24)); fieldValues.put(InpatientFields.CLM_UTLZTN_DAY_CNT, "" + days); if (days > 60) { field = "" + (days - 60); } else { field = "0"; } fieldValues.put(InpatientFields.BENE_TOT_COINSRNC_DAYS_CNT, field); if (days > 60) { field = "1"; // days outlier } else if (encounter.claim.getTotalClaimCost() > 100_000) { field = "2"; // cost outlier } else { field = "0"; // no outlier } fieldValues.put(InpatientFields.CLM_DRG_OUTLIER_STAY_CD, field); fieldValues.put(InpatientFields.REV_CNTR_TOT_CHRG_AMT, String.format("%.2f", encounter.claim.getCoveredCost())); fieldValues.put(InpatientFields.REV_CNTR_NCVRD_CHRG_AMT, String.format("%.2f", encounter.claim.getPatientCost())); // OPTIONAL FIELDS fieldValues.put(InpatientFields.RNDRNG_PHYSN_NPI, encounter.clinician.npi); if (encounter.reason != null) { // If the encounter has a recorded reason, enter the mapped // values into the principle diagnoses code. if (conditionCodeMapper.canMap(encounter.reason.code)) { String icdCode = conditionCodeMapper.map(encounter.reason.code, person, true); fieldValues.put(InpatientFields.PRNCPAL_DGNS_CD, icdCode); fieldValues.put(InpatientFields.ADMTG_DGNS_CD, icdCode); if (drgCodeMapper.canMap(icdCode)) { fieldValues.put(InpatientFields.CLM_DRG_CD, drgCodeMapper.map(icdCode, person)); } } } // Use the active condition diagnoses to enter mapped values // into the diagnoses codes. List<String> presentOnAdmission = getDiagnosesCodes(person, encounter.start); List<String> mappedDiagnosisCodes = getDiagnosesCodes(person, encounter.stop); boolean noDiagnoses = mappedDiagnosisCodes.isEmpty(); if (!noDiagnoses) { int smallest = Math.min(mappedDiagnosisCodes.size(), inpatientDxFields.length); for (int i = 0; i < smallest; i++) { InpatientFields[] dxField = inpatientDxFields[i]; String dxCode = mappedDiagnosisCodes.get(i); fieldValues.put(dxField[0], dxCode); fieldValues.put(dxField[1], "0"); // 0=ICD10 String present = presentOnAdmission.contains(dxCode) ? "Y" : "N"; fieldValues.put(dxField[2], present); } if (!fieldValues.containsKey(InpatientFields.PRNCPAL_DGNS_CD)) { fieldValues.put(InpatientFields.PRNCPAL_DGNS_CD, mappedDiagnosisCodes.get(0)); } } // Use the procedures in this encounter to enter mapped values boolean noProcedures = false; if (!encounter.procedures.isEmpty()) { List<HealthRecord.Procedure> mappableProcedures = new ArrayList<>(); List<String> mappedProcedureCodes = new ArrayList<>(); for (HealthRecord.Procedure procedure : encounter.procedures) { for (HealthRecord.Code code : procedure.codes) { if (conditionCodeMapper.canMap(code.code)) { mappableProcedures.add(procedure); mappedProcedureCodes.add(conditionCodeMapper.map(code.code, person, true)); break; // take the first mappable code for each procedure } } } if (!mappableProcedures.isEmpty()) { int smallest = Math.min(mappableProcedures.size(), inpatientPxFields.length); for (int i = 0; i < smallest; i++) { InpatientFields[] pxField = inpatientPxFields[i]; fieldValues.put(pxField[0], mappedProcedureCodes.get(i)); fieldValues.put(pxField[1], "0"); // 0=ICD10 fieldValues.put(pxField[2], bb2DateFromTimestamp(mappableProcedures.get(i).start)); } } else { noProcedures = true; } } if (noDiagnoses && noProcedures) { continue; // skip this encounter } previousEmergency = isEmergency; synchronized (inpatient) { int claimLine = 1; for (ClaimEntry lineItem : encounter.claim.items) { String hcpcsCode = null; if (lineItem.entry instanceof HealthRecord.Procedure) { for (HealthRecord.Code code : lineItem.entry.codes) { if (hcpcsCodeMapper.canMap(code.code)) { hcpcsCode = hcpcsCodeMapper.map(code.code, person, true); break; // take the first mappable code for each procedure } } fieldValues.remove(InpatientFields.REV_CNTR_NDC_QTY); fieldValues.remove(InpatientFields.REV_CNTR_NDC_QTY_QLFR_CD); } else if (lineItem.entry instanceof HealthRecord.Medication) { HealthRecord.Medication med = (HealthRecord.Medication) lineItem.entry; if (med.administration) { hcpcsCode = "T1502"; // Administration of medication fieldValues.put(InpatientFields.REV_CNTR_NDC_QTY, "1"); // 1 Unit fieldValues.put(InpatientFields.REV_CNTR_NDC_QTY_QLFR_CD, "UN"); // Unit } } if (hcpcsCode == null) { continue; } fieldValues.put(InpatientFields.CLM_LINE_NUM, Integer.toString(claimLine++)); fieldValues.put(InpatientFields.HCPCS_CD, hcpcsCode); fieldValues.put(InpatientFields.REV_CNTR_RATE_AMT, String.format("%.2f", (lineItem.cost / Integer.max(1, days)))); fieldValues.put(InpatientFields.REV_CNTR_TOT_CHRG_AMT, String.format("%.2f", lineItem.cost)); fieldValues.put(InpatientFields.REV_CNTR_NCVRD_CHRG_AMT, String.format("%.2f", lineItem.copay + lineItem.deductible + lineItem.pocket)); if (lineItem.pocket == 0 && lineItem.deductible == 0) { // Not subject to deductible or coinsurance fieldValues.put(InpatientFields.REV_CNTR_DDCTBL_COINSRNC_CD, "3"); } else if (lineItem.pocket > 0 && lineItem.deductible > 0) { // Subject to deductible and coinsurance fieldValues.put(InpatientFields.REV_CNTR_DDCTBL_COINSRNC_CD, "0"); } else if (lineItem.pocket == 0) { // Not subject to deductible fieldValues.put(InpatientFields.REV_CNTR_DDCTBL_COINSRNC_CD, "1"); } else { // Not subject to coinsurance fieldValues.put(InpatientFields.REV_CNTR_DDCTBL_COINSRNC_CD, "2"); } inpatient.writeValues(InpatientFields.class, fieldValues); } if (claimLine == 1) { // If claimLine still equals 1, then no line items were successfully added. // Add a single top-level entry. fieldValues.put(InpatientFields.CLM_LINE_NUM, Integer.toString(claimLine)); // HCPCS 99221: "Inpatient hospital visits: Initial and subsequent" fieldValues.put(InpatientFields.HCPCS_CD, "99221"); inpatient.writeValues(InpatientFields.class, fieldValues); } } } } /** * Export carrier claims details for a single person. * @param person the person to export * @param stopTime end time of simulation * @throws IOException if something goes wrong */ private void exportCarrier(Person person, long stopTime) throws IOException { HashMap<CarrierFields, String> fieldValues = new HashMap<>(); double latestHemoglobin = 0; for (HealthRecord.Encounter encounter : person.record.encounters) { if (ProviderType.PRIMARY != encounter.provider.type) { continue; } long claimId = BB2RIFExporter.claimId.getAndDecrement(); int claimGroupId = BB2RIFExporter.claimGroupId.getAndDecrement(); for (HealthRecord.Observation observation : encounter.observations) { if (observation.containsCode("718-7", "http://loinc.org")) { latestHemoglobin = (double) observation.value; } } staticFieldConfig.setValues(fieldValues, CarrierFields.class, person); fieldValues.put(CarrierFields.BENE_ID, (String) person.attributes.get(BB2_BENE_ID)); // The REQUIRED fields fieldValues.put(CarrierFields.CLM_ID, "" + claimId); fieldValues.put(CarrierFields.CLM_GRP_ID, "" + claimGroupId); fieldValues.put(CarrierFields.CLM_FROM_DT, bb2DateFromTimestamp(encounter.start)); fieldValues.put(CarrierFields.LINE_1ST_EXPNS_DT, bb2DateFromTimestamp(encounter.start)); fieldValues.put(CarrierFields.CLM_THRU_DT, bb2DateFromTimestamp(encounter.stop)); fieldValues.put(CarrierFields.LINE_LAST_EXPNS_DT, bb2DateFromTimestamp(encounter.stop)); fieldValues.put(CarrierFields.NCH_WKLY_PROC_DT, bb2DateFromTimestamp(ExportHelper.nextFriday(encounter.stop))); fieldValues.put(CarrierFields.CARR_NUM, getCarrier(encounter.provider.state, CarrierFields.CARR_NUM)); fieldValues.put(CarrierFields.CLM_PMT_AMT, String.format("%.2f", encounter.claim.getTotalClaimCost())); if (encounter.claim.payer == Payer.getGovernmentPayer("Medicare")) { fieldValues.put(CarrierFields.CARR_CLM_PRMRY_PYR_PD_AMT, "0"); } else { fieldValues.put(CarrierFields.CARR_CLM_PRMRY_PYR_PD_AMT, String.format("%.2f", encounter.claim.getCoveredCost())); } fieldValues.put(CarrierFields.NCH_CLM_PRVDR_PMT_AMT, String.format("%.2f", encounter.claim.getTotalClaimCost())); fieldValues.put(CarrierFields.NCH_CARR_CLM_SBMTD_CHRG_AMT, String.format("%.2f", encounter.claim.getTotalClaimCost())); fieldValues.put(CarrierFields.NCH_CARR_CLM_ALOWD_AMT, String.format("%.2f", encounter.claim.getCoveredCost())); fieldValues.put(CarrierFields.CARR_CLM_CASH_DDCTBL_APLD_AMT, String.format("%.2f", encounter.claim.getDeductiblePaid())); fieldValues.put(CarrierFields.CARR_CLM_RFRNG_PIN_NUM, encounter.provider.id); fieldValues.put(CarrierFields.CARR_PRFRNG_PIN_NUM, encounter.provider.id); fieldValues.put(CarrierFields.ORG_NPI_NUM, encounter.provider.npi); fieldValues.put(CarrierFields.PRF_PHYSN_NPI, encounter.clinician.npi); fieldValues.put(CarrierFields.RFR_PHYSN_NPI, encounter.clinician.npi); fieldValues.put(CarrierFields.PRVDR_SPCLTY, ClinicianSpecialty.getCMSProviderSpecialtyCode( (String) encounter.clinician.attributes.get(Clinician.SPECIALTY))); fieldValues.put(CarrierFields.TAX_NUM, bb2TaxId((String)encounter.clinician.attributes.get(Person.IDENTIFIER_SSN))); fieldValues.put(CarrierFields.LINE_SRVC_CNT, "" + encounter.claim.items.size()); fieldValues.put(CarrierFields.CARR_LINE_PRCNG_LCLTY_CD, getCarrier(encounter.provider.state, CarrierFields.CARR_LINE_PRCNG_LCLTY_CD)); fieldValues.put(CarrierFields.LINE_NCH_PMT_AMT, String.format("%.2f", encounter.claim.getCoveredCost())); // length of encounter in minutes fieldValues.put(CarrierFields.CARR_LINE_MTUS_CNT, "" + ((encounter.stop - encounter.start) / (1000 * 60))); fieldValues.put(CarrierFields.LINE_HCT_HGB_RSLT_NUM, "" + latestHemoglobin); // OPTIONAL String icdReasonCode = null; if (encounter.reason != null) { // If the encounter has a recorded reason, enter the mapped // values into the principle diagnoses code. if (conditionCodeMapper.canMap(encounter.reason.code)) { icdReasonCode = conditionCodeMapper.map(encounter.reason.code, person, true); fieldValues.put(CarrierFields.PRNCPAL_DGNS_CD, icdReasonCode); fieldValues.put(CarrierFields.LINE_ICD_DGNS_CD, icdReasonCode); } } // Use the active condition diagnoses to enter mapped values // into the diagnoses codes. List<String> mappedDiagnosisCodes = getDiagnosesCodes(person, encounter.stop); if (mappedDiagnosisCodes.isEmpty() && icdReasonCode == null) { continue; // skip this encounter } int smallest = Math.min(mappedDiagnosisCodes.size(), carrierDxFields.length); for (int i = 0; i < smallest; i++) { CarrierFields[] dxField = carrierDxFields[i]; fieldValues.put(dxField[0], mappedDiagnosisCodes.get(i)); fieldValues.put(dxField[1], "0"); // 0=ICD10 } if (!fieldValues.containsKey(CarrierFields.PRNCPAL_DGNS_CD)) { fieldValues.put(CarrierFields.PRNCPAL_DGNS_CD, mappedDiagnosisCodes.get(0)); } synchronized (carrier) { int lineNum = 1; CLIA cliaLab = cliaLabNumbers[person.randInt(cliaLabNumbers.length)]; for (ClaimEntry lineItem : encounter.claim.items) { fieldValues.put(CarrierFields.LINE_BENE_PTB_DDCTBL_AMT, String.format("%.2f", lineItem.deductible)); fieldValues.put(CarrierFields.LINE_COINSRNC_AMT, String.format("%.2f", lineItem.coinsurance)); fieldValues.put(CarrierFields.LINE_BENE_PMT_AMT, String.format("%.2f", lineItem.copay + lineItem.deductible + lineItem.pocket)); fieldValues.put(CarrierFields.LINE_PRVDR_PMT_AMT, String.format("%.2f", lineItem.coinsurance + lineItem.payer)); fieldValues.put(CarrierFields.LINE_SBMTD_CHRG_AMT, String.format("%.2f", lineItem.cost)); fieldValues.put(CarrierFields.LINE_ALOWD_CHRG_AMT, String.format("%.2f", lineItem.cost - lineItem.adjustment)); // If this item is a lab report, add the number of the clinical lab... if (lineItem.entry instanceof HealthRecord.Report) { fieldValues.put(CarrierFields.CARR_LINE_CLIA_LAB_NUM, cliaLab.toString()); } // set the line number and write out field values fieldValues.put(CarrierFields.LINE_NUM, Integer.toString(lineNum++)); carrier.writeValues(CarrierFields.class, fieldValues); } if (lineNum == 1) { // If lineNum still equals 1, then no line items were successfully added. // Add a single top-level entry. fieldValues.put(CarrierFields.LINE_NUM, Integer.toString(lineNum)); fieldValues.put(CarrierFields.LINE_BENE_PTB_DDCTBL_AMT, String.format("%.2f", encounter.claim.getDeductiblePaid())); fieldValues.put(CarrierFields.LINE_COINSRNC_AMT, String.format("%.2f", encounter.claim.getCoinsurancePaid())); fieldValues.put(CarrierFields.LINE_SBMTD_CHRG_AMT, String.format("%.2f", encounter.claim.getTotalClaimCost())); fieldValues.put(CarrierFields.LINE_ALOWD_CHRG_AMT, String.format("%.2f", encounter.claim.getCoveredCost())); fieldValues.put(CarrierFields.LINE_PRVDR_PMT_AMT, String.format("%.2f", encounter.claim.getCoveredCost())); fieldValues.put(CarrierFields.LINE_BENE_PMT_AMT, String.format("%.2f", encounter.claim.getPatientCost())); carrier.writeValues(CarrierFields.class, fieldValues); } } } } private static String bb2TaxId(String ssn) { if (ssn != null) { return ssn.replaceAll("-", ""); } else { return ""; } } private String getCarrier(String state, CarrierFields column) { for (LinkedHashMap<String, String> row : carrierLookup) { if (row.get("STATE").equals(state) || row.get("STATE_CODE").equals(state)) { return row.get(column.toString()); } } return "0"; } private static class PartDContractHistory { private static final PartDContractID[] partDContractIDs = initContractIDs(); private Map<Integer, PartDContractID> partDContracts; public PartDContractHistory(Person person, long stopTime) { long deathDate = person.attributes.get(Person.DEATHDATE) == null ? -1 : (long) person.attributes.get(Person.DEATHDATE); int yearsOfHistory = Config.getAsInteger("exporter.years_of_history"); int endYear = Utilities.getYear(stopTime); if (deathDate != -1 && Utilities.getYear(deathDate) < endYear) { endYear = Utilities.getYear(deathDate); // stop after year in which patient dies } partDContracts = new HashMap<>(); for (int year = endYear - yearsOfHistory; year <= endYear; year++) { if (person.randInt(10) > 2) { // 30% chance of not enrolling in Part D PartDContractID partDContractID = partDContractIDs[person.randInt(partDContractIDs.length)]; partDContracts.put(year, partDContractID); } } } public PartDContractID getContractID(int year) { return partDContracts.get(year); } private static PartDContractID[] initContractIDs() { int numContracts = Config.getAsInteger("exporter.bfd.partd_contract_count",1); PartDContractID[] contractIDs = new PartDContractID[numContracts]; PartDContractID contractID = PartDContractID.parse( Config.get("exporter.bfd.partd_contract_start", "Z0001")); for (int i = 0; i < numContracts; i++) { contractIDs[i] = contractID; contractID = contractID.next(); } return contractIDs; } } /** * Export prescription claims details for a single person. * @param person the person to export * @param stopTime end time of simulation * @throws IOException if something goes wrong */ private void exportPrescription(Person person, long stopTime) throws IOException { PartDContractHistory partDContracts = (PartDContractHistory) person.attributes.get(BB2_PARTD_CONTRACTS); HashMap<PrescriptionFields, String> fieldValues = new HashMap<>(); HashMap<String, Integer> fillNum = new HashMap<>(); double costs = 0; int costYear = 0; for (HealthRecord.Encounter encounter : person.record.encounters) { PartDContractID partDContractID = partDContracts.getContractID( Utilities.getYear(encounter.start)); if (partDContractID == null) { continue; // skip medications if patient isn't enrolled in Part D } for (Medication medication : encounter.medications) { if (!medicationCodeMapper.canMap(medication.codes.get(0).code)) { continue; // skip codes that can't be mapped to NDC } long pdeId = BB2RIFExporter.pdeId.getAndDecrement(); int claimGroupId = BB2RIFExporter.claimGroupId.getAndDecrement(); fieldValues.clear(); staticFieldConfig.setValues(fieldValues, PrescriptionFields.class, person); // The REQUIRED fields fieldValues.put(PrescriptionFields.PDE_ID, "" + pdeId); fieldValues.put(PrescriptionFields.CLM_GRP_ID, "" + claimGroupId); fieldValues.put(PrescriptionFields.BENE_ID, (String) person.attributes.get(BB2_BENE_ID)); fieldValues.put(PrescriptionFields.SRVC_DT, bb2DateFromTimestamp(encounter.start)); fieldValues.put(PrescriptionFields.SRVC_PRVDR_ID, encounter.provider.id); fieldValues.put(PrescriptionFields.PRSCRBR_ID, "" + (9_999_999_999L - encounter.clinician.identifier)); fieldValues.put(PrescriptionFields.RX_SRVC_RFRNC_NUM, "" + pdeId); fieldValues.put(PrescriptionFields.PROD_SRVC_ID, medicationCodeMapper.map(medication.codes.get(0).code, person)); // The following field was replaced by the PartD contract ID, leaving this here for now // until this is validated // H=hmo, R=ppo, S=stand-alone, E=employer direct, X=limited income // fieldValues.put(PrescriptionFields.PLAN_CNTRCT_REC_ID, // ("R" + Math.abs( // UUID.fromString(medication.claim.payer.uuid) // .getMostSignificantBits())).substring(0, 5)); fieldValues.put(PrescriptionFields.PLAN_CNTRCT_REC_ID, partDContractID.toString()); fieldValues.put(PrescriptionFields.DAW_PROD_SLCTN_CD, "" + (int) person.rand(0, 9)); fieldValues.put(PrescriptionFields.QTY_DSPNSD_NUM, "" + getQuantity(medication, stopTime)); fieldValues.put(PrescriptionFields.DAYS_SUPLY_NUM, "" + getDays(medication, stopTime)); Integer fill = 1; if (fillNum.containsKey(medication.codes.get(0).code)) { fill = 1 + fillNum.get(medication.codes.get(0).code); } fillNum.put(medication.codes.get(0).code, fill); fieldValues.put(PrescriptionFields.FILL_NUM, "" + fill); int year = Utilities.getYear(medication.start); if (year != costYear) { costYear = year; costs = 0; } costs += medication.claim.getPatientCost(); if (costs <= 4550.00) { fieldValues.put(PrescriptionFields.GDC_BLW_OOPT_AMT, String.format("%.2f", costs)); fieldValues.put(PrescriptionFields.GDC_ABV_OOPT_AMT, "0"); } else { fieldValues.put(PrescriptionFields.GDC_BLW_OOPT_AMT, "4550.00"); fieldValues.put(PrescriptionFields.GDC_ABV_OOPT_AMT, String.format("%.2f", (costs - 4550))); } fieldValues.put(PrescriptionFields.PTNT_PAY_AMT, String.format("%.2f", medication.claim.getPatientCost())); fieldValues.put(PrescriptionFields.CVRD_D_PLAN_PD_AMT, String.format("%.2f", medication.claim.getCoveredCost())); fieldValues.put(PrescriptionFields.NCVRD_PLAN_PD_AMT, String.format("%.2f", medication.claim.getPatientCost())); fieldValues.put(PrescriptionFields.TOT_RX_CST_AMT, String.format("%.2f", medication.claim.getTotalClaimCost())); fieldValues.put(PrescriptionFields.PHRMCY_SRVC_TYPE_CD, "0" + (int) person.rand(1, 8)); fieldValues.put(PrescriptionFields.PD_DT, bb2DateFromTimestamp(encounter.start)); // 00=not specified, 01=home, 02=SNF, 03=long-term, 11=hospice, 14=homeless if (person.attributes.containsKey("homeless") && ((Boolean) person.attributes.get("homeless") == true)) { fieldValues.put(PrescriptionFields.PTNT_RSDNC_CD, "14"); } else { fieldValues.put(PrescriptionFields.PTNT_RSDNC_CD, "01"); } prescription.writeValues(PrescriptionFields.class, fieldValues); } } } /** * Export DME details for a single person. * @param person the person to export * @param stopTime end time of simulation * @throws IOException if something goes wrong */ private void exportDME(Person person, long stopTime) throws IOException { HashMap<DMEFields, String> fieldValues = new HashMap<>(); for (HealthRecord.Encounter encounter : person.record.encounters) { long claimId = BB2RIFExporter.claimId.getAndDecrement(); int claimGroupId = BB2RIFExporter.claimGroupId.getAndDecrement(); double latestHemoglobin = 0; for (HealthRecord.Observation observation : encounter.observations) { if (observation.containsCode("718-7", "http://loinc.org")) { latestHemoglobin = (double) observation.value; } } fieldValues.clear(); staticFieldConfig.setValues(fieldValues, DMEFields.class, person); // complex fields that could not easily be set using cms_field_values.tsv fieldValues.put(DMEFields.CLM_ID, "" + claimId); fieldValues.put(DMEFields.CLM_GRP_ID, "" + claimGroupId); fieldValues.put(DMEFields.BENE_ID, (String) person.attributes.get(BB2_BENE_ID)); fieldValues.put(DMEFields.LINE_HCT_HGB_RSLT_NUM, "" + latestHemoglobin); fieldValues.put(DMEFields.CARR_NUM, getCarrier(encounter.provider.state, CarrierFields.CARR_NUM)); fieldValues.put(DMEFields.NCH_WKLY_PROC_DT, bb2DateFromTimestamp(ExportHelper.nextFriday(encounter.stop))); fieldValues.put(DMEFields.PRVDR_NUM, encounter.provider.id); fieldValues.put(DMEFields.PRVDR_NPI, encounter.provider.npi); fieldValues.put(DMEFields.PRVDR_SPCLTY, ClinicianSpecialty.getCMSProviderSpecialtyCode( (String) encounter.clinician.attributes.get(Clinician.SPECIALTY))); fieldValues.put(DMEFields.PRVDR_STATE_CD, locationMapper.getStateCode(encounter.provider.state)); fieldValues.put(DMEFields.TAX_NUM, bb2TaxId((String)encounter.clinician.attributes.get(Person.IDENTIFIER_SSN))); fieldValues.put(DMEFields.DMERC_LINE_PRCNG_STATE_CD, locationMapper.getStateCode((String)person.attributes.get(Person.STATE))); fieldValues.put(DMEFields.LINE_1ST_EXPNS_DT, bb2DateFromTimestamp(encounter.start)); fieldValues.put(DMEFields.LINE_LAST_EXPNS_DT, bb2DateFromTimestamp(encounter.stop)); // OPTIONAL if (encounter.reason != null) { // If the encounter has a recorded reason, enter the mapped // values into the principle diagnoses code. if (conditionCodeMapper.canMap(encounter.reason.code)) { String icdCode = conditionCodeMapper.map(encounter.reason.code, person, true); fieldValues.put(DMEFields.PRNCPAL_DGNS_CD, icdCode); fieldValues.put(DMEFields.LINE_ICD_DGNS_CD, icdCode); } } // Use the active condition diagnoses to enter mapped values // into the diagnoses codes. List<String> mappedDiagnosisCodes = getDiagnosesCodes(person, encounter.stop); if (mappedDiagnosisCodes.isEmpty()) { continue; // skip this encounter } int smallest = Math.min(mappedDiagnosisCodes.size(), dmeDxFields.length); for (int i = 0; i < smallest; i++) { DMEFields[] dxField = dmeDxFields[i]; fieldValues.put(dxField[0], mappedDiagnosisCodes.get(i)); fieldValues.put(dxField[1], "0"); // 0=ICD10 } if (!fieldValues.containsKey(DMEFields.PRNCPAL_DGNS_CD)) { fieldValues.put(DMEFields.PRNCPAL_DGNS_CD, mappedDiagnosisCodes.get(0)); fieldValues.put(DMEFields.LINE_ICD_DGNS_CD, mappedDiagnosisCodes.get(0)); } synchronized (dme) { int lineNum = 1; for (ClaimEntry lineItem : encounter.claim.items) { if (!(lineItem.entry instanceof Device)) { continue; } Device device = (Device)lineItem.entry; if (!dmeCodeMapper.canMap(device.codes.get(0).code)) { System.err.println(" *** Possibly Missing DME Code: " + device.codes.get(0).code + " " + device.codes.get(0).display); continue; } fieldValues.put(DMEFields.CLM_FROM_DT, bb2DateFromTimestamp(device.start)); fieldValues.put(DMEFields.CLM_THRU_DT, bb2DateFromTimestamp(device.start)); fieldValues.put(DMEFields.HCPCS_CD, dmeCodeMapper.map(device.codes.get(0).code, person)); fieldValues.put(DMEFields.LINE_CMS_TYPE_SRVC_CD, dmeCodeMapper.map(device.codes.get(0).code, DMEFields.LINE_CMS_TYPE_SRVC_CD.toString().toLowerCase(), person)); fieldValues.put(DMEFields.LINE_BENE_PTB_DDCTBL_AMT, String.format("%.2f", lineItem.deductible)); fieldValues.put(DMEFields.LINE_COINSRNC_AMT, String.format("%.2f", lineItem.coinsurance)); fieldValues.put(DMEFields.LINE_BENE_PMT_AMT, String.format("%.2f", lineItem.copay + lineItem.deductible + lineItem.pocket)); fieldValues.put(DMEFields.LINE_PRVDR_PMT_AMT, String.format("%.2f", lineItem.coinsurance + lineItem.payer)); fieldValues.put(DMEFields.LINE_SBMTD_CHRG_AMT, String.format("%.2f", lineItem.cost)); fieldValues.put(DMEFields.LINE_ALOWD_CHRG_AMT, String.format("%.2f", lineItem.cost - lineItem.adjustment)); // set the line number and write out field values fieldValues.put(DMEFields.LINE_NUM, Integer.toString(lineNum++)); dme.writeValues(DMEFields.class, fieldValues); } } } } /** * Export Home Health Agency visits for a single person. * @param person the person to export * @param stopTime end time of simulation * @throws IOException if something goes wrong */ private void exportHome(Person person, long stopTime) throws IOException { HashMap<HHAFields, String> fieldValues = new HashMap<>(); int homeVisits = 0; for (HealthRecord.Encounter encounter : person.record.encounters) { if (!encounter.type.equals(EncounterType.HOME.toString())) { continue; } homeVisits += 1; long claimId = BB2RIFExporter.claimId.getAndDecrement(); int claimGroupId = BB2RIFExporter.claimGroupId.getAndDecrement(); fieldValues.clear(); staticFieldConfig.setValues(fieldValues, HHAFields.class, person); // The REQUIRED fields fieldValues.put(HHAFields.BENE_ID, (String) person.attributes.get(BB2_BENE_ID)); fieldValues.put(HHAFields.CLM_ID, "" + claimId); fieldValues.put(HHAFields.CLM_GRP_ID, "" + claimGroupId); fieldValues.put(HHAFields.CLM_FROM_DT, bb2DateFromTimestamp(encounter.start)); fieldValues.put(HHAFields.CLM_THRU_DT, bb2DateFromTimestamp(encounter.stop)); fieldValues.put(HHAFields.NCH_WKLY_PROC_DT, bb2DateFromTimestamp(ExportHelper.nextFriday(encounter.stop))); fieldValues.put(HHAFields.PRVDR_NUM, encounter.provider.id); fieldValues.put(HHAFields.ORG_NPI_NUM, encounter.provider.npi); fieldValues.put(HHAFields.AT_PHYSN_NPI, encounter.clinician.npi); fieldValues.put(HHAFields.RNDRNG_PHYSN_NPI, encounter.clinician.npi); fieldValues.put(HHAFields.CLM_PMT_AMT, String.format("%.2f", encounter.claim.getCoveredCost())); if (encounter.claim.payer == Payer.getGovernmentPayer("Medicare")) { fieldValues.put(HHAFields.NCH_PRMRY_PYR_CLM_PD_AMT, "0"); } else { fieldValues.put(HHAFields.NCH_PRMRY_PYR_CLM_PD_AMT, String.format("%.2f", encounter.claim.getCoveredCost())); } fieldValues.put(HHAFields.PRVDR_STATE_CD, locationMapper.getStateCode(encounter.provider.state)); fieldValues.put(HHAFields.CLM_TOT_CHRG_AMT, String.format("%.2f", encounter.claim.getTotalClaimCost())); fieldValues.put(HHAFields.CLM_HHA_TOT_VISIT_CNT, "" + homeVisits); int days = (int) ((encounter.stop - encounter.start) / (1000 * 60 * 60 * 24)); if (days <= 0) { days = 1; } fieldValues.put(HHAFields.REV_CNTR_UNIT_CNT, "" + days); fieldValues.put(HHAFields.REV_CNTR_RATE_AMT, String.format("%.2f", (encounter.claim.getTotalClaimCost() / days))); fieldValues.put(HHAFields.REV_CNTR_PMT_AMT_AMT, String.format("%.2f", encounter.claim.getCoveredCost())); fieldValues.put(HHAFields.REV_CNTR_TOT_CHRG_AMT, String.format("%.2f", encounter.claim.getTotalClaimCost())); fieldValues.put(HHAFields.REV_CNTR_NCVRD_CHRG_AMT, String.format("%.2f", encounter.claim.getPatientCost())); if (encounter.reason != null) { // If the encounter has a recorded reason, enter the mapped // values into the principle diagnoses code. if (conditionCodeMapper.canMap(encounter.reason.code)) { String icdCode = conditionCodeMapper.map(encounter.reason.code, person, true); fieldValues.put(HHAFields.PRNCPAL_DGNS_CD, icdCode); } } // Use the active condition diagnoses to enter mapped values // into the diagnoses codes. List<String> mappedDiagnosisCodes = getDiagnosesCodes(person, encounter.stop); if (mappedDiagnosisCodes.isEmpty()) { continue; // skip this encounter } int smallest = Math.min(mappedDiagnosisCodes.size(), homeDxFields.length); for (int i = 0; i < smallest; i++) { HHAFields[] dxField = homeDxFields[i]; fieldValues.put(dxField[0], mappedDiagnosisCodes.get(i)); fieldValues.put(dxField[1], "0"); // 0=ICD10 } if (!fieldValues.containsKey(HHAFields.PRNCPAL_DGNS_CD)) { fieldValues.put(HHAFields.PRNCPAL_DGNS_CD, mappedDiagnosisCodes.get(0)); } synchronized (home) { int claimLine = 1; for (ClaimEntry lineItem : encounter.claim.items) { String hcpcsCode = null; if (lineItem.entry instanceof HealthRecord.Procedure) { for (HealthRecord.Code code : lineItem.entry.codes) { if (hcpcsCodeMapper.canMap(code.code)) { hcpcsCode = hcpcsCodeMapper.map(code.code, person, true); break; // take the first mappable code for each procedure } } fieldValues.remove(HHAFields.REV_CNTR_NDC_QTY); fieldValues.remove(HHAFields.REV_CNTR_NDC_QTY_QLFR_CD); } else if (lineItem.entry instanceof HealthRecord.Medication) { HealthRecord.Medication med = (HealthRecord.Medication) lineItem.entry; if (med.administration) { hcpcsCode = "T1502"; // Administration of medication fieldValues.put(HHAFields.REV_CNTR_NDC_QTY, "1"); // 1 Unit fieldValues.put(HHAFields.REV_CNTR_NDC_QTY_QLFR_CD, "UN"); // Unit } } if (hcpcsCode == null) { continue; } fieldValues.put(HHAFields.CLM_LINE_NUM, Integer.toString(claimLine++)); fieldValues.put(HHAFields.REV_CNTR_DT, bb2DateFromTimestamp(lineItem.entry.start)); fieldValues.put(HHAFields.HCPCS_CD, hcpcsCode); fieldValues.put(HHAFields.REV_CNTR_RATE_AMT, String.format("%.2f", (lineItem.cost / Integer.max(1, days)))); fieldValues.put(HHAFields.REV_CNTR_PMT_AMT_AMT, String.format("%.2f", lineItem.coinsurance + lineItem.payer)); fieldValues.put(HHAFields.REV_CNTR_TOT_CHRG_AMT, String.format("%.2f", lineItem.cost)); fieldValues.put(HHAFields.REV_CNTR_NCVRD_CHRG_AMT, String.format("%.2f", lineItem.copay + lineItem.deductible + lineItem.pocket)); if (lineItem.pocket == 0 && lineItem.deductible == 0) { // Not subject to deductible or coinsurance fieldValues.put(HHAFields.REV_CNTR_DDCTBL_COINSRNC_CD, "3"); } else if (lineItem.pocket > 0 && lineItem.deductible > 0) { // Subject to deductible and coinsurance fieldValues.put(HHAFields.REV_CNTR_DDCTBL_COINSRNC_CD, "0"); } else if (lineItem.pocket == 0) { // Not subject to deductible fieldValues.put(HHAFields.REV_CNTR_DDCTBL_COINSRNC_CD, "1"); } else { // Not subject to coinsurance fieldValues.put(HHAFields.REV_CNTR_DDCTBL_COINSRNC_CD, "2"); } home.writeValues(HHAFields.class, fieldValues); } if (claimLine == 1) { // If claimLine still equals 1, then no line items were successfully added. // Add a single top-level entry. fieldValues.put(HHAFields.CLM_LINE_NUM, Integer.toString(claimLine)); fieldValues.put(HHAFields.REV_CNTR_DT, bb2DateFromTimestamp(encounter.start)); fieldValues.put(HHAFields.HCPCS_CD, "T1021"); // home health visit home.writeValues(HHAFields.class, fieldValues); } } } } /** * Export Home Health Agency visits for a single person. * @param person the person to export * @param stopTime end time of simulation * @throws IOException if something goes wrong */ private void exportHospice(Person person, long stopTime) throws IOException { HashMap<HospiceFields, String> fieldValues = new HashMap<>(); for (HealthRecord.Encounter encounter : person.record.encounters) { if (!encounter.type.equals(EncounterType.HOSPICE.toString())) { continue; } // Use the active condition diagnoses to enter mapped values // into the diagnoses codes. List<String> mappedDiagnosisCodes = getDiagnosesCodes(person, encounter.stop); if (mappedDiagnosisCodes.isEmpty()) { continue; // skip this encounter } long claimId = BB2RIFExporter.claimId.getAndDecrement(); int claimGroupId = BB2RIFExporter.claimGroupId.getAndDecrement(); fieldValues.clear(); staticFieldConfig.setValues(fieldValues, HospiceFields.class, person); fieldValues.put(HospiceFields.BENE_ID, (String) person.attributes.get(BB2_BENE_ID)); fieldValues.put(HospiceFields.CLM_ID, "" + claimId); fieldValues.put(HospiceFields.CLM_GRP_ID, "" + claimGroupId); fieldValues.put(HospiceFields.CLM_FROM_DT, bb2DateFromTimestamp(encounter.start)); fieldValues.put(HospiceFields.CLM_HOSPC_START_DT_ID, bb2DateFromTimestamp(encounter.start)); fieldValues.put(HospiceFields.CLM_THRU_DT, bb2DateFromTimestamp(encounter.stop)); fieldValues.put(HospiceFields.NCH_WKLY_PROC_DT, bb2DateFromTimestamp(ExportHelper.nextFriday(encounter.stop))); fieldValues.put(HospiceFields.PRVDR_NUM, encounter.provider.id); fieldValues.put(HospiceFields.AT_PHYSN_NPI, encounter.clinician.npi); fieldValues.put(HospiceFields.RNDRNG_PHYSN_NPI, encounter.clinician.npi); fieldValues.put(HospiceFields.ORG_NPI_NUM, encounter.provider.npi); fieldValues.put(HospiceFields.CLM_PMT_AMT, String.format("%.2f", encounter.claim.getTotalClaimCost())); if (encounter.claim.payer == Payer.getGovernmentPayer("Medicare")) { fieldValues.put(HospiceFields.NCH_PRMRY_PYR_CLM_PD_AMT, "0"); } else { fieldValues.put(HospiceFields.NCH_PRMRY_PYR_CLM_PD_AMT, String.format("%.2f", encounter.claim.getCoveredCost())); } fieldValues.put(HospiceFields.PRVDR_STATE_CD, locationMapper.getStateCode(encounter.provider.state)); // PTNT_DSCHRG_STUS_CD: 1=home, 2=transfer, 3=SNF, 20=died, 30=still here // NCH_PTNT_STUS_IND_CD: A = Discharged, B = Died, C = Still a patient String dischargeStatus = null; String patientStatus = null; String dischargeDate = null; if (encounter.ended) { dischargeStatus = "1"; // TODO 2=transfer if the next encounter is also inpatient patientStatus = "A"; // discharged dischargeDate = bb2DateFromTimestamp(ExportHelper.nextFriday(encounter.stop)); } else { dischargeStatus = "30"; // the patient is still here patientStatus = "C"; // still a patient } if (!person.alive(encounter.stop)) { dischargeStatus = "20"; // the patient died before the encounter ended patientStatus = "B"; // died dischargeDate = bb2DateFromTimestamp(ExportHelper.nextFriday(encounter.stop)); } fieldValues.put(HospiceFields.PTNT_DSCHRG_STUS_CD, dischargeStatus); fieldValues.put(HospiceFields.NCH_PTNT_STATUS_IND_CD, patientStatus); if (dischargeDate != null) { fieldValues.put(HospiceFields.NCH_BENE_DSCHRG_DT, dischargeDate); } fieldValues.put(HospiceFields.CLM_TOT_CHRG_AMT, String.format("%.2f", encounter.claim.getTotalClaimCost())); fieldValues.put(HospiceFields.REV_CNTR_TOT_CHRG_AMT, String.format("%.2f", encounter.claim.getCoveredCost())); fieldValues.put(HospiceFields.REV_CNTR_NCVRD_CHRG_AMT, String.format("%.2f", encounter.claim.getPatientCost())); fieldValues.put(HospiceFields.REV_CNTR_PMT_AMT_AMT, String.format("%.2f", encounter.claim.getCoveredCost())); if (encounter.reason != null) { // If the encounter has a recorded reason, enter the mapped // values into the principle diagnoses code. if (conditionCodeMapper.canMap(encounter.reason.code)) { String icdCode = conditionCodeMapper.map(encounter.reason.code, person, true); fieldValues.put(HospiceFields.PRNCPAL_DGNS_CD, icdCode); } } int smallest = Math.min(mappedDiagnosisCodes.size(), hospiceDxFields.length); for (int i = 0; i < smallest; i++) { HospiceFields[] dxField = hospiceDxFields[i]; fieldValues.put(dxField[0], mappedDiagnosisCodes.get(i)); fieldValues.put(dxField[1], "0"); // 0=ICD10 } if (!fieldValues.containsKey(HospiceFields.PRNCPAL_DGNS_CD)) { fieldValues.put(HospiceFields.PRNCPAL_DGNS_CD, mappedDiagnosisCodes.get(0)); } int days = (int) ((encounter.stop - encounter.start) / (1000 * 60 * 60 * 24)); if (days <= 0) { days = 1; } fieldValues.put(HospiceFields.CLM_UTLZTN_DAY_CNT, "" + days); int coinDays = days - 21; // first 21 days no coinsurance if (coinDays < 0) { coinDays = 0; } fieldValues.put(HospiceFields.REV_CNTR_UNIT_CNT, "" + days); fieldValues.put(HospiceFields.REV_CNTR_RATE_AMT, String.format("%.2f", (encounter.claim.getTotalClaimCost() / days))); synchronized (hospice) { int claimLine = 1; for (ClaimEntry lineItem : encounter.claim.items) { String hcpcsCode = null; if (lineItem.entry instanceof HealthRecord.Procedure) { for (HealthRecord.Code code : lineItem.entry.codes) { if (hcpcsCodeMapper.canMap(code.code)) { hcpcsCode = hcpcsCodeMapper.map(code.code, person, true); break; // take the first mappable code for each procedure } } fieldValues.remove(HospiceFields.REV_CNTR_NDC_QTY); fieldValues.remove(HospiceFields.REV_CNTR_NDC_QTY_QLFR_CD); } else if (lineItem.entry instanceof HealthRecord.Medication) { HealthRecord.Medication med = (HealthRecord.Medication) lineItem.entry; if (med.administration) { hcpcsCode = "T1502"; // Administration of medication fieldValues.put(HospiceFields.REV_CNTR_NDC_QTY, "1"); // 1 Unit fieldValues.put(HospiceFields.REV_CNTR_NDC_QTY_QLFR_CD, "UN"); // Unit } } if (hcpcsCode == null) { continue; } fieldValues.put(HospiceFields.CLM_LINE_NUM, Integer.toString(claimLine++)); fieldValues.put(HospiceFields.REV_CNTR_DT, bb2DateFromTimestamp(lineItem.entry.start)); fieldValues.put(HospiceFields.HCPCS_CD, hcpcsCode); fieldValues.put(HospiceFields.REV_CNTR_RATE_AMT, String.format("%.2f", (lineItem.cost / Integer.max(1, days)))); fieldValues.put(HospiceFields.REV_CNTR_PMT_AMT_AMT, String.format("%.2f", lineItem.coinsurance + lineItem.payer)); fieldValues.put(HospiceFields.REV_CNTR_TOT_CHRG_AMT, String.format("%.2f", lineItem.cost)); fieldValues.put(HospiceFields.REV_CNTR_NCVRD_CHRG_AMT, String.format("%.2f", lineItem.copay + lineItem.deductible + lineItem.pocket)); if (lineItem.pocket == 0 && lineItem.deductible == 0) { // Not subject to deductible or coinsurance fieldValues.put(HospiceFields.REV_CNTR_DDCTBL_COINSRNC_CD, "3"); } else if (lineItem.pocket > 0 && lineItem.deductible > 0) { // Subject to deductible and coinsurance fieldValues.put(HospiceFields.REV_CNTR_DDCTBL_COINSRNC_CD, "0"); } else if (lineItem.pocket == 0) { // Not subject to deductible fieldValues.put(HospiceFields.REV_CNTR_DDCTBL_COINSRNC_CD, "1"); } else { // Not subject to coinsurance fieldValues.put(HospiceFields.REV_CNTR_DDCTBL_COINSRNC_CD, "2"); } hospice.writeValues(HospiceFields.class, fieldValues); } if (claimLine == 1) { // If claimLine still equals 1, then no line items were successfully added. // Add a single top-level entry. fieldValues.put(HospiceFields.CLM_LINE_NUM, Integer.toString(claimLine)); fieldValues.put(HospiceFields.REV_CNTR_DT, bb2DateFromTimestamp(encounter.start)); fieldValues.put(HospiceFields.HCPCS_CD, "S9126"); // hospice per diem hospice.writeValues(HospiceFields.class, fieldValues); } } } } /** * Export Home Health Agency visits for a single person. * @param person the person to export * @param stopTime end time of simulation * @throws IOException if something goes wrong */ private void exportSNF(Person person, long stopTime) throws IOException { HashMap<SNFFields, String> fieldValues = new HashMap<>(); boolean previousEmergency; boolean previousUrgent; for (HealthRecord.Encounter encounter : person.record.encounters) { previousEmergency = encounter.type.equals(EncounterType.EMERGENCY.toString()); previousUrgent = encounter.type.equals(EncounterType.URGENTCARE.toString()); if (!encounter.type.equals(EncounterType.SNF.toString())) { continue; } long claimId = BB2RIFExporter.claimId.getAndDecrement(); int claimGroupId = BB2RIFExporter.claimGroupId.getAndDecrement(); fieldValues.clear(); staticFieldConfig.setValues(fieldValues, SNFFields.class, person); // The REQUIRED Fields fieldValues.put(SNFFields.BENE_ID, (String) person.attributes.get(BB2_BENE_ID)); fieldValues.put(SNFFields.CLM_ID, "" + claimId); fieldValues.put(SNFFields.CLM_GRP_ID, "" + claimGroupId); fieldValues.put(SNFFields.CLM_FROM_DT, bb2DateFromTimestamp(encounter.start)); fieldValues.put(SNFFields.CLM_THRU_DT, bb2DateFromTimestamp(encounter.stop)); fieldValues.put(SNFFields.NCH_WKLY_PROC_DT, bb2DateFromTimestamp(ExportHelper.nextFriday(encounter.stop))); fieldValues.put(SNFFields.PRVDR_NUM, encounter.provider.id); fieldValues.put(SNFFields.ORG_NPI_NUM, encounter.provider.npi); fieldValues.put(SNFFields.AT_PHYSN_NPI, encounter.clinician.npi); fieldValues.put(SNFFields.RNDRNG_PHYSN_NPI, encounter.clinician.npi); fieldValues.put(SNFFields.CLM_PMT_AMT, String.format("%.2f", encounter.claim.getCoveredCost())); if (encounter.claim.payer == Payer.getGovernmentPayer("Medicare")) { fieldValues.put(SNFFields.NCH_PRMRY_PYR_CLM_PD_AMT, "0"); } else { fieldValues.put(SNFFields.NCH_PRMRY_PYR_CLM_PD_AMT, String.format("%.2f", encounter.claim.getCoveredCost())); } fieldValues.put(SNFFields.PRVDR_STATE_CD, locationMapper.getStateCode(encounter.provider.state)); fieldValues.put(SNFFields.CLM_TOT_CHRG_AMT, String.format("%.2f", encounter.claim.getTotalClaimCost())); if (previousEmergency) { fieldValues.put(SNFFields.CLM_IP_ADMSN_TYPE_CD, "1"); } else if (previousUrgent) { fieldValues.put(SNFFields.CLM_IP_ADMSN_TYPE_CD, "2"); } else { fieldValues.put(SNFFields.CLM_IP_ADMSN_TYPE_CD, "3"); } fieldValues.put(SNFFields.NCH_BENE_IP_DDCTBL_AMT, String.format("%.2f", encounter.claim.getDeductiblePaid())); fieldValues.put(SNFFields.NCH_BENE_PTA_COINSRNC_LBLTY_AM, String.format("%.2f", encounter.claim.getCoinsurancePaid())); fieldValues.put(SNFFields.NCH_IP_NCVRD_CHRG_AMT, String.format("%.2f", encounter.claim.getPatientCost())); fieldValues.put(SNFFields.NCH_IP_TOT_DDCTN_AMT, String.format("%.2f", encounter.claim.getDeductiblePaid() + encounter.claim.getCoinsurancePaid())); int days = (int) ((encounter.stop - encounter.start) / (1000 * 60 * 60 * 24)); if (days <= 0) { days = 1; } fieldValues.put(SNFFields.CLM_UTLZTN_DAY_CNT, "" + days); int coinDays = days - 21; // first 21 days no coinsurance if (coinDays < 0) { coinDays = 0; } fieldValues.put(SNFFields.BENE_TOT_COINSRNC_DAYS_CNT, "" + coinDays); fieldValues.put(SNFFields.REV_CNTR_UNIT_CNT, "" + days); fieldValues.put(SNFFields.REV_CNTR_RATE_AMT, String.format("%.2f", (encounter.claim.getTotalClaimCost() / days))); fieldValues.put(SNFFields.REV_CNTR_TOT_CHRG_AMT, String.format("%.2f", encounter.claim.getTotalClaimCost())); fieldValues.put(SNFFields.REV_CNTR_NCVRD_CHRG_AMT, String.format("%.2f", encounter.claim.getPatientCost())); // OPTIONAL CODES if (encounter.reason != null) { // If the encounter has a recorded reason, enter the mapped // values into the principle diagnoses code. if (conditionCodeMapper.canMap(encounter.reason.code)) { String icdCode = conditionCodeMapper.map(encounter.reason.code, person, true); fieldValues.put(SNFFields.PRNCPAL_DGNS_CD, icdCode); fieldValues.put(SNFFields.ADMTG_DGNS_CD, icdCode); } } // Use the active condition diagnoses to enter mapped values // into the diagnoses codes. List<String> mappedDiagnosisCodes = getDiagnosesCodes(person, encounter.stop); boolean noDiagnoses = mappedDiagnosisCodes.isEmpty(); if (!noDiagnoses) { int smallest = Math.min(mappedDiagnosisCodes.size(), snfDxFields.length); for (int i = 0; i < smallest; i++) { SNFFields[] dxField = snfDxFields[i]; fieldValues.put(dxField[0], mappedDiagnosisCodes.get(i)); fieldValues.put(dxField[1], "0"); // 0=ICD10 } if (!fieldValues.containsKey(SNFFields.PRNCPAL_DGNS_CD)) { fieldValues.put(SNFFields.PRNCPAL_DGNS_CD, mappedDiagnosisCodes.get(0)); fieldValues.put(SNFFields.ADMTG_DGNS_CD, mappedDiagnosisCodes.get(0)); } } // Use the procedures in this encounter to enter mapped values boolean noProcedures = false; if (!encounter.procedures.isEmpty()) { List<HealthRecord.Procedure> mappableProcedures = new ArrayList<>(); List<String> mappedProcedureCodes = new ArrayList<>(); for (HealthRecord.Procedure procedure : encounter.procedures) { for (HealthRecord.Code code : procedure.codes) { if (conditionCodeMapper.canMap(code.code)) { mappableProcedures.add(procedure); mappedProcedureCodes.add(conditionCodeMapper.map(code.code, person, true)); break; // take the first mappable code for each procedure } } } if (!mappableProcedures.isEmpty()) { int smallest = Math.min(mappableProcedures.size(), snfPxFields.length); for (int i = 0; i < smallest; i++) { SNFFields[] pxField = snfPxFields[i]; fieldValues.put(pxField[0], mappedProcedureCodes.get(i)); fieldValues.put(pxField[1], "0"); // 0=ICD10 fieldValues.put(pxField[2], bb2DateFromTimestamp(mappableProcedures.get(i).start)); } } else { noProcedures = true; } } if (noDiagnoses && noProcedures) { continue; // skip this encounter } synchronized (snf) { int claimLine = 1; for (ClaimEntry lineItem : encounter.claim.items) { String hcpcsCode = null; if (lineItem.entry instanceof HealthRecord.Procedure) { for (HealthRecord.Code code : lineItem.entry.codes) { if (hcpcsCodeMapper.canMap(code.code)) { hcpcsCode = hcpcsCodeMapper.map(code.code, person, true); break; // take the first mappable code for each procedure } } fieldValues.remove(SNFFields.REV_CNTR_NDC_QTY); fieldValues.remove(SNFFields.REV_CNTR_NDC_QTY_QLFR_CD); } else if (lineItem.entry instanceof HealthRecord.Medication) { HealthRecord.Medication med = (HealthRecord.Medication) lineItem.entry; if (med.administration) { hcpcsCode = "T1502"; // Administration of medication fieldValues.put(SNFFields.REV_CNTR_NDC_QTY, "1"); // 1 Unit fieldValues.put(SNFFields.REV_CNTR_NDC_QTY_QLFR_CD, "UN"); // Unit } } if (hcpcsCode == null) { continue; } fieldValues.put(SNFFields.CLM_LINE_NUM, Integer.toString(claimLine++)); fieldValues.put(SNFFields.HCPCS_CD, hcpcsCode); fieldValues.put(SNFFields.REV_CNTR_RATE_AMT, String.format("%.2f", (lineItem.cost / Integer.max(1, days)))); fieldValues.put(SNFFields.REV_CNTR_TOT_CHRG_AMT, String.format("%.2f", lineItem.cost)); fieldValues.put(SNFFields.REV_CNTR_NCVRD_CHRG_AMT, String.format("%.2f", lineItem.copay + lineItem.deductible + lineItem.pocket)); if (lineItem.pocket == 0 && lineItem.deductible == 0) { // Not subject to deductible or coinsurance fieldValues.put(SNFFields.REV_CNTR_DDCTBL_COINSRNC_CD, "3"); } else if (lineItem.pocket > 0 && lineItem.deductible > 0) { // Subject to deductible and coinsurance fieldValues.put(SNFFields.REV_CNTR_DDCTBL_COINSRNC_CD, "0"); } else if (lineItem.pocket == 0) { // Not subject to deductible fieldValues.put(SNFFields.REV_CNTR_DDCTBL_COINSRNC_CD, "1"); } else { // Not subject to coinsurance fieldValues.put(SNFFields.REV_CNTR_DDCTBL_COINSRNC_CD, "2"); } snf.writeValues(SNFFields.class, fieldValues); } if (claimLine == 1) { // If claimLine still equals 1, then no line items were successfully added. // Add a single top-level entry. fieldValues.put(SNFFields.CLM_LINE_NUM, Integer.toString(claimLine)); fieldValues.put(SNFFields.HCPCS_CD, "G0299"); snf.writeValues(SNFFields.class, fieldValues); } } } } /** * Get the BB2 race code. BB2 uses a single code to represent race and ethnicity, we assume * ethnicity gets priority here. * @param ethnicity the Synthea ethnicity * @param race the Synthea race * @return the BB2 race code */ public static String bb2RaceCode(String ethnicity, String race) { if ("hispanic".equals(ethnicity)) { return "5"; } else { String bbRaceCode; // unknown switch (race) { case "white": bbRaceCode = "1"; break; case "black": bbRaceCode = "2"; break; case "asian": bbRaceCode = "4"; break; case "native": bbRaceCode = "6"; break; case "other": default: bbRaceCode = "3"; break; } return bbRaceCode; } } private int getQuantity(Medication medication, long stopTime) { double amountPerDay = 1; double days = getDays(medication, stopTime); if (medication.prescriptionDetails != null && medication.prescriptionDetails.has("dosage")) { JsonObject dosage = medication.prescriptionDetails.getAsJsonObject("dosage"); long amount = dosage.get("amount").getAsLong(); long frequency = dosage.get("frequency").getAsLong(); long period = dosage.get("period").getAsLong(); String units = dosage.get("unit").getAsString(); long periodTime = Utilities.convertTime(units, period); long perPeriod = amount * frequency; amountPerDay = (double) ((double) (perPeriod * periodTime) / (1000.0 * 60 * 60 * 24)); if (amountPerDay == 0) { amountPerDay = 1; } } return (int) (amountPerDay * days); } private int getDays(Medication medication, long stopTime) { double days = 1; long stop = medication.stop; if (stop == 0L) { stop = stopTime; } long medDuration = stop - medication.start; days = (double) (medDuration / (1000 * 60 * 60 * 24)); if (medication.prescriptionDetails != null && medication.prescriptionDetails.has("duration")) { JsonObject duration = medication.prescriptionDetails.getAsJsonObject("duration"); long quantity = duration.get("quantity").getAsLong(); String unit = duration.get("unit").getAsString(); long durationTime = Utilities.convertTime(unit, quantity); double durationTimeInDays = (double) (durationTime / (1000 * 60 * 60 * 24)); if (durationTimeInDays > days) { days = durationTimeInDays; } } return (int) days; } /** * Utility class for converting state names and abbreviations to provider state codes. */ class StateCodeMapper { private final HashMap<String, String> providerStateCodes; private Map<String, String> stateToAbbrev = this.buildStateAbbrevTable(); private final Map<String, String> abbrevToState; private final HashMap<String, String> ssaTable; public StateCodeMapper() { this.providerStateCodes = this.buildProviderStateTable(); this.stateToAbbrev = this.buildStateAbbrevTable(); // support two-way conversion between state name and abbreviations this.abbrevToState = new HashMap<>(); for (Map.Entry<String, String> entry : stateToAbbrev.entrySet()) { this.abbrevToState.put(entry.getValue(), entry.getKey()); } this.ssaTable = buildSSATable(); } /** * Return state code for a given state. * @param state (either state name or abbreviation) * @return 2-digit state code */ String getStateCode(String state) { if (state.length() == 2) { state = this.changeStateFormat(state); } else { state = this.capitalizeWords(state); } String res = this.providerStateCodes.getOrDefault(state, "NONE"); return res; } /** * Switch between state name and abbreviation. If state is abbreviation, will return name, * and vice versa * @param state abbreviation or name of state * @return */ private String changeStateFormat(String state) { if (state.length() == 2) { return this.abbrevToState.getOrDefault(state.toUpperCase(), null); } else { String stateClean = this.capitalizeWords(state.toLowerCase()); return this.stateToAbbrev.getOrDefault(stateClean, null); } } private Map<String, String> buildStateAbbrevTable() { Map<String, String> states = new HashMap<String, String>(); states.put("Alabama","AL"); states.put("Alaska","AK"); states.put("Alberta","AB"); states.put("American Samoa","AS"); states.put("Arizona","AZ"); states.put("Arkansas","AR"); states.put("Armed Forces (AE)","AE"); states.put("Armed Forces Americas","AA"); states.put("Armed Forces Pacific","AP"); states.put("British Columbia","BC"); states.put("California","CA"); states.put("Colorado","CO"); states.put("Connecticut","CT"); states.put("Delaware","DE"); states.put("District Of Columbia","DC"); states.put("Florida","FL"); states.put("Georgia","GA"); states.put("Guam","GU"); states.put("Hawaii","HI"); states.put("Idaho","ID"); states.put("Illinois","IL"); states.put("Indiana","IN"); states.put("Iowa","IA"); states.put("Kansas","KS"); states.put("Kentucky","KY"); states.put("Louisiana","LA"); states.put("Maine","ME"); states.put("Manitoba","MB"); states.put("Maryland","MD"); states.put("Massachusetts","MA"); states.put("Michigan","MI"); states.put("Minnesota","MN"); states.put("Mississippi","MS"); states.put("Missouri","MO"); states.put("Montana","MT"); states.put("Nebraska","NE"); states.put("Nevada","NV"); states.put("New Brunswick","NB"); states.put("New Hampshire","NH"); states.put("New Jersey","NJ"); states.put("New Mexico","NM"); states.put("New York","NY"); states.put("Newfoundland","NF"); states.put("North Carolina","NC"); states.put("North Dakota","ND"); states.put("Northwest Territories","NT"); states.put("Nova Scotia","NS"); states.put("Nunavut","NU"); states.put("Ohio","OH"); states.put("Oklahoma","OK"); states.put("Ontario","ON"); states.put("Oregon","OR"); states.put("Pennsylvania","PA"); states.put("Prince Edward Island","PE"); states.put("Puerto Rico","PR"); states.put("Quebec","QC"); states.put("Rhode Island","RI"); states.put("Saskatchewan","SK"); states.put("South Carolina","SC"); states.put("South Dakota","SD"); states.put("Tennessee","TN"); states.put("Texas","TX"); states.put("Utah","UT"); states.put("Vermont","VT"); states.put("Virgin Islands","VI"); states.put("Virginia","VA"); states.put("Washington","WA"); states.put("West Virginia","WV"); states.put("Wisconsin","WI"); states.put("Wyoming","WY"); states.put("Yukon Territory","YT"); return states; } private HashMap<String, String> buildProviderStateTable() { HashMap<String, String> providerStateCode = new HashMap<String, String>(); providerStateCode.put("Alabama", "01"); providerStateCode.put("Alaska", "02"); providerStateCode.put("Arizona", "03"); providerStateCode.put("Arkansas", "04"); providerStateCode.put("California", "05"); providerStateCode.put("Colorado", "06"); providerStateCode.put("Connecticut", "07"); providerStateCode.put("Delaware", "08"); providerStateCode.put("District of Columbia", "09"); providerStateCode.put("Florida", "10"); providerStateCode.put("Georgia", "11"); providerStateCode.put("Hawaii", "12"); providerStateCode.put("Idaho", "13"); providerStateCode.put("Illinois", "14"); providerStateCode.put("Indiana", "15"); providerStateCode.put("Iowa", "16"); providerStateCode.put("Kansas", "17"); providerStateCode.put("Kentucky", "18"); providerStateCode.put("Louisiana", "19"); providerStateCode.put("Maine", "20"); providerStateCode.put("Maryland", "21"); providerStateCode.put("Massachusetts", "22"); providerStateCode.put("Michigan", "23"); providerStateCode.put("Minnesota", "24"); providerStateCode.put("Mississippi", "25"); providerStateCode.put("Missouri", "26"); providerStateCode.put("Montana", "27"); providerStateCode.put("Nebraska", "28"); providerStateCode.put("Nevada", "29"); providerStateCode.put("New Hampshire", "30"); providerStateCode.put("New Jersey", "31"); providerStateCode.put("New Mexico", "32"); providerStateCode.put("New York", "33"); providerStateCode.put("North Carolina", "34"); providerStateCode.put("North Dakota", "35"); providerStateCode.put("Ohio", "36"); providerStateCode.put("Oklahoma", "37"); providerStateCode.put("Oregon", "38"); providerStateCode.put("Pennsylvania", "39"); providerStateCode.put("Puerto Rico", "40"); providerStateCode.put("Rhode Island", "41"); providerStateCode.put("South Carolina", "42"); providerStateCode.put("South Dakota", "43"); providerStateCode.put("Tennessee", "44"); providerStateCode.put("Texas", "45"); providerStateCode.put("Utah", "46"); providerStateCode.put("Vermont", "47"); providerStateCode.put("Virgin Islands", "48"); providerStateCode.put("Virginia", "49"); providerStateCode.put("Washington", "50"); providerStateCode.put("West Virginia", "51"); providerStateCode.put("Wisconsin", "52"); providerStateCode.put("Wyoming", "53"); providerStateCode.put("Africa", "54"); providerStateCode.put("California", "55"); providerStateCode.put("Canada & Islands", "56"); providerStateCode.put("Central America and West Indies", "57"); providerStateCode.put("Europe", "58"); providerStateCode.put("Mexico", "59"); providerStateCode.put("Oceania", "60"); providerStateCode.put("Philippines", "61"); providerStateCode.put("South America", "62"); providerStateCode.put("U.S. Possessions", "63"); providerStateCode.put("American Samoa", "64"); providerStateCode.put("Guam", "65"); providerStateCode.put("Commonwealth of the Northern Marianas Islands", "66"); return providerStateCode; } /** * Get the SSA county code for a given zipcode. Will eventually use countyname, but wanted * to use a unique key * @param zipcode the ZIP * @return */ private String zipToCountyCode(String zipcode) { // TODO: fix this. Currently hard-coding default because required field, but will // eventually add name-based matching as fallback return ssaTable.getOrDefault(zipcode, "22090"); } private HashMap<String, String> buildSSATable() { HashMap<String, String> ssaTable = new HashMap<String, String>(); List<LinkedHashMap<String, String>> csvData; try { String csv = Utilities.readResourceAndStripBOM("geography/fipscodes.csv"); csvData = SimpleCSV.parse(csv); } catch (IOException e) { throw new RuntimeException(e); } for (LinkedHashMap<String, String> row : csvData) { String zipcode = row.get("zip"); if (zipcode.length() > 3) { if (zipcode.length() == 4) { zipcode = "0" + zipcode; } } String ssaCode = row.get("ssacounty"); ssaTable.put(zipcode, ssaCode); } return ssaTable; } private String capitalizeWords(String str) { String[] words = str.split("\\s"); String capitalizeWords = ""; for (String w: words) { String first = w.substring(0,1); String afterFirst = w.substring(1); capitalizeWords += first.toUpperCase() + afterFirst + " "; } return capitalizeWords.trim(); } } /** * Defines the fields used in the beneficiary file. Note that order is significant, columns will * be written in the order specified. * Note also that it is package accessible, since it is used in BFDExportBuilder */ enum BeneficiaryFields { DML_IND, BENE_ID, STATE_CODE, BENE_COUNTY_CD, BENE_ZIP_CD, BENE_BIRTH_DT, BENE_SEX_IDENT_CD, BENE_RACE_CD, BENE_ENTLMT_RSN_ORIG, BENE_ENTLMT_RSN_CURR, BENE_ESRD_IND, BENE_MDCR_STATUS_CD, BENE_PTA_TRMNTN_CD, BENE_PTB_TRMNTN_CD, // BENE_PTD_TRMNTN_CD, // The spreadsheet has a gap for this column, examples do not include it BENE_CRNT_HIC_NUM, BENE_SRNM_NAME, BENE_GVN_NAME, BENE_MDL_NAME, MBI_NUM, DEATH_DT, RFRNC_YR, A_MO_CNT, B_MO_CNT, BUYIN_MO_CNT, HMO_MO_CNT, RDS_MO_CNT, ENRL_SRC, SAMPLE_GROUP, EFIVEPCT, CRNT_BIC, AGE, COVSTART, DUAL_MO_CNT, FIPS_STATE_CNTY_JAN_CD, FIPS_STATE_CNTY_FEB_CD, FIPS_STATE_CNTY_MAR_CD, FIPS_STATE_CNTY_APR_CD, FIPS_STATE_CNTY_MAY_CD, FIPS_STATE_CNTY_JUN_CD, FIPS_STATE_CNTY_JUL_CD, FIPS_STATE_CNTY_AUG_CD, FIPS_STATE_CNTY_SEPT_CD, FIPS_STATE_CNTY_OCT_CD, FIPS_STATE_CNTY_NOV_CD, FIPS_STATE_CNTY_DEC_CD, V_DOD_SW, RTI_RACE_CD, MDCR_STUS_JAN_CD, MDCR_STUS_FEB_CD, MDCR_STUS_MAR_CD, MDCR_STUS_APR_CD, MDCR_STUS_MAY_CD, MDCR_STUS_JUN_CD, MDCR_STUS_JUL_CD, MDCR_STUS_AUG_CD, MDCR_STUS_SEPT_CD, MDCR_STUS_OCT_CD, MDCR_STUS_NOV_CD, MDCR_STUS_DEC_CD, PLAN_CVRG_MO_CNT, MDCR_ENTLMT_BUYIN_1_IND, MDCR_ENTLMT_BUYIN_2_IND, MDCR_ENTLMT_BUYIN_3_IND, MDCR_ENTLMT_BUYIN_4_IND, MDCR_ENTLMT_BUYIN_5_IND, MDCR_ENTLMT_BUYIN_6_IND, MDCR_ENTLMT_BUYIN_7_IND, MDCR_ENTLMT_BUYIN_8_IND, MDCR_ENTLMT_BUYIN_9_IND, MDCR_ENTLMT_BUYIN_10_IND, MDCR_ENTLMT_BUYIN_11_IND, MDCR_ENTLMT_BUYIN_12_IND, HMO_1_IND, HMO_2_IND, HMO_3_IND, HMO_4_IND, HMO_5_IND, HMO_6_IND, HMO_7_IND, HMO_8_IND, HMO_9_IND, HMO_10_IND, HMO_11_IND, HMO_12_IND, PTC_CNTRCT_JAN_ID, PTC_CNTRCT_FEB_ID, PTC_CNTRCT_MAR_ID, PTC_CNTRCT_APR_ID, PTC_CNTRCT_MAY_ID, PTC_CNTRCT_JUN_ID, PTC_CNTRCT_JUL_ID, PTC_CNTRCT_AUG_ID, PTC_CNTRCT_SEPT_ID, PTC_CNTRCT_OCT_ID, PTC_CNTRCT_NOV_ID, PTC_CNTRCT_DEC_ID, PTC_PBP_JAN_ID, PTC_PBP_FEB_ID, PTC_PBP_MAR_ID, PTC_PBP_APR_ID, PTC_PBP_MAY_ID, PTC_PBP_JUN_ID, PTC_PBP_JUL_ID, PTC_PBP_AUG_ID, PTC_PBP_SEPT_ID, PTC_PBP_OCT_ID, PTC_PBP_NOV_ID, PTC_PBP_DEC_ID, PTC_PLAN_TYPE_JAN_CD, PTC_PLAN_TYPE_FEB_CD, PTC_PLAN_TYPE_MAR_CD, PTC_PLAN_TYPE_APR_CD, PTC_PLAN_TYPE_MAY_CD, PTC_PLAN_TYPE_JUN_CD, PTC_PLAN_TYPE_JUL_CD, PTC_PLAN_TYPE_AUG_CD, PTC_PLAN_TYPE_SEPT_CD, PTC_PLAN_TYPE_OCT_CD, PTC_PLAN_TYPE_NOV_CD, PTC_PLAN_TYPE_DEC_CD, PTD_CNTRCT_JAN_ID, PTD_CNTRCT_FEB_ID, PTD_CNTRCT_MAR_ID, PTD_CNTRCT_APR_ID, PTD_CNTRCT_MAY_ID, PTD_CNTRCT_JUN_ID, PTD_CNTRCT_JUL_ID, PTD_CNTRCT_AUG_ID, PTD_CNTRCT_SEPT_ID, PTD_CNTRCT_OCT_ID, PTD_CNTRCT_NOV_ID, PTD_CNTRCT_DEC_ID, PTD_PBP_JAN_ID, PTD_PBP_FEB_ID, PTD_PBP_MAR_ID, PTD_PBP_APR_ID, PTD_PBP_MAY_ID, PTD_PBP_JUN_ID, PTD_PBP_JUL_ID, PTD_PBP_AUG_ID, PTD_PBP_SEPT_ID, PTD_PBP_OCT_ID, PTD_PBP_NOV_ID, PTD_PBP_DEC_ID, PTD_SGMT_JAN_ID, PTD_SGMT_FEB_ID, PTD_SGMT_MAR_ID, PTD_SGMT_APR_ID, PTD_SGMT_MAY_ID, PTD_SGMT_JUN_ID, PTD_SGMT_JUL_ID, PTD_SGMT_AUG_ID, PTD_SGMT_SEPT_ID, PTD_SGMT_OCT_ID, PTD_SGMT_NOV_ID, PTD_SGMT_DEC_ID, RDS_JAN_IND, RDS_FEB_IND, RDS_MAR_IND, RDS_APR_IND, RDS_MAY_IND, RDS_JUN_IND, RDS_JUL_IND, RDS_AUG_IND, RDS_SEPT_IND, RDS_OCT_IND, RDS_NOV_IND, RDS_DEC_IND, META_DUAL_ELGBL_STUS_JAN_CD, META_DUAL_ELGBL_STUS_FEB_CD, META_DUAL_ELGBL_STUS_MAR_CD, META_DUAL_ELGBL_STUS_APR_CD, META_DUAL_ELGBL_STUS_MAY_CD, META_DUAL_ELGBL_STUS_JUN_CD, META_DUAL_ELGBL_STUS_JUL_CD, META_DUAL_ELGBL_STUS_AUG_CD, META_DUAL_ELGBL_STUS_SEPT_CD, META_DUAL_ELGBL_STUS_OCT_CD, META_DUAL_ELGBL_STUS_NOV_CD, META_DUAL_ELGBL_STUS_DEC_CD, CST_SHR_GRP_JAN_CD, CST_SHR_GRP_FEB_CD, CST_SHR_GRP_MAR_CD, CST_SHR_GRP_APR_CD, CST_SHR_GRP_MAY_CD, CST_SHR_GRP_JUN_CD, CST_SHR_GRP_JUL_CD, CST_SHR_GRP_AUG_CD, CST_SHR_GRP_SEPT_CD, CST_SHR_GRP_OCT_CD, CST_SHR_GRP_NOV_CD, CST_SHR_GRP_DEC_CD, DRVD_LINE_1_ADR, DRVD_LINE_2_ADR, DRVD_LINE_3_ADR, DRVD_LINE_4_ADR, DRVD_LINE_5_ADR, DRVD_LINE_6_ADR, CITY_NAME, STATE_CD, STATE_CNTY_ZIP_CD, EFCTV_BGN_DT, EFCTV_END_DT, BENE_LINK_KEY } private final BeneficiaryFields[] beneficiaryPartDContractFields = { BeneficiaryFields.PTD_CNTRCT_JAN_ID, BeneficiaryFields.PTD_CNTRCT_FEB_ID, BeneficiaryFields.PTD_CNTRCT_MAR_ID, BeneficiaryFields.PTD_CNTRCT_APR_ID, BeneficiaryFields.PTD_CNTRCT_MAY_ID, BeneficiaryFields.PTD_CNTRCT_JUN_ID, BeneficiaryFields.PTD_CNTRCT_JUL_ID, BeneficiaryFields.PTD_CNTRCT_AUG_ID, BeneficiaryFields.PTD_CNTRCT_SEPT_ID, BeneficiaryFields.PTD_CNTRCT_OCT_ID, BeneficiaryFields.PTD_CNTRCT_NOV_ID, BeneficiaryFields.PTD_CNTRCT_DEC_ID }; /* package access */ enum BeneficiaryHistoryFields { DML_IND, BENE_ID, STATE_CODE, BENE_COUNTY_CD, BENE_ZIP_CD, BENE_BIRTH_DT, BENE_SEX_IDENT_CD, BENE_RACE_CD, BENE_ENTLMT_RSN_ORIG, BENE_ENTLMT_RSN_CURR, BENE_ESRD_IND, BENE_MDCR_STATUS_CD, BENE_PTA_TRMNTN_CD, BENE_PTB_TRMNTN_CD, BENE_CRNT_HIC_NUM, BENE_SRNM_NAME, BENE_GVN_NAME, BENE_MDL_NAME, MBI_NUM, EFCTV_BGN_DT, EFCTV_END_DT } enum OutpatientFields { DML_IND, BENE_ID, CLM_ID, CLM_GRP_ID, FINAL_ACTION, NCH_NEAR_LINE_REC_IDENT_CD, NCH_CLM_TYPE_CD, CLM_FROM_DT, CLM_THRU_DT, NCH_WKLY_PROC_DT, FI_CLM_PROC_DT, CLAIM_QUERY_CODE, PRVDR_NUM, CLM_FAC_TYPE_CD, CLM_SRVC_CLSFCTN_TYPE_CD, CLM_FREQ_CD, FI_NUM, CLM_MDCR_NON_PMT_RSN_CD, CLM_PMT_AMT, NCH_PRMRY_PYR_CLM_PD_AMT, NCH_PRMRY_PYR_CD, PRVDR_STATE_CD, ORG_NPI_NUM, AT_PHYSN_UPIN, AT_PHYSN_NPI, OP_PHYSN_UPIN, OP_PHYSN_NPI, OT_PHYSN_UPIN, OT_PHYSN_NPI, CLM_MCO_PD_SW, PTNT_DSCHRG_STUS_CD, CLM_TOT_CHRG_AMT, NCH_BENE_BLOOD_DDCTBL_LBLTY_AM, NCH_PROFNL_CMPNT_CHRG_AMT, PRNCPAL_DGNS_CD, PRNCPAL_DGNS_VRSN_CD, ICD_DGNS_CD1, ICD_DGNS_VRSN_CD1, ICD_DGNS_CD2, ICD_DGNS_VRSN_CD2, ICD_DGNS_CD3, ICD_DGNS_VRSN_CD3, ICD_DGNS_CD4, ICD_DGNS_VRSN_CD4, ICD_DGNS_CD5, ICD_DGNS_VRSN_CD5, ICD_DGNS_CD6, ICD_DGNS_VRSN_CD6, ICD_DGNS_CD7, ICD_DGNS_VRSN_CD7, ICD_DGNS_CD8, ICD_DGNS_VRSN_CD8, ICD_DGNS_CD9, ICD_DGNS_VRSN_CD9, ICD_DGNS_CD10, ICD_DGNS_VRSN_CD10, ICD_DGNS_CD11, ICD_DGNS_VRSN_CD11, ICD_DGNS_CD12, ICD_DGNS_VRSN_CD12, ICD_DGNS_CD13, ICD_DGNS_VRSN_CD13, ICD_DGNS_CD14, ICD_DGNS_VRSN_CD14, ICD_DGNS_CD15, ICD_DGNS_VRSN_CD15, ICD_DGNS_CD16, ICD_DGNS_VRSN_CD16, ICD_DGNS_CD17, ICD_DGNS_VRSN_CD17, ICD_DGNS_CD18, ICD_DGNS_VRSN_CD18, ICD_DGNS_CD19, ICD_DGNS_VRSN_CD19, ICD_DGNS_CD20, ICD_DGNS_VRSN_CD20, ICD_DGNS_CD21, ICD_DGNS_VRSN_CD21, ICD_DGNS_CD22, ICD_DGNS_VRSN_CD22, ICD_DGNS_CD23, ICD_DGNS_VRSN_CD23, ICD_DGNS_CD24, ICD_DGNS_VRSN_CD24, ICD_DGNS_CD25, ICD_DGNS_VRSN_CD25, FST_DGNS_E_CD, FST_DGNS_E_VRSN_CD, ICD_DGNS_E_CD1, ICD_DGNS_E_VRSN_CD1, ICD_DGNS_E_CD2, ICD_DGNS_E_VRSN_CD2, ICD_DGNS_E_CD3, ICD_DGNS_E_VRSN_CD3, ICD_DGNS_E_CD4, ICD_DGNS_E_VRSN_CD4, ICD_DGNS_E_CD5, ICD_DGNS_E_VRSN_CD5, ICD_DGNS_E_CD6, ICD_DGNS_E_VRSN_CD6, ICD_DGNS_E_CD7, ICD_DGNS_E_VRSN_CD7, ICD_DGNS_E_CD8, ICD_DGNS_E_VRSN_CD8, ICD_DGNS_E_CD9, ICD_DGNS_E_VRSN_CD9, ICD_DGNS_E_CD10, ICD_DGNS_E_VRSN_CD10, ICD_DGNS_E_CD11, ICD_DGNS_E_VRSN_CD11, ICD_DGNS_E_CD12, ICD_DGNS_E_VRSN_CD12, ICD_PRCDR_CD1, ICD_PRCDR_VRSN_CD1, PRCDR_DT1, ICD_PRCDR_CD2, ICD_PRCDR_VRSN_CD2, PRCDR_DT2, ICD_PRCDR_CD3, ICD_PRCDR_VRSN_CD3, PRCDR_DT3, ICD_PRCDR_CD4, ICD_PRCDR_VRSN_CD4, PRCDR_DT4, ICD_PRCDR_CD5, ICD_PRCDR_VRSN_CD5, PRCDR_DT5, ICD_PRCDR_CD6, ICD_PRCDR_VRSN_CD6, PRCDR_DT6, ICD_PRCDR_CD7, ICD_PRCDR_VRSN_CD7, PRCDR_DT7, ICD_PRCDR_CD8, ICD_PRCDR_VRSN_CD8, PRCDR_DT8, ICD_PRCDR_CD9, ICD_PRCDR_VRSN_CD9, PRCDR_DT9, ICD_PRCDR_CD10, ICD_PRCDR_VRSN_CD10, PRCDR_DT10, ICD_PRCDR_CD11, ICD_PRCDR_VRSN_CD11, PRCDR_DT11, ICD_PRCDR_CD12, ICD_PRCDR_VRSN_CD12, PRCDR_DT12, ICD_PRCDR_CD13, ICD_PRCDR_VRSN_CD13, PRCDR_DT13, ICD_PRCDR_CD14, ICD_PRCDR_VRSN_CD14, PRCDR_DT14, ICD_PRCDR_CD15, ICD_PRCDR_VRSN_CD15, PRCDR_DT15, ICD_PRCDR_CD16, ICD_PRCDR_VRSN_CD16, PRCDR_DT16, ICD_PRCDR_CD17, ICD_PRCDR_VRSN_CD17, PRCDR_DT17, ICD_PRCDR_CD18, ICD_PRCDR_VRSN_CD18, PRCDR_DT18, ICD_PRCDR_CD19, ICD_PRCDR_VRSN_CD19, PRCDR_DT19, ICD_PRCDR_CD20, ICD_PRCDR_VRSN_CD20, PRCDR_DT20, ICD_PRCDR_CD21, ICD_PRCDR_VRSN_CD21, PRCDR_DT21, ICD_PRCDR_CD22, ICD_PRCDR_VRSN_CD22, PRCDR_DT22, ICD_PRCDR_CD23, ICD_PRCDR_VRSN_CD23, PRCDR_DT23, ICD_PRCDR_CD24, ICD_PRCDR_VRSN_CD24, PRCDR_DT24, ICD_PRCDR_CD25, ICD_PRCDR_VRSN_CD25, PRCDR_DT25, RSN_VISIT_CD1, RSN_VISIT_VRSN_CD1, RSN_VISIT_CD2, RSN_VISIT_VRSN_CD2, RSN_VISIT_CD3, RSN_VISIT_VRSN_CD3, NCH_BENE_PTB_DDCTBL_AMT, NCH_BENE_PTB_COINSRNC_AMT, CLM_OP_PRVDR_PMT_AMT, CLM_OP_BENE_PMT_AMT, FI_DOC_CLM_CNTL_NUM, FI_ORIG_CLM_CNTL_NUM, CLM_LINE_NUM, REV_CNTR, REV_CNTR_DT, REV_CNTR_1ST_ANSI_CD, REV_CNTR_2ND_ANSI_CD, REV_CNTR_3RD_ANSI_CD, REV_CNTR_4TH_ANSI_CD, REV_CNTR_APC_HIPPS_CD, HCPCS_CD, HCPCS_1ST_MDFR_CD, HCPCS_2ND_MDFR_CD, REV_CNTR_PMT_MTHD_IND_CD, REV_CNTR_DSCNT_IND_CD, REV_CNTR_PACKG_IND_CD, REV_CNTR_OTAF_PMT_CD, REV_CNTR_IDE_NDC_UPC_NUM, REV_CNTR_UNIT_CNT, REV_CNTR_RATE_AMT, REV_CNTR_BLOOD_DDCTBL_AMT, REV_CNTR_CASH_DDCTBL_AMT, REV_CNTR_COINSRNC_WGE_ADJSTD_C, REV_CNTR_RDCD_COINSRNC_AMT, REV_CNTR_1ST_MSP_PD_AMT, REV_CNTR_2ND_MSP_PD_AMT, REV_CNTR_PRVDR_PMT_AMT, REV_CNTR_BENE_PMT_AMT, REV_CNTR_PTNT_RSPNSBLTY_PMT, REV_CNTR_PMT_AMT_AMT, REV_CNTR_TOT_CHRG_AMT, REV_CNTR_NCVRD_CHRG_AMT, REV_CNTR_STUS_IND_CD, REV_CNTR_NDC_QTY, REV_CNTR_NDC_QTY_QLFR_CD, RNDRNG_PHYSN_UPIN, RNDRNG_PHYSN_NPI } /* package access */ enum InpatientFields { DML_IND, BENE_ID, CLM_ID, CLM_GRP_ID, FINAL_ACTION, NCH_NEAR_LINE_REC_IDENT_CD, NCH_CLM_TYPE_CD, CLM_FROM_DT, CLM_THRU_DT, NCH_WKLY_PROC_DT, FI_CLM_PROC_DT, CLAIM_QUERY_CODE, PRVDR_NUM, CLM_FAC_TYPE_CD, CLM_SRVC_CLSFCTN_TYPE_CD, CLM_FREQ_CD, FI_NUM, CLM_MDCR_NON_PMT_RSN_CD, CLM_PMT_AMT, NCH_PRMRY_PYR_CLM_PD_AMT, NCH_PRMRY_PYR_CD, FI_CLM_ACTN_CD, PRVDR_STATE_CD, ORG_NPI_NUM, AT_PHYSN_UPIN, AT_PHYSN_NPI, OP_PHYSN_UPIN, OP_PHYSN_NPI, OT_PHYSN_UPIN, OT_PHYSN_NPI, CLM_MCO_PD_SW, PTNT_DSCHRG_STUS_CD, CLM_PPS_IND_CD, CLM_TOT_CHRG_AMT, CLM_ADMSN_DT, CLM_IP_ADMSN_TYPE_CD, CLM_SRC_IP_ADMSN_CD, NCH_PTNT_STATUS_IND_CD, CLM_PASS_THRU_PER_DIEM_AMT, NCH_BENE_IP_DDCTBL_AMT, NCH_BENE_PTA_COINSRNC_LBLTY_AM, NCH_BENE_BLOOD_DDCTBL_LBLTY_AM, NCH_PROFNL_CMPNT_CHRG_AMT, NCH_IP_NCVRD_CHRG_AMT, NCH_IP_TOT_DDCTN_AMT, CLM_TOT_PPS_CPTL_AMT, CLM_PPS_CPTL_FSP_AMT, CLM_PPS_CPTL_OUTLIER_AMT, CLM_PPS_CPTL_DSPRPRTNT_SHR_AMT, CLM_PPS_CPTL_IME_AMT, CLM_PPS_CPTL_EXCPTN_AMT, CLM_PPS_OLD_CPTL_HLD_HRMLS_AMT, CLM_PPS_CPTL_DRG_WT_NUM, CLM_UTLZTN_DAY_CNT, BENE_TOT_COINSRNC_DAYS_CNT, BENE_LRD_USED_CNT, CLM_NON_UTLZTN_DAYS_CNT, NCH_BLOOD_PNTS_FRNSHD_QTY, NCH_VRFD_NCVRD_STAY_FROM_DT, NCH_VRFD_NCVRD_STAY_THRU_DT, NCH_ACTV_OR_CVRD_LVL_CARE_THRU, NCH_BENE_MDCR_BNFTS_EXHTD_DT_I, NCH_BENE_DSCHRG_DT, CLM_DRG_CD, CLM_DRG_OUTLIER_STAY_CD, NCH_DRG_OUTLIER_APRVD_PMT_AMT, ADMTG_DGNS_CD, ADMTG_DGNS_VRSN_CD, PRNCPAL_DGNS_CD, PRNCPAL_DGNS_VRSN_CD, ICD_DGNS_CD1, ICD_DGNS_VRSN_CD1, CLM_POA_IND_SW1, ICD_DGNS_CD2, ICD_DGNS_VRSN_CD2, CLM_POA_IND_SW2, ICD_DGNS_CD3, ICD_DGNS_VRSN_CD3, CLM_POA_IND_SW3, ICD_DGNS_CD4, ICD_DGNS_VRSN_CD4, CLM_POA_IND_SW4, ICD_DGNS_CD5, ICD_DGNS_VRSN_CD5, CLM_POA_IND_SW5, ICD_DGNS_CD6, ICD_DGNS_VRSN_CD6, CLM_POA_IND_SW6, ICD_DGNS_CD7, ICD_DGNS_VRSN_CD7, CLM_POA_IND_SW7, ICD_DGNS_CD8, ICD_DGNS_VRSN_CD8, CLM_POA_IND_SW8, ICD_DGNS_CD9, ICD_DGNS_VRSN_CD9, CLM_POA_IND_SW9, ICD_DGNS_CD10, ICD_DGNS_VRSN_CD10, CLM_POA_IND_SW10, ICD_DGNS_CD11, ICD_DGNS_VRSN_CD11, CLM_POA_IND_SW11, ICD_DGNS_CD12, ICD_DGNS_VRSN_CD12, CLM_POA_IND_SW12, ICD_DGNS_CD13, ICD_DGNS_VRSN_CD13, CLM_POA_IND_SW13, ICD_DGNS_CD14, ICD_DGNS_VRSN_CD14, CLM_POA_IND_SW14, ICD_DGNS_CD15, ICD_DGNS_VRSN_CD15, CLM_POA_IND_SW15, ICD_DGNS_CD16, ICD_DGNS_VRSN_CD16, CLM_POA_IND_SW16, ICD_DGNS_CD17, ICD_DGNS_VRSN_CD17, CLM_POA_IND_SW17, ICD_DGNS_CD18, ICD_DGNS_VRSN_CD18, CLM_POA_IND_SW18, ICD_DGNS_CD19, ICD_DGNS_VRSN_CD19, CLM_POA_IND_SW19, ICD_DGNS_CD20, ICD_DGNS_VRSN_CD20, CLM_POA_IND_SW20, ICD_DGNS_CD21, ICD_DGNS_VRSN_CD21, CLM_POA_IND_SW21, ICD_DGNS_CD22, ICD_DGNS_VRSN_CD22, CLM_POA_IND_SW22, ICD_DGNS_CD23, ICD_DGNS_VRSN_CD23, CLM_POA_IND_SW23, ICD_DGNS_CD24, ICD_DGNS_VRSN_CD24, CLM_POA_IND_SW24, ICD_DGNS_CD25, ICD_DGNS_VRSN_CD25, CLM_POA_IND_SW25, FST_DGNS_E_CD, FST_DGNS_E_VRSN_CD, ICD_DGNS_E_CD1, ICD_DGNS_E_VRSN_CD1, CLM_E_POA_IND_SW1, ICD_DGNS_E_CD2, ICD_DGNS_E_VRSN_CD2, CLM_E_POA_IND_SW2, ICD_DGNS_E_CD3, ICD_DGNS_E_VRSN_CD3, CLM_E_POA_IND_SW3, ICD_DGNS_E_CD4, ICD_DGNS_E_VRSN_CD4, CLM_E_POA_IND_SW4, ICD_DGNS_E_CD5, ICD_DGNS_E_VRSN_CD5, CLM_E_POA_IND_SW5, ICD_DGNS_E_CD6, ICD_DGNS_E_VRSN_CD6, CLM_E_POA_IND_SW6, ICD_DGNS_E_CD7, ICD_DGNS_E_VRSN_CD7, CLM_E_POA_IND_SW7, ICD_DGNS_E_CD8, ICD_DGNS_E_VRSN_CD8, CLM_E_POA_IND_SW8, ICD_DGNS_E_CD9, ICD_DGNS_E_VRSN_CD9, CLM_E_POA_IND_SW9, ICD_DGNS_E_CD10, ICD_DGNS_E_VRSN_CD10, CLM_E_POA_IND_SW10, ICD_DGNS_E_CD11, ICD_DGNS_E_VRSN_CD11, CLM_E_POA_IND_SW11, ICD_DGNS_E_CD12, ICD_DGNS_E_VRSN_CD12, CLM_E_POA_IND_SW12, ICD_PRCDR_CD1, ICD_PRCDR_VRSN_CD1, PRCDR_DT1, ICD_PRCDR_CD2, ICD_PRCDR_VRSN_CD2, PRCDR_DT2, ICD_PRCDR_CD3, ICD_PRCDR_VRSN_CD3, PRCDR_DT3, ICD_PRCDR_CD4, ICD_PRCDR_VRSN_CD4, PRCDR_DT4, ICD_PRCDR_CD5, ICD_PRCDR_VRSN_CD5, PRCDR_DT5, ICD_PRCDR_CD6, ICD_PRCDR_VRSN_CD6, PRCDR_DT6, ICD_PRCDR_CD7, ICD_PRCDR_VRSN_CD7, PRCDR_DT7, ICD_PRCDR_CD8, ICD_PRCDR_VRSN_CD8, PRCDR_DT8, ICD_PRCDR_CD9, ICD_PRCDR_VRSN_CD9, PRCDR_DT9, ICD_PRCDR_CD10, ICD_PRCDR_VRSN_CD10, PRCDR_DT10, ICD_PRCDR_CD11, ICD_PRCDR_VRSN_CD11, PRCDR_DT11, ICD_PRCDR_CD12, ICD_PRCDR_VRSN_CD12, PRCDR_DT12, ICD_PRCDR_CD13, ICD_PRCDR_VRSN_CD13, PRCDR_DT13, ICD_PRCDR_CD14, ICD_PRCDR_VRSN_CD14, PRCDR_DT14, ICD_PRCDR_CD15, ICD_PRCDR_VRSN_CD15, PRCDR_DT15, ICD_PRCDR_CD16, ICD_PRCDR_VRSN_CD16, PRCDR_DT16, ICD_PRCDR_CD17, ICD_PRCDR_VRSN_CD17, PRCDR_DT17, ICD_PRCDR_CD18, ICD_PRCDR_VRSN_CD18, PRCDR_DT18, ICD_PRCDR_CD19, ICD_PRCDR_VRSN_CD19, PRCDR_DT19, ICD_PRCDR_CD20, ICD_PRCDR_VRSN_CD20, PRCDR_DT20, ICD_PRCDR_CD21, ICD_PRCDR_VRSN_CD21, PRCDR_DT21, ICD_PRCDR_CD22, ICD_PRCDR_VRSN_CD22, PRCDR_DT22, ICD_PRCDR_CD23, ICD_PRCDR_VRSN_CD23, PRCDR_DT23, ICD_PRCDR_CD24, ICD_PRCDR_VRSN_CD24, PRCDR_DT24, ICD_PRCDR_CD25, ICD_PRCDR_VRSN_CD25, PRCDR_DT25, IME_OP_CLM_VAL_AMT, DSH_OP_CLM_VAL_AMT, CLM_UNCOMPD_CARE_PMT_AMT, FI_DOC_CLM_CNTL_NUM, FI_ORIG_CLM_CNTL_NUM, CLM_LINE_NUM, REV_CNTR, HCPCS_CD, REV_CNTR_UNIT_CNT, REV_CNTR_RATE_AMT, REV_CNTR_TOT_CHRG_AMT, REV_CNTR_NCVRD_CHRG_AMT, REV_CNTR_DDCTBL_COINSRNC_CD, REV_CNTR_NDC_QTY, REV_CNTR_NDC_QTY_QLFR_CD, RNDRNG_PHYSN_UPIN, RNDRNG_PHYSN_NPI } private InpatientFields[][] inpatientDxFields = { { InpatientFields.ICD_DGNS_CD1, InpatientFields.ICD_DGNS_VRSN_CD1, InpatientFields.CLM_POA_IND_SW1 }, { InpatientFields.ICD_DGNS_CD2, InpatientFields.ICD_DGNS_VRSN_CD2, InpatientFields.CLM_POA_IND_SW2 }, { InpatientFields.ICD_DGNS_CD3, InpatientFields.ICD_DGNS_VRSN_CD3, InpatientFields.CLM_POA_IND_SW3 }, { InpatientFields.ICD_DGNS_CD4, InpatientFields.ICD_DGNS_VRSN_CD4, InpatientFields.CLM_POA_IND_SW4 }, { InpatientFields.ICD_DGNS_CD5, InpatientFields.ICD_DGNS_VRSN_CD5, InpatientFields.CLM_POA_IND_SW5 }, { InpatientFields.ICD_DGNS_CD6, InpatientFields.ICD_DGNS_VRSN_CD6, InpatientFields.CLM_POA_IND_SW6 }, { InpatientFields.ICD_DGNS_CD7, InpatientFields.ICD_DGNS_VRSN_CD7, InpatientFields.CLM_POA_IND_SW7 }, { InpatientFields.ICD_DGNS_CD8, InpatientFields.ICD_DGNS_VRSN_CD8, InpatientFields.CLM_POA_IND_SW8 }, { InpatientFields.ICD_DGNS_CD9, InpatientFields.ICD_DGNS_VRSN_CD9, InpatientFields.CLM_POA_IND_SW9 }, { InpatientFields.ICD_DGNS_CD10, InpatientFields.ICD_DGNS_VRSN_CD10, InpatientFields.CLM_POA_IND_SW10 }, { InpatientFields.ICD_DGNS_CD11, InpatientFields.ICD_DGNS_VRSN_CD11, InpatientFields.CLM_POA_IND_SW11 }, { InpatientFields.ICD_DGNS_CD12, InpatientFields.ICD_DGNS_VRSN_CD12, InpatientFields.CLM_POA_IND_SW12 }, { InpatientFields.ICD_DGNS_CD13, InpatientFields.ICD_DGNS_VRSN_CD13, InpatientFields.CLM_POA_IND_SW13 }, { InpatientFields.ICD_DGNS_CD14, InpatientFields.ICD_DGNS_VRSN_CD14, InpatientFields.CLM_POA_IND_SW14 }, { InpatientFields.ICD_DGNS_CD15, InpatientFields.ICD_DGNS_VRSN_CD15, InpatientFields.CLM_POA_IND_SW15 }, { InpatientFields.ICD_DGNS_CD16, InpatientFields.ICD_DGNS_VRSN_CD16, InpatientFields.CLM_POA_IND_SW16 }, { InpatientFields.ICD_DGNS_CD17, InpatientFields.ICD_DGNS_VRSN_CD17, InpatientFields.CLM_POA_IND_SW17 }, { InpatientFields.ICD_DGNS_CD18, InpatientFields.ICD_DGNS_VRSN_CD18, InpatientFields.CLM_POA_IND_SW18 }, { InpatientFields.ICD_DGNS_CD19, InpatientFields.ICD_DGNS_VRSN_CD19, InpatientFields.CLM_POA_IND_SW19 }, { InpatientFields.ICD_DGNS_CD20, InpatientFields.ICD_DGNS_VRSN_CD20, InpatientFields.CLM_POA_IND_SW20 }, { InpatientFields.ICD_DGNS_CD21, InpatientFields.ICD_DGNS_VRSN_CD21, InpatientFields.CLM_POA_IND_SW21 }, { InpatientFields.ICD_DGNS_CD22, InpatientFields.ICD_DGNS_VRSN_CD22, InpatientFields.CLM_POA_IND_SW22 }, { InpatientFields.ICD_DGNS_CD23, InpatientFields.ICD_DGNS_VRSN_CD23, InpatientFields.CLM_POA_IND_SW23 }, { InpatientFields.ICD_DGNS_CD24, InpatientFields.ICD_DGNS_VRSN_CD24, InpatientFields.CLM_POA_IND_SW24 }, { InpatientFields.ICD_DGNS_CD25, InpatientFields.ICD_DGNS_VRSN_CD25, InpatientFields.CLM_POA_IND_SW25 } }; private InpatientFields[][] inpatientPxFields = { { InpatientFields.ICD_PRCDR_CD1, InpatientFields.ICD_PRCDR_VRSN_CD1, InpatientFields.PRCDR_DT1 }, { InpatientFields.ICD_PRCDR_CD2, InpatientFields.ICD_PRCDR_VRSN_CD2, InpatientFields.PRCDR_DT2 }, { InpatientFields.ICD_PRCDR_CD3, InpatientFields.ICD_PRCDR_VRSN_CD3, InpatientFields.PRCDR_DT3 }, { InpatientFields.ICD_PRCDR_CD4, InpatientFields.ICD_PRCDR_VRSN_CD4, InpatientFields.PRCDR_DT4 }, { InpatientFields.ICD_PRCDR_CD5, InpatientFields.ICD_PRCDR_VRSN_CD5, InpatientFields.PRCDR_DT5 }, { InpatientFields.ICD_PRCDR_CD6, InpatientFields.ICD_PRCDR_VRSN_CD6, InpatientFields.PRCDR_DT6 }, { InpatientFields.ICD_PRCDR_CD7, InpatientFields.ICD_PRCDR_VRSN_CD7, InpatientFields.PRCDR_DT7 }, { InpatientFields.ICD_PRCDR_CD8, InpatientFields.ICD_PRCDR_VRSN_CD8, InpatientFields.PRCDR_DT8 }, { InpatientFields.ICD_PRCDR_CD9, InpatientFields.ICD_PRCDR_VRSN_CD9, InpatientFields.PRCDR_DT9 }, { InpatientFields.ICD_PRCDR_CD10, InpatientFields.ICD_PRCDR_VRSN_CD10, InpatientFields.PRCDR_DT10 }, { InpatientFields.ICD_PRCDR_CD11, InpatientFields.ICD_PRCDR_VRSN_CD11, InpatientFields.PRCDR_DT11 }, { InpatientFields.ICD_PRCDR_CD12, InpatientFields.ICD_PRCDR_VRSN_CD12, InpatientFields.PRCDR_DT12 }, { InpatientFields.ICD_PRCDR_CD13, InpatientFields.ICD_PRCDR_VRSN_CD13, InpatientFields.PRCDR_DT13 }, { InpatientFields.ICD_PRCDR_CD14, InpatientFields.ICD_PRCDR_VRSN_CD14, InpatientFields.PRCDR_DT14 }, { InpatientFields.ICD_PRCDR_CD15, InpatientFields.ICD_PRCDR_VRSN_CD15, InpatientFields.PRCDR_DT15 }, { InpatientFields.ICD_PRCDR_CD16, InpatientFields.ICD_PRCDR_VRSN_CD16, InpatientFields.PRCDR_DT16 }, { InpatientFields.ICD_PRCDR_CD17, InpatientFields.ICD_PRCDR_VRSN_CD17, InpatientFields.PRCDR_DT17 }, { InpatientFields.ICD_PRCDR_CD18, InpatientFields.ICD_PRCDR_VRSN_CD18, InpatientFields.PRCDR_DT18 }, { InpatientFields.ICD_PRCDR_CD19, InpatientFields.ICD_PRCDR_VRSN_CD19, InpatientFields.PRCDR_DT19 }, { InpatientFields.ICD_PRCDR_CD20, InpatientFields.ICD_PRCDR_VRSN_CD20, InpatientFields.PRCDR_DT20 }, { InpatientFields.ICD_PRCDR_CD21, InpatientFields.ICD_PRCDR_VRSN_CD21, InpatientFields.PRCDR_DT21 }, { InpatientFields.ICD_PRCDR_CD22, InpatientFields.ICD_PRCDR_VRSN_CD22, InpatientFields.PRCDR_DT22 }, { InpatientFields.ICD_PRCDR_CD23, InpatientFields.ICD_PRCDR_VRSN_CD23, InpatientFields.PRCDR_DT23 }, { InpatientFields.ICD_PRCDR_CD24, InpatientFields.ICD_PRCDR_VRSN_CD24, InpatientFields.PRCDR_DT24 }, { InpatientFields.ICD_PRCDR_CD25, InpatientFields.ICD_PRCDR_VRSN_CD25, InpatientFields.PRCDR_DT25 } }; private OutpatientFields[][] outpatientDxFields = { { OutpatientFields.ICD_DGNS_CD1, OutpatientFields.ICD_DGNS_VRSN_CD1 }, { OutpatientFields.ICD_DGNS_CD2, OutpatientFields.ICD_DGNS_VRSN_CD2 }, { OutpatientFields.ICD_DGNS_CD3, OutpatientFields.ICD_DGNS_VRSN_CD3 }, { OutpatientFields.ICD_DGNS_CD4, OutpatientFields.ICD_DGNS_VRSN_CD4 }, { OutpatientFields.ICD_DGNS_CD5, OutpatientFields.ICD_DGNS_VRSN_CD5 }, { OutpatientFields.ICD_DGNS_CD6, OutpatientFields.ICD_DGNS_VRSN_CD6 }, { OutpatientFields.ICD_DGNS_CD7, OutpatientFields.ICD_DGNS_VRSN_CD7 }, { OutpatientFields.ICD_DGNS_CD8, OutpatientFields.ICD_DGNS_VRSN_CD8 }, { OutpatientFields.ICD_DGNS_CD9, OutpatientFields.ICD_DGNS_VRSN_CD9 }, { OutpatientFields.ICD_DGNS_CD10, OutpatientFields.ICD_DGNS_VRSN_CD10 }, { OutpatientFields.ICD_DGNS_CD11, OutpatientFields.ICD_DGNS_VRSN_CD11 }, { OutpatientFields.ICD_DGNS_CD12, OutpatientFields.ICD_DGNS_VRSN_CD12 }, { OutpatientFields.ICD_DGNS_CD13, OutpatientFields.ICD_DGNS_VRSN_CD13 }, { OutpatientFields.ICD_DGNS_CD14, OutpatientFields.ICD_DGNS_VRSN_CD14 }, { OutpatientFields.ICD_DGNS_CD15, OutpatientFields.ICD_DGNS_VRSN_CD15 }, { OutpatientFields.ICD_DGNS_CD16, OutpatientFields.ICD_DGNS_VRSN_CD16 }, { OutpatientFields.ICD_DGNS_CD17, OutpatientFields.ICD_DGNS_VRSN_CD17 }, { OutpatientFields.ICD_DGNS_CD18, OutpatientFields.ICD_DGNS_VRSN_CD18 }, { OutpatientFields.ICD_DGNS_CD19, OutpatientFields.ICD_DGNS_VRSN_CD19 }, { OutpatientFields.ICD_DGNS_CD20, OutpatientFields.ICD_DGNS_VRSN_CD20 }, { OutpatientFields.ICD_DGNS_CD21, OutpatientFields.ICD_DGNS_VRSN_CD21 }, { OutpatientFields.ICD_DGNS_CD22, OutpatientFields.ICD_DGNS_VRSN_CD22 }, { OutpatientFields.ICD_DGNS_CD23, OutpatientFields.ICD_DGNS_VRSN_CD23 }, { OutpatientFields.ICD_DGNS_CD24, OutpatientFields.ICD_DGNS_VRSN_CD24 }, { OutpatientFields.ICD_DGNS_CD25, OutpatientFields.ICD_DGNS_VRSN_CD25 } }; private OutpatientFields[][] outpatientPxFields = { { OutpatientFields.ICD_PRCDR_CD1, OutpatientFields.ICD_PRCDR_VRSN_CD1, OutpatientFields.PRCDR_DT1 }, { OutpatientFields.ICD_PRCDR_CD2, OutpatientFields.ICD_PRCDR_VRSN_CD2, OutpatientFields.PRCDR_DT2 }, { OutpatientFields.ICD_PRCDR_CD3, OutpatientFields.ICD_PRCDR_VRSN_CD3, OutpatientFields.PRCDR_DT3 }, { OutpatientFields.ICD_PRCDR_CD4, OutpatientFields.ICD_PRCDR_VRSN_CD4, OutpatientFields.PRCDR_DT4 }, { OutpatientFields.ICD_PRCDR_CD5, OutpatientFields.ICD_PRCDR_VRSN_CD5, OutpatientFields.PRCDR_DT5 }, { OutpatientFields.ICD_PRCDR_CD6, OutpatientFields.ICD_PRCDR_VRSN_CD6, OutpatientFields.PRCDR_DT6 }, { OutpatientFields.ICD_PRCDR_CD7, OutpatientFields.ICD_PRCDR_VRSN_CD7, OutpatientFields.PRCDR_DT7 }, { OutpatientFields.ICD_PRCDR_CD8, OutpatientFields.ICD_PRCDR_VRSN_CD8, OutpatientFields.PRCDR_DT8 }, { OutpatientFields.ICD_PRCDR_CD9, OutpatientFields.ICD_PRCDR_VRSN_CD9, OutpatientFields.PRCDR_DT9 }, { OutpatientFields.ICD_PRCDR_CD10, OutpatientFields.ICD_PRCDR_VRSN_CD10, OutpatientFields.PRCDR_DT10 }, { OutpatientFields.ICD_PRCDR_CD11, OutpatientFields.ICD_PRCDR_VRSN_CD11, OutpatientFields.PRCDR_DT11 }, { OutpatientFields.ICD_PRCDR_CD12, OutpatientFields.ICD_PRCDR_VRSN_CD12, OutpatientFields.PRCDR_DT12 }, { OutpatientFields.ICD_PRCDR_CD13, OutpatientFields.ICD_PRCDR_VRSN_CD13, OutpatientFields.PRCDR_DT13 }, { OutpatientFields.ICD_PRCDR_CD14, OutpatientFields.ICD_PRCDR_VRSN_CD14, OutpatientFields.PRCDR_DT14 }, { OutpatientFields.ICD_PRCDR_CD15, OutpatientFields.ICD_PRCDR_VRSN_CD15, OutpatientFields.PRCDR_DT15 }, { OutpatientFields.ICD_PRCDR_CD16, OutpatientFields.ICD_PRCDR_VRSN_CD16, OutpatientFields.PRCDR_DT16 }, { OutpatientFields.ICD_PRCDR_CD17, OutpatientFields.ICD_PRCDR_VRSN_CD17, OutpatientFields.PRCDR_DT17 }, { OutpatientFields.ICD_PRCDR_CD18, OutpatientFields.ICD_PRCDR_VRSN_CD18, OutpatientFields.PRCDR_DT18 }, { OutpatientFields.ICD_PRCDR_CD19, OutpatientFields.ICD_PRCDR_VRSN_CD19, OutpatientFields.PRCDR_DT19 }, { OutpatientFields.ICD_PRCDR_CD20, OutpatientFields.ICD_PRCDR_VRSN_CD20, OutpatientFields.PRCDR_DT20 }, { OutpatientFields.ICD_PRCDR_CD21, OutpatientFields.ICD_PRCDR_VRSN_CD21, OutpatientFields.PRCDR_DT21 }, { OutpatientFields.ICD_PRCDR_CD22, OutpatientFields.ICD_PRCDR_VRSN_CD22, OutpatientFields.PRCDR_DT22 }, { OutpatientFields.ICD_PRCDR_CD23, OutpatientFields.ICD_PRCDR_VRSN_CD23, OutpatientFields.PRCDR_DT23 }, { OutpatientFields.ICD_PRCDR_CD24, OutpatientFields.ICD_PRCDR_VRSN_CD24, OutpatientFields.PRCDR_DT24 }, { OutpatientFields.ICD_PRCDR_CD25, OutpatientFields.ICD_PRCDR_VRSN_CD25, OutpatientFields.PRCDR_DT25 } }; /* package access */ enum CarrierFields { DML_IND, BENE_ID, CLM_ID, CLM_GRP_ID, FINAL_ACTION, NCH_NEAR_LINE_REC_IDENT_CD, NCH_CLM_TYPE_CD, CLM_FROM_DT, CLM_THRU_DT, NCH_WKLY_PROC_DT, CARR_CLM_ENTRY_CD, CLM_DISP_CD, CARR_NUM, CARR_CLM_PMT_DNL_CD, CLM_PMT_AMT, CARR_CLM_PRMRY_PYR_PD_AMT, RFR_PHYSN_UPIN, RFR_PHYSN_NPI, CARR_CLM_PRVDR_ASGNMT_IND_SW, NCH_CLM_PRVDR_PMT_AMT, NCH_CLM_BENE_PMT_AMT, NCH_CARR_CLM_SBMTD_CHRG_AMT, NCH_CARR_CLM_ALOWD_AMT, CARR_CLM_CASH_DDCTBL_APLD_AMT, CARR_CLM_HCPCS_YR_CD, CARR_CLM_RFRNG_PIN_NUM, PRNCPAL_DGNS_CD, PRNCPAL_DGNS_VRSN_CD, ICD_DGNS_CD1, ICD_DGNS_VRSN_CD1, ICD_DGNS_CD2, ICD_DGNS_VRSN_CD2, ICD_DGNS_CD3, ICD_DGNS_VRSN_CD3, ICD_DGNS_CD4, ICD_DGNS_VRSN_CD4, ICD_DGNS_CD5, ICD_DGNS_VRSN_CD5, ICD_DGNS_CD6, ICD_DGNS_VRSN_CD6, ICD_DGNS_CD7, ICD_DGNS_VRSN_CD7, ICD_DGNS_CD8, ICD_DGNS_VRSN_CD8, ICD_DGNS_CD9, ICD_DGNS_VRSN_CD9, ICD_DGNS_CD10, ICD_DGNS_VRSN_CD10, ICD_DGNS_CD11, ICD_DGNS_VRSN_CD11, ICD_DGNS_CD12, ICD_DGNS_VRSN_CD12, CLM_CLNCL_TRIL_NUM, CARR_CLM_CNTL_NUM, LINE_NUM, CARR_PRFRNG_PIN_NUM, PRF_PHYSN_UPIN, PRF_PHYSN_NPI, ORG_NPI_NUM, CARR_LINE_PRVDR_TYPE_CD, TAX_NUM, PRVDR_STATE_CD, PRVDR_ZIP, PRVDR_SPCLTY, PRTCPTNG_IND_CD, CARR_LINE_RDCD_PMT_PHYS_ASTN_C, LINE_SRVC_CNT, LINE_CMS_TYPE_SRVC_CD, LINE_PLACE_OF_SRVC_CD, CARR_LINE_PRCNG_LCLTY_CD, LINE_1ST_EXPNS_DT, LINE_LAST_EXPNS_DT, HCPCS_CD, HCPCS_1ST_MDFR_CD, HCPCS_2ND_MDFR_CD, BETOS_CD, LINE_NCH_PMT_AMT, LINE_BENE_PMT_AMT, LINE_PRVDR_PMT_AMT, LINE_BENE_PTB_DDCTBL_AMT, LINE_BENE_PRMRY_PYR_CD, LINE_BENE_PRMRY_PYR_PD_AMT, LINE_COINSRNC_AMT, LINE_SBMTD_CHRG_AMT, LINE_ALOWD_CHRG_AMT, LINE_PRCSG_IND_CD, LINE_PMT_80_100_CD, LINE_SERVICE_DEDUCTIBLE, CARR_LINE_MTUS_CNT, CARR_LINE_MTUS_CD, LINE_ICD_DGNS_CD, LINE_ICD_DGNS_VRSN_CD, HPSA_SCRCTY_IND_CD, CARR_LINE_RX_NUM, LINE_HCT_HGB_RSLT_NUM, LINE_HCT_HGB_TYPE_CD, LINE_NDC_CD, CARR_LINE_CLIA_LAB_NUM, CARR_LINE_ANSTHSA_UNIT_CNT } private CarrierFields[][] carrierDxFields = { { CarrierFields.ICD_DGNS_CD1, CarrierFields.ICD_DGNS_VRSN_CD1 }, { CarrierFields.ICD_DGNS_CD2, CarrierFields.ICD_DGNS_VRSN_CD2 }, { CarrierFields.ICD_DGNS_CD3, CarrierFields.ICD_DGNS_VRSN_CD3 }, { CarrierFields.ICD_DGNS_CD4, CarrierFields.ICD_DGNS_VRSN_CD4 }, { CarrierFields.ICD_DGNS_CD5, CarrierFields.ICD_DGNS_VRSN_CD5 }, { CarrierFields.ICD_DGNS_CD6, CarrierFields.ICD_DGNS_VRSN_CD6 }, { CarrierFields.ICD_DGNS_CD7, CarrierFields.ICD_DGNS_VRSN_CD7 }, { CarrierFields.ICD_DGNS_CD8, CarrierFields.ICD_DGNS_VRSN_CD8 }, { CarrierFields.ICD_DGNS_CD9, CarrierFields.ICD_DGNS_VRSN_CD9 }, { CarrierFields.ICD_DGNS_CD10, CarrierFields.ICD_DGNS_VRSN_CD10 }, { CarrierFields.ICD_DGNS_CD11, CarrierFields.ICD_DGNS_VRSN_CD11 }, { CarrierFields.ICD_DGNS_CD12, CarrierFields.ICD_DGNS_VRSN_CD12 } }; public enum PrescriptionFields { DML_IND, PDE_ID, CLM_GRP_ID, FINAL_ACTION, BENE_ID, SRVC_DT, PD_DT, SRVC_PRVDR_ID_QLFYR_CD, SRVC_PRVDR_ID, PRSCRBR_ID_QLFYR_CD, PRSCRBR_ID, RX_SRVC_RFRNC_NUM, PROD_SRVC_ID, PLAN_CNTRCT_REC_ID, PLAN_PBP_REC_NUM, CMPND_CD, DAW_PROD_SLCTN_CD, QTY_DSPNSD_NUM, DAYS_SUPLY_NUM, FILL_NUM, DSPNSNG_STUS_CD, DRUG_CVRG_STUS_CD, ADJSTMT_DLTN_CD, NSTD_FRMT_CD, PRCNG_EXCPTN_CD, CTSTRPHC_CVRG_CD, GDC_BLW_OOPT_AMT, GDC_ABV_OOPT_AMT, PTNT_PAY_AMT, OTHR_TROOP_AMT, LICS_AMT, PLRO_AMT, CVRD_D_PLAN_PD_AMT, NCVRD_PLAN_PD_AMT, TOT_RX_CST_AMT, RX_ORGN_CD, RPTD_GAP_DSCNT_NUM, BRND_GNRC_CD, PHRMCY_SRVC_TYPE_CD, PTNT_RSDNC_CD, SUBMSN_CLR_CD } public enum DMEFields { DML_IND, BENE_ID, CLM_ID, CLM_GRP_ID, FINAL_ACTION, NCH_NEAR_LINE_REC_IDENT_CD, NCH_CLM_TYPE_CD, CLM_FROM_DT, CLM_THRU_DT, NCH_WKLY_PROC_DT, CARR_CLM_ENTRY_CD, CLM_DISP_CD, CARR_NUM, CARR_CLM_PMT_DNL_CD, CLM_PMT_AMT, CARR_CLM_PRMRY_PYR_PD_AMT, CARR_CLM_PRVDR_ASGNMT_IND_SW, NCH_CLM_PRVDR_PMT_AMT, NCH_CLM_BENE_PMT_AMT, NCH_CARR_CLM_SBMTD_CHRG_AMT, NCH_CARR_CLM_ALOWD_AMT, CARR_CLM_CASH_DDCTBL_APLD_AMT, CARR_CLM_HCPCS_YR_CD, PRNCPAL_DGNS_CD, PRNCPAL_DGNS_VRSN_CD, ICD_DGNS_CD1, ICD_DGNS_VRSN_CD1, ICD_DGNS_CD2, ICD_DGNS_VRSN_CD2, ICD_DGNS_CD3, ICD_DGNS_VRSN_CD3, ICD_DGNS_CD4, ICD_DGNS_VRSN_CD4, ICD_DGNS_CD5, ICD_DGNS_VRSN_CD5, ICD_DGNS_CD6, ICD_DGNS_VRSN_CD6, ICD_DGNS_CD7, ICD_DGNS_VRSN_CD7, ICD_DGNS_CD8, ICD_DGNS_VRSN_CD8, ICD_DGNS_CD9, ICD_DGNS_VRSN_CD9, ICD_DGNS_CD10, ICD_DGNS_VRSN_CD10, ICD_DGNS_CD11, ICD_DGNS_VRSN_CD11, ICD_DGNS_CD12, ICD_DGNS_VRSN_CD12, RFR_PHYSN_UPIN, RFR_PHYSN_NPI, CLM_CLNCL_TRIL_NUM, CARR_CLM_CNTL_NUM, LINE_NUM, TAX_NUM, PRVDR_SPCLTY, PRTCPTNG_IND_CD, LINE_SRVC_CNT, LINE_CMS_TYPE_SRVC_CD, LINE_PLACE_OF_SRVC_CD, LINE_1ST_EXPNS_DT, LINE_LAST_EXPNS_DT, HCPCS_CD, HCPCS_1ST_MDFR_CD, HCPCS_2ND_MDFR_CD, BETOS_CD, LINE_NCH_PMT_AMT, LINE_BENE_PMT_AMT, LINE_PRVDR_PMT_AMT, LINE_BENE_PTB_DDCTBL_AMT, LINE_BENE_PRMRY_PYR_CD, LINE_BENE_PRMRY_PYR_PD_AMT, LINE_COINSRNC_AMT, LINE_PRMRY_ALOWD_CHRG_AMT, LINE_SBMTD_CHRG_AMT, LINE_ALOWD_CHRG_AMT, LINE_PRCSG_IND_CD, LINE_PMT_80_100_CD, LINE_SERVICE_DEDUCTIBLE, LINE_ICD_DGNS_CD, LINE_ICD_DGNS_VRSN_CD, LINE_DME_PRCHS_PRICE_AMT, PRVDR_NUM, PRVDR_NPI, DMERC_LINE_PRCNG_STATE_CD, PRVDR_STATE_CD, DMERC_LINE_SUPPLR_TYPE_CD, HCPCS_3RD_MDFR_CD, HCPCS_4TH_MDFR_CD, DMERC_LINE_SCRN_SVGS_AMT, DMERC_LINE_MTUS_CNT, DMERC_LINE_MTUS_CD, LINE_HCT_HGB_RSLT_NUM, LINE_HCT_HGB_TYPE_CD, LINE_NDC_CD } private DMEFields[][] dmeDxFields = { { DMEFields.ICD_DGNS_CD1, DMEFields.ICD_DGNS_VRSN_CD1 }, { DMEFields.ICD_DGNS_CD2, DMEFields.ICD_DGNS_VRSN_CD2 }, { DMEFields.ICD_DGNS_CD3, DMEFields.ICD_DGNS_VRSN_CD3 }, { DMEFields.ICD_DGNS_CD4, DMEFields.ICD_DGNS_VRSN_CD4 }, { DMEFields.ICD_DGNS_CD5, DMEFields.ICD_DGNS_VRSN_CD5 }, { DMEFields.ICD_DGNS_CD6, DMEFields.ICD_DGNS_VRSN_CD6 }, { DMEFields.ICD_DGNS_CD7, DMEFields.ICD_DGNS_VRSN_CD7 }, { DMEFields.ICD_DGNS_CD8, DMEFields.ICD_DGNS_VRSN_CD8 }, { DMEFields.ICD_DGNS_CD9, DMEFields.ICD_DGNS_VRSN_CD9 }, { DMEFields.ICD_DGNS_CD10, DMEFields.ICD_DGNS_VRSN_CD10 }, { DMEFields.ICD_DGNS_CD11, DMEFields.ICD_DGNS_VRSN_CD11 }, { DMEFields.ICD_DGNS_CD12, DMEFields.ICD_DGNS_VRSN_CD12 } }; public enum NPIFields { NPI, ENTITY_TYPE_CODE, REPLACEMENT_NPI, EIN, ORG_NAME, LAST_NAME, FIRST_NAME, MIDDLE_NAME, PREFIX, SUFFIX, CREDENTIALS } public enum HHAFields { DML_IND, BENE_ID, CLM_ID, CLM_GRP_ID, FINAL_ACTION, NCH_NEAR_LINE_REC_IDENT_CD, NCH_CLM_TYPE_CD, CLM_FROM_DT, CLM_THRU_DT, NCH_WKLY_PROC_DT, FI_CLM_PROC_DT, PRVDR_NUM, CLM_FAC_TYPE_CD, CLM_SRVC_CLSFCTN_TYPE_CD, CLM_FREQ_CD, FI_NUM, CLM_MDCR_NON_PMT_RSN_CD, CLM_PMT_AMT, NCH_PRMRY_PYR_CLM_PD_AMT, NCH_PRMRY_PYR_CD, PRVDR_STATE_CD, ORG_NPI_NUM, AT_PHYSN_UPIN, AT_PHYSN_NPI, PTNT_DSCHRG_STUS_CD, CLM_PPS_IND_CD, CLM_TOT_CHRG_AMT, PRNCPAL_DGNS_CD, PRNCPAL_DGNS_VRSN_CD, ICD_DGNS_CD1, ICD_DGNS_VRSN_CD1, ICD_DGNS_CD2, ICD_DGNS_VRSN_CD2, ICD_DGNS_CD3, ICD_DGNS_VRSN_CD3, ICD_DGNS_CD4, ICD_DGNS_VRSN_CD4, ICD_DGNS_CD5, ICD_DGNS_VRSN_CD5, ICD_DGNS_CD6, ICD_DGNS_VRSN_CD6, ICD_DGNS_CD7, ICD_DGNS_VRSN_CD7, ICD_DGNS_CD8, ICD_DGNS_VRSN_CD8, ICD_DGNS_CD9, ICD_DGNS_VRSN_CD9, ICD_DGNS_CD10, ICD_DGNS_VRSN_CD10, ICD_DGNS_CD11, ICD_DGNS_VRSN_CD11, ICD_DGNS_CD12, ICD_DGNS_VRSN_CD12, ICD_DGNS_CD13, ICD_DGNS_VRSN_CD13, ICD_DGNS_CD14, ICD_DGNS_VRSN_CD14, ICD_DGNS_CD15, ICD_DGNS_VRSN_CD15, ICD_DGNS_CD16, ICD_DGNS_VRSN_CD16, ICD_DGNS_CD17, ICD_DGNS_VRSN_CD17, ICD_DGNS_CD18, ICD_DGNS_VRSN_CD18, ICD_DGNS_CD19, ICD_DGNS_VRSN_CD19, ICD_DGNS_CD20, ICD_DGNS_VRSN_CD20, ICD_DGNS_CD21, ICD_DGNS_VRSN_CD21, ICD_DGNS_CD22, ICD_DGNS_VRSN_CD22, ICD_DGNS_CD23, ICD_DGNS_VRSN_CD23, ICD_DGNS_CD24, ICD_DGNS_VRSN_CD24, ICD_DGNS_CD25, ICD_DGNS_VRSN_CD25, FST_DGNS_E_CD, FST_DGNS_E_VRSN_CD, ICD_DGNS_E_CD1, ICD_DGNS_E_VRSN_CD1, ICD_DGNS_E_CD2, ICD_DGNS_E_VRSN_CD2, ICD_DGNS_E_CD3, ICD_DGNS_E_VRSN_CD3, ICD_DGNS_E_CD4, ICD_DGNS_E_VRSN_CD4, ICD_DGNS_E_CD5, ICD_DGNS_E_VRSN_CD5, ICD_DGNS_E_CD6, ICD_DGNS_E_VRSN_CD6, ICD_DGNS_E_CD7, ICD_DGNS_E_VRSN_CD7, ICD_DGNS_E_CD8, ICD_DGNS_E_VRSN_CD8, ICD_DGNS_E_CD9, ICD_DGNS_E_VRSN_CD9, ICD_DGNS_E_CD10, ICD_DGNS_E_VRSN_CD10, ICD_DGNS_E_CD11, ICD_DGNS_E_VRSN_CD11, ICD_DGNS_E_CD12, ICD_DGNS_E_VRSN_CD12, CLM_HHA_LUPA_IND_CD, CLM_HHA_RFRL_CD, CLM_HHA_TOT_VISIT_CNT, CLM_ADMSN_DT, FI_DOC_CLM_CNTL_NUM, FI_ORIG_CLM_CNTL_NUM, CLM_LINE_NUM, REV_CNTR, REV_CNTR_DT, REV_CNTR_1ST_ANSI_CD, REV_CNTR_APC_HIPPS_CD, HCPCS_CD, HCPCS_1ST_MDFR_CD, HCPCS_2ND_MDFR_CD, REV_CNTR_PMT_MTHD_IND_CD, REV_CNTR_UNIT_CNT, REV_CNTR_RATE_AMT, REV_CNTR_PMT_AMT_AMT, REV_CNTR_TOT_CHRG_AMT, REV_CNTR_NCVRD_CHRG_AMT, REV_CNTR_DDCTBL_COINSRNC_CD, REV_CNTR_STUS_IND_CD, REV_CNTR_NDC_QTY, REV_CNTR_NDC_QTY_QLFR_CD, RNDRNG_PHYSN_UPIN, RNDRNG_PHYSN_NPI } private HHAFields[][] homeDxFields = { { HHAFields.ICD_DGNS_CD1, HHAFields.ICD_DGNS_VRSN_CD1 }, { HHAFields.ICD_DGNS_CD2, HHAFields.ICD_DGNS_VRSN_CD2 }, { HHAFields.ICD_DGNS_CD3, HHAFields.ICD_DGNS_VRSN_CD3 }, { HHAFields.ICD_DGNS_CD4, HHAFields.ICD_DGNS_VRSN_CD4 }, { HHAFields.ICD_DGNS_CD5, HHAFields.ICD_DGNS_VRSN_CD5 }, { HHAFields.ICD_DGNS_CD6, HHAFields.ICD_DGNS_VRSN_CD6 }, { HHAFields.ICD_DGNS_CD7, HHAFields.ICD_DGNS_VRSN_CD7 }, { HHAFields.ICD_DGNS_CD8, HHAFields.ICD_DGNS_VRSN_CD8 }, { HHAFields.ICD_DGNS_CD9, HHAFields.ICD_DGNS_VRSN_CD9 }, { HHAFields.ICD_DGNS_CD10, HHAFields.ICD_DGNS_VRSN_CD10 }, { HHAFields.ICD_DGNS_CD11, HHAFields.ICD_DGNS_VRSN_CD11 }, { HHAFields.ICD_DGNS_CD12, HHAFields.ICD_DGNS_VRSN_CD12 }, { HHAFields.ICD_DGNS_CD13, HHAFields.ICD_DGNS_VRSN_CD13 }, { HHAFields.ICD_DGNS_CD14, HHAFields.ICD_DGNS_VRSN_CD14 }, { HHAFields.ICD_DGNS_CD15, HHAFields.ICD_DGNS_VRSN_CD15 }, { HHAFields.ICD_DGNS_CD16, HHAFields.ICD_DGNS_VRSN_CD16 }, { HHAFields.ICD_DGNS_CD17, HHAFields.ICD_DGNS_VRSN_CD17 }, { HHAFields.ICD_DGNS_CD18, HHAFields.ICD_DGNS_VRSN_CD18 }, { HHAFields.ICD_DGNS_CD19, HHAFields.ICD_DGNS_VRSN_CD19 }, { HHAFields.ICD_DGNS_CD20, HHAFields.ICD_DGNS_VRSN_CD20 }, { HHAFields.ICD_DGNS_CD21, HHAFields.ICD_DGNS_VRSN_CD21 }, { HHAFields.ICD_DGNS_CD22, HHAFields.ICD_DGNS_VRSN_CD22 }, { HHAFields.ICD_DGNS_CD23, HHAFields.ICD_DGNS_VRSN_CD23 }, { HHAFields.ICD_DGNS_CD24, HHAFields.ICD_DGNS_VRSN_CD24 }, { HHAFields.ICD_DGNS_CD25, HHAFields.ICD_DGNS_VRSN_CD25 } }; public enum HospiceFields { DML_IND, BENE_ID, CLM_ID, CLM_GRP_ID, FINAL_ACTION, NCH_NEAR_LINE_REC_IDENT_CD, NCH_CLM_TYPE_CD, CLM_FROM_DT, CLM_THRU_DT, NCH_WKLY_PROC_DT, FI_CLM_PROC_DT, PRVDR_NUM, CLM_FAC_TYPE_CD, CLM_SRVC_CLSFCTN_TYPE_CD, CLM_FREQ_CD, FI_NUM, CLM_MDCR_NON_PMT_RSN_CD, CLM_PMT_AMT, NCH_PRMRY_PYR_CLM_PD_AMT, NCH_PRMRY_PYR_CD, PRVDR_STATE_CD, ORG_NPI_NUM, AT_PHYSN_UPIN, AT_PHYSN_NPI, PTNT_DSCHRG_STUS_CD, CLM_TOT_CHRG_AMT, NCH_PTNT_STATUS_IND_CD, CLM_UTLZTN_DAY_CNT, NCH_BENE_DSCHRG_DT, PRNCPAL_DGNS_CD, PRNCPAL_DGNS_VRSN_CD, ICD_DGNS_CD1, ICD_DGNS_VRSN_CD1, ICD_DGNS_CD2, ICD_DGNS_VRSN_CD2, ICD_DGNS_CD3, ICD_DGNS_VRSN_CD3, ICD_DGNS_CD4, ICD_DGNS_VRSN_CD4, ICD_DGNS_CD5, ICD_DGNS_VRSN_CD5, ICD_DGNS_CD6, ICD_DGNS_VRSN_CD6, ICD_DGNS_CD7, ICD_DGNS_VRSN_CD7, ICD_DGNS_CD8, ICD_DGNS_VRSN_CD8, ICD_DGNS_CD9, ICD_DGNS_VRSN_CD9, ICD_DGNS_CD10, ICD_DGNS_VRSN_CD10, ICD_DGNS_CD11, ICD_DGNS_VRSN_CD11, ICD_DGNS_CD12, ICD_DGNS_VRSN_CD12, ICD_DGNS_CD13, ICD_DGNS_VRSN_CD13, ICD_DGNS_CD14, ICD_DGNS_VRSN_CD14, ICD_DGNS_CD15, ICD_DGNS_VRSN_CD15, ICD_DGNS_CD16, ICD_DGNS_VRSN_CD16, ICD_DGNS_CD17, ICD_DGNS_VRSN_CD17, ICD_DGNS_CD18, ICD_DGNS_VRSN_CD18, ICD_DGNS_CD19, ICD_DGNS_VRSN_CD19, ICD_DGNS_CD20, ICD_DGNS_VRSN_CD20, ICD_DGNS_CD21, ICD_DGNS_VRSN_CD21, ICD_DGNS_CD22, ICD_DGNS_VRSN_CD22, ICD_DGNS_CD23, ICD_DGNS_VRSN_CD23, ICD_DGNS_CD24, ICD_DGNS_VRSN_CD24, ICD_DGNS_CD25, ICD_DGNS_VRSN_CD25, FST_DGNS_E_CD, FST_DGNS_E_VRSN_CD, ICD_DGNS_E_CD1, ICD_DGNS_E_VRSN_CD1, ICD_DGNS_E_CD2, ICD_DGNS_E_VRSN_CD2, ICD_DGNS_E_CD3, ICD_DGNS_E_VRSN_CD3, ICD_DGNS_E_CD4, ICD_DGNS_E_VRSN_CD4, ICD_DGNS_E_CD5, ICD_DGNS_E_VRSN_CD5, ICD_DGNS_E_CD6, ICD_DGNS_E_VRSN_CD6, ICD_DGNS_E_CD7, ICD_DGNS_E_VRSN_CD7, ICD_DGNS_E_CD8, ICD_DGNS_E_VRSN_CD8, ICD_DGNS_E_CD9, ICD_DGNS_E_VRSN_CD9, ICD_DGNS_E_CD10, ICD_DGNS_E_VRSN_CD10, ICD_DGNS_E_CD11, ICD_DGNS_E_VRSN_CD11, ICD_DGNS_E_CD12, ICD_DGNS_E_VRSN_CD12, CLM_HOSPC_START_DT_ID, BENE_HOSPC_PRD_CNT, FI_DOC_CLM_CNTL_NUM, FI_ORIG_CLM_CNTL_NUM, CLM_LINE_NUM, REV_CNTR, REV_CNTR_DT, HCPCS_CD, HCPCS_1ST_MDFR_CD, HCPCS_2ND_MDFR_CD, REV_CNTR_UNIT_CNT, REV_CNTR_RATE_AMT, REV_CNTR_PRVDR_PMT_AMT, REV_CNTR_BENE_PMT_AMT, REV_CNTR_PMT_AMT_AMT, REV_CNTR_TOT_CHRG_AMT, REV_CNTR_NCVRD_CHRG_AMT, REV_CNTR_DDCTBL_COINSRNC_CD, REV_CNTR_NDC_QTY, REV_CNTR_NDC_QTY_QLFR_CD, RNDRNG_PHYSN_UPIN, RNDRNG_PHYSN_NPI } private HospiceFields[][] hospiceDxFields = { { HospiceFields.ICD_DGNS_CD1, HospiceFields.ICD_DGNS_VRSN_CD1 }, { HospiceFields.ICD_DGNS_CD2, HospiceFields.ICD_DGNS_VRSN_CD2 }, { HospiceFields.ICD_DGNS_CD3, HospiceFields.ICD_DGNS_VRSN_CD3 }, { HospiceFields.ICD_DGNS_CD4, HospiceFields.ICD_DGNS_VRSN_CD4 }, { HospiceFields.ICD_DGNS_CD5, HospiceFields.ICD_DGNS_VRSN_CD5 }, { HospiceFields.ICD_DGNS_CD6, HospiceFields.ICD_DGNS_VRSN_CD6 }, { HospiceFields.ICD_DGNS_CD7, HospiceFields.ICD_DGNS_VRSN_CD7 }, { HospiceFields.ICD_DGNS_CD8, HospiceFields.ICD_DGNS_VRSN_CD8 }, { HospiceFields.ICD_DGNS_CD9, HospiceFields.ICD_DGNS_VRSN_CD9 }, { HospiceFields.ICD_DGNS_CD10, HospiceFields.ICD_DGNS_VRSN_CD10 }, { HospiceFields.ICD_DGNS_CD11, HospiceFields.ICD_DGNS_VRSN_CD11 }, { HospiceFields.ICD_DGNS_CD12, HospiceFields.ICD_DGNS_VRSN_CD12 }, { HospiceFields.ICD_DGNS_CD13, HospiceFields.ICD_DGNS_VRSN_CD13 }, { HospiceFields.ICD_DGNS_CD14, HospiceFields.ICD_DGNS_VRSN_CD14 }, { HospiceFields.ICD_DGNS_CD15, HospiceFields.ICD_DGNS_VRSN_CD15 }, { HospiceFields.ICD_DGNS_CD16, HospiceFields.ICD_DGNS_VRSN_CD16 }, { HospiceFields.ICD_DGNS_CD17, HospiceFields.ICD_DGNS_VRSN_CD17 }, { HospiceFields.ICD_DGNS_CD18, HospiceFields.ICD_DGNS_VRSN_CD18 }, { HospiceFields.ICD_DGNS_CD19, HospiceFields.ICD_DGNS_VRSN_CD19 }, { HospiceFields.ICD_DGNS_CD20, HospiceFields.ICD_DGNS_VRSN_CD20 }, { HospiceFields.ICD_DGNS_CD21, HospiceFields.ICD_DGNS_VRSN_CD21 }, { HospiceFields.ICD_DGNS_CD22, HospiceFields.ICD_DGNS_VRSN_CD22 }, { HospiceFields.ICD_DGNS_CD23, HospiceFields.ICD_DGNS_VRSN_CD23 }, { HospiceFields.ICD_DGNS_CD24, HospiceFields.ICD_DGNS_VRSN_CD24 }, { HospiceFields.ICD_DGNS_CD25, HospiceFields.ICD_DGNS_VRSN_CD25 } }; public enum SNFFields { DML_IND, BENE_ID, CLM_ID, CLM_GRP_ID, FINAL_ACTION, NCH_NEAR_LINE_REC_IDENT_CD, NCH_CLM_TYPE_CD, CLM_FROM_DT, CLM_THRU_DT, NCH_WKLY_PROC_DT, FI_CLM_PROC_DT, CLAIM_QUERY_CODE, PRVDR_NUM, CLM_FAC_TYPE_CD, CLM_SRVC_CLSFCTN_TYPE_CD, CLM_FREQ_CD, FI_NUM, CLM_MDCR_NON_PMT_RSN_CD, CLM_PMT_AMT, NCH_PRMRY_PYR_CLM_PD_AMT, NCH_PRMRY_PYR_CD, FI_CLM_ACTN_CD, PRVDR_STATE_CD, ORG_NPI_NUM, AT_PHYSN_UPIN, AT_PHYSN_NPI, OP_PHYSN_UPIN, OP_PHYSN_NPI, OT_PHYSN_UPIN, OT_PHYSN_NPI, CLM_MCO_PD_SW, PTNT_DSCHRG_STUS_CD, CLM_PPS_IND_CD, CLM_TOT_CHRG_AMT, CLM_ADMSN_DT, CLM_IP_ADMSN_TYPE_CD, CLM_SRC_IP_ADMSN_CD, NCH_PTNT_STATUS_IND_CD, NCH_BENE_IP_DDCTBL_AMT, NCH_BENE_PTA_COINSRNC_LBLTY_AM, NCH_BENE_BLOOD_DDCTBL_LBLTY_AM, NCH_IP_NCVRD_CHRG_AMT, NCH_IP_TOT_DDCTN_AMT, CLM_PPS_CPTL_FSP_AMT, CLM_PPS_CPTL_OUTLIER_AMT, CLM_PPS_CPTL_DSPRPRTNT_SHR_AMT, CLM_PPS_CPTL_IME_AMT, CLM_PPS_CPTL_EXCPTN_AMT, CLM_PPS_OLD_CPTL_HLD_HRMLS_AMT, CLM_UTLZTN_DAY_CNT, BENE_TOT_COINSRNC_DAYS_CNT, CLM_NON_UTLZTN_DAYS_CNT, NCH_BLOOD_PNTS_FRNSHD_QTY, NCH_QLFYD_STAY_FROM_DT, NCH_QLFYD_STAY_THRU_DT, NCH_VRFD_NCVRD_STAY_FROM_DT, NCH_VRFD_NCVRD_STAY_THRU_DT, NCH_ACTV_OR_CVRD_LVL_CARE_THRU, NCH_BENE_MDCR_BNFTS_EXHTD_DT_I, NCH_BENE_DSCHRG_DT, CLM_DRG_CD, ADMTG_DGNS_CD, ADMTG_DGNS_VRSN_CD, PRNCPAL_DGNS_CD, PRNCPAL_DGNS_VRSN_CD, ICD_DGNS_CD1, ICD_DGNS_VRSN_CD1, ICD_DGNS_CD2, ICD_DGNS_VRSN_CD2, ICD_DGNS_CD3, ICD_DGNS_VRSN_CD3, ICD_DGNS_CD4, ICD_DGNS_VRSN_CD4, ICD_DGNS_CD5, ICD_DGNS_VRSN_CD5, ICD_DGNS_CD6, ICD_DGNS_VRSN_CD6, ICD_DGNS_CD7, ICD_DGNS_VRSN_CD7, ICD_DGNS_CD8, ICD_DGNS_VRSN_CD8, ICD_DGNS_CD9, ICD_DGNS_VRSN_CD9, ICD_DGNS_CD10, ICD_DGNS_VRSN_CD10, ICD_DGNS_CD11, ICD_DGNS_VRSN_CD11, ICD_DGNS_CD12, ICD_DGNS_VRSN_CD12, ICD_DGNS_CD13, ICD_DGNS_VRSN_CD13, ICD_DGNS_CD14, ICD_DGNS_VRSN_CD14, ICD_DGNS_CD15, ICD_DGNS_VRSN_CD15, ICD_DGNS_CD16, ICD_DGNS_VRSN_CD16, ICD_DGNS_CD17, ICD_DGNS_VRSN_CD17, ICD_DGNS_CD18, ICD_DGNS_VRSN_CD18, ICD_DGNS_CD19, ICD_DGNS_VRSN_CD19, ICD_DGNS_CD20, ICD_DGNS_VRSN_CD20, ICD_DGNS_CD21, ICD_DGNS_VRSN_CD21, ICD_DGNS_CD22, ICD_DGNS_VRSN_CD22, ICD_DGNS_CD23, ICD_DGNS_VRSN_CD23, ICD_DGNS_CD24, ICD_DGNS_VRSN_CD24, ICD_DGNS_CD25, ICD_DGNS_VRSN_CD25, FST_DGNS_E_CD, FST_DGNS_E_VRSN_CD, ICD_DGNS_E_CD1, ICD_DGNS_E_VRSN_CD1, ICD_DGNS_E_CD2, ICD_DGNS_E_VRSN_CD2, ICD_DGNS_E_CD3, ICD_DGNS_E_VRSN_CD3, ICD_DGNS_E_CD4, ICD_DGNS_E_VRSN_CD4, ICD_DGNS_E_CD5, ICD_DGNS_E_VRSN_CD5, ICD_DGNS_E_CD6, ICD_DGNS_E_VRSN_CD6, ICD_DGNS_E_CD7, ICD_DGNS_E_VRSN_CD7, ICD_DGNS_E_CD8, ICD_DGNS_E_VRSN_CD8, ICD_DGNS_E_CD9, ICD_DGNS_E_VRSN_CD9, ICD_DGNS_E_CD10, ICD_DGNS_E_VRSN_CD10, ICD_DGNS_E_CD11, ICD_DGNS_E_VRSN_CD11, ICD_DGNS_E_CD12, ICD_DGNS_E_VRSN_CD12, ICD_PRCDR_CD1, ICD_PRCDR_VRSN_CD1, PRCDR_DT1, ICD_PRCDR_CD2, ICD_PRCDR_VRSN_CD2, PRCDR_DT2, ICD_PRCDR_CD3, ICD_PRCDR_VRSN_CD3, PRCDR_DT3, ICD_PRCDR_CD4, ICD_PRCDR_VRSN_CD4, PRCDR_DT4, ICD_PRCDR_CD5, ICD_PRCDR_VRSN_CD5, PRCDR_DT5, ICD_PRCDR_CD6, ICD_PRCDR_VRSN_CD6, PRCDR_DT6, ICD_PRCDR_CD7, ICD_PRCDR_VRSN_CD7, PRCDR_DT7, ICD_PRCDR_CD8, ICD_PRCDR_VRSN_CD8, PRCDR_DT8, ICD_PRCDR_CD9, ICD_PRCDR_VRSN_CD9, PRCDR_DT9, ICD_PRCDR_CD10, ICD_PRCDR_VRSN_CD10, PRCDR_DT10, ICD_PRCDR_CD11, ICD_PRCDR_VRSN_CD11, PRCDR_DT11, ICD_PRCDR_CD12, ICD_PRCDR_VRSN_CD12, PRCDR_DT12, ICD_PRCDR_CD13, ICD_PRCDR_VRSN_CD13, PRCDR_DT13, ICD_PRCDR_CD14, ICD_PRCDR_VRSN_CD14, PRCDR_DT14, ICD_PRCDR_CD15, ICD_PRCDR_VRSN_CD15, PRCDR_DT15, ICD_PRCDR_CD16, ICD_PRCDR_VRSN_CD16, PRCDR_DT16, ICD_PRCDR_CD17, ICD_PRCDR_VRSN_CD17, PRCDR_DT17, ICD_PRCDR_CD18, ICD_PRCDR_VRSN_CD18, PRCDR_DT18, ICD_PRCDR_CD19, ICD_PRCDR_VRSN_CD19, PRCDR_DT19, ICD_PRCDR_CD20, ICD_PRCDR_VRSN_CD20, PRCDR_DT20, ICD_PRCDR_CD21, ICD_PRCDR_VRSN_CD21, PRCDR_DT21, ICD_PRCDR_CD22, ICD_PRCDR_VRSN_CD22, PRCDR_DT22, ICD_PRCDR_CD23, ICD_PRCDR_VRSN_CD23, PRCDR_DT23, ICD_PRCDR_CD24, ICD_PRCDR_VRSN_CD24, PRCDR_DT24, ICD_PRCDR_CD25, ICD_PRCDR_VRSN_CD25, PRCDR_DT25, FI_DOC_CLM_CNTL_NUM, FI_ORIG_CLM_CNTL_NUM, CLM_LINE_NUM, REV_CNTR, HCPCS_CD, REV_CNTR_UNIT_CNT, REV_CNTR_RATE_AMT, REV_CNTR_TOT_CHRG_AMT, REV_CNTR_NCVRD_CHRG_AMT, REV_CNTR_DDCTBL_COINSRNC_CD, REV_CNTR_NDC_QTY, REV_CNTR_NDC_QTY_QLFR_CD, RNDRNG_PHYSN_UPIN, RNDRNG_PHYSN_NPI } private SNFFields[][] snfDxFields = { { SNFFields.ICD_DGNS_CD1, SNFFields.ICD_DGNS_VRSN_CD1 }, { SNFFields.ICD_DGNS_CD2, SNFFields.ICD_DGNS_VRSN_CD2 }, { SNFFields.ICD_DGNS_CD3, SNFFields.ICD_DGNS_VRSN_CD3 }, { SNFFields.ICD_DGNS_CD4, SNFFields.ICD_DGNS_VRSN_CD4 }, { SNFFields.ICD_DGNS_CD5, SNFFields.ICD_DGNS_VRSN_CD5 }, { SNFFields.ICD_DGNS_CD6, SNFFields.ICD_DGNS_VRSN_CD6 }, { SNFFields.ICD_DGNS_CD7, SNFFields.ICD_DGNS_VRSN_CD7 }, { SNFFields.ICD_DGNS_CD8, SNFFields.ICD_DGNS_VRSN_CD8 }, { SNFFields.ICD_DGNS_CD9, SNFFields.ICD_DGNS_VRSN_CD9 }, { SNFFields.ICD_DGNS_CD10, SNFFields.ICD_DGNS_VRSN_CD10 }, { SNFFields.ICD_DGNS_CD11, SNFFields.ICD_DGNS_VRSN_CD11 }, { SNFFields.ICD_DGNS_CD12, SNFFields.ICD_DGNS_VRSN_CD12 }, { SNFFields.ICD_DGNS_CD13, SNFFields.ICD_DGNS_VRSN_CD13 }, { SNFFields.ICD_DGNS_CD14, SNFFields.ICD_DGNS_VRSN_CD14 }, { SNFFields.ICD_DGNS_CD15, SNFFields.ICD_DGNS_VRSN_CD15 }, { SNFFields.ICD_DGNS_CD16, SNFFields.ICD_DGNS_VRSN_CD16 }, { SNFFields.ICD_DGNS_CD17, SNFFields.ICD_DGNS_VRSN_CD17 }, { SNFFields.ICD_DGNS_CD18, SNFFields.ICD_DGNS_VRSN_CD18 }, { SNFFields.ICD_DGNS_CD19, SNFFields.ICD_DGNS_VRSN_CD19 }, { SNFFields.ICD_DGNS_CD20, SNFFields.ICD_DGNS_VRSN_CD20 }, { SNFFields.ICD_DGNS_CD21, SNFFields.ICD_DGNS_VRSN_CD21 }, { SNFFields.ICD_DGNS_CD22, SNFFields.ICD_DGNS_VRSN_CD22 }, { SNFFields.ICD_DGNS_CD23, SNFFields.ICD_DGNS_VRSN_CD23 }, { SNFFields.ICD_DGNS_CD24, SNFFields.ICD_DGNS_VRSN_CD24 }, { SNFFields.ICD_DGNS_CD25, SNFFields.ICD_DGNS_VRSN_CD25 } }; private SNFFields[][] snfPxFields = { { SNFFields.ICD_PRCDR_CD1, SNFFields.ICD_PRCDR_VRSN_CD1, SNFFields.PRCDR_DT1 }, { SNFFields.ICD_PRCDR_CD2, SNFFields.ICD_PRCDR_VRSN_CD2, SNFFields.PRCDR_DT2 }, { SNFFields.ICD_PRCDR_CD3, SNFFields.ICD_PRCDR_VRSN_CD3, SNFFields.PRCDR_DT3 }, { SNFFields.ICD_PRCDR_CD4, SNFFields.ICD_PRCDR_VRSN_CD4, SNFFields.PRCDR_DT4 }, { SNFFields.ICD_PRCDR_CD5, SNFFields.ICD_PRCDR_VRSN_CD5, SNFFields.PRCDR_DT5 }, { SNFFields.ICD_PRCDR_CD6, SNFFields.ICD_PRCDR_VRSN_CD6, SNFFields.PRCDR_DT6 }, { SNFFields.ICD_PRCDR_CD7, SNFFields.ICD_PRCDR_VRSN_CD7, SNFFields.PRCDR_DT7 }, { SNFFields.ICD_PRCDR_CD8, SNFFields.ICD_PRCDR_VRSN_CD8, SNFFields.PRCDR_DT8 }, { SNFFields.ICD_PRCDR_CD9, SNFFields.ICD_PRCDR_VRSN_CD9, SNFFields.PRCDR_DT9 }, { SNFFields.ICD_PRCDR_CD10, SNFFields.ICD_PRCDR_VRSN_CD10, SNFFields.PRCDR_DT10 }, { SNFFields.ICD_PRCDR_CD11, SNFFields.ICD_PRCDR_VRSN_CD11, SNFFields.PRCDR_DT11 }, { SNFFields.ICD_PRCDR_CD12, SNFFields.ICD_PRCDR_VRSN_CD12, SNFFields.PRCDR_DT12 }, { SNFFields.ICD_PRCDR_CD13, SNFFields.ICD_PRCDR_VRSN_CD13, SNFFields.PRCDR_DT13 }, { SNFFields.ICD_PRCDR_CD14, SNFFields.ICD_PRCDR_VRSN_CD14, SNFFields.PRCDR_DT14 }, { SNFFields.ICD_PRCDR_CD15, SNFFields.ICD_PRCDR_VRSN_CD15, SNFFields.PRCDR_DT15 }, { SNFFields.ICD_PRCDR_CD16, SNFFields.ICD_PRCDR_VRSN_CD16, SNFFields.PRCDR_DT16 }, { SNFFields.ICD_PRCDR_CD17, SNFFields.ICD_PRCDR_VRSN_CD17, SNFFields.PRCDR_DT17 }, { SNFFields.ICD_PRCDR_CD18, SNFFields.ICD_PRCDR_VRSN_CD18, SNFFields.PRCDR_DT18 }, { SNFFields.ICD_PRCDR_CD19, SNFFields.ICD_PRCDR_VRSN_CD19, SNFFields.PRCDR_DT19 }, { SNFFields.ICD_PRCDR_CD20, SNFFields.ICD_PRCDR_VRSN_CD20, SNFFields.PRCDR_DT20 }, { SNFFields.ICD_PRCDR_CD21, SNFFields.ICD_PRCDR_VRSN_CD21, SNFFields.PRCDR_DT21 }, { SNFFields.ICD_PRCDR_CD22, SNFFields.ICD_PRCDR_VRSN_CD22, SNFFields.PRCDR_DT22 }, { SNFFields.ICD_PRCDR_CD23, SNFFields.ICD_PRCDR_VRSN_CD23, SNFFields.PRCDR_DT23 }, { SNFFields.ICD_PRCDR_CD24, SNFFields.ICD_PRCDR_VRSN_CD24, SNFFields.PRCDR_DT24 }, { SNFFields.ICD_PRCDR_CD25, SNFFields.ICD_PRCDR_VRSN_CD25, SNFFields.PRCDR_DT25 } }; private static class SingletonHolder { /** * Singleton instance of the CSVExporter. */ private static final BB2RIFExporter instance = new BB2RIFExporter(); } /** * Get the current instance of the BBExporter. * * @return the current instance of the BBExporter. */ public static BB2RIFExporter getInstance() { return SingletonHolder.instance; } /** * Utility class for dealing with code mapping configuration writers. */ static class CodeMapper { private static boolean requireCodeMaps = Config.getAsBoolean( "exporter.bfd.require_code_maps", true); private HashMap<String, List<Map<String, String>>> map; /** * Create a new CodeMapper for the supplied JSON string. * @param jsonMap a stringified JSON mapping writer. Expects the following format: * <pre> * { * "synthea_code": [ # each synthea code will be mapped to one of the codes in this array * { * "code": "BFD_code", * "description": "Description of code", # optional * "other field": "value of other field" # optional additional fields * } * ] * } * </pre> */ public CodeMapper(String jsonMap) { try { String json = Utilities.readResource(jsonMap); Gson g = new Gson(); Type type = new TypeToken<HashMap<String,List<Map<String, String>>>>(){}.getType(); map = g.fromJson(json, type); } catch (JsonSyntaxException | IOException | IllegalArgumentException e) { if (requireCodeMaps) { throw new MissingResourceException("Unable to read code map file: " + jsonMap, "CodeMapper", jsonMap); } else { // For testing, the mapping writer is not present. System.out.println("BB2Exporter is running without " + jsonMap); } } } /** * Determines whether this mapper has an entry for the supplied code. * @param codeToMap the Synthea code to look for * @return true if the Synthea code can be mapped to BFD, false if not */ public boolean canMap(String codeToMap) { if (map == null) { return false; } return map.containsKey(codeToMap); } /** * Get one of the BFD codes for the supplied Synthea code. Equivalent to * {@code map(codeToMap, "code", rand)}. * @param codeToMap the Synthea code to look for * @param rand a source of random numbers used to pick one of the list of BFD codes * @return the BFD code or null if the code can't be mapped */ public String map(String codeToMap, RandomNumberGenerator rand) { return map(codeToMap, "code", rand); } /** * Get one of the BFD codes for the supplied Synthea code. Equivalent to * {@code map(codeToMap, "code", rand)}. * @param codeToMap the Synthea code to look for * @param rand a source of random numbers used to pick one of the list of BFD codes * @param stripDots whether to remove dots in codes (e.g. J39.45 -> J3945) * @return the BFD code or null if the code can't be mapped */ public String map(String codeToMap, RandomNumberGenerator rand, boolean stripDots) { return map(codeToMap, "code", rand, stripDots); } /** * Get one of the BFD codes for the supplied Synthea code. * @param codeToMap the Synthea code to look for * @param bfdCodeType the type of BFD code to map to * @param rand a source of random numbers used to pick one of the list of BFD codes * @return the BFD code or null if the code can't be mapped */ public String map(String codeToMap, String bfdCodeType, RandomNumberGenerator rand) { return map(codeToMap, bfdCodeType, rand, false); } /** * Get one of the BFD codes for the supplied Synthea code. * @param codeToMap the Synthea code to look for * @param bfdCodeType the type of BFD code to map to * @param rand a source of random numbers used to pick one of the list of BFD codes * @param stripDots whether to remove dots in codes (e.g. J39.45 -> J3945) * @return the BFD code or null if the code can't be mapped */ public String map(String codeToMap, String bfdCodeType, RandomNumberGenerator rand, boolean stripDots) { if (!canMap(codeToMap)) { return null; } List<Map<String, String>> options = map.get(codeToMap); int choice = rand.randInt(options.size()); String code = options.get(choice).get(bfdCodeType); if (stripDots) { return code.replaceAll("\\.", ""); } else { return code; } } } /** * Utility class for writing to BB2 writers. */ private static class SynchronizedBBLineWriter { private String bbFieldSeparator = "|"; private Path path; /** * Construct a new instance. Fields will be separated using the default '|' character. * @param path the file path to write to * @throws IOException if something goes wrong */ public SynchronizedBBLineWriter(Path path) { this.path = path; } /** * Construct a new instance. * @param path the file path to write to * @param separator overrides the default '|' field separator * @throws IOException if something goes wrong */ public SynchronizedBBLineWriter(Path path, String separator) { this.bbFieldSeparator = separator; this.path = path; } /** * Write a line of output consisting of one or more fields separated by '|' and terminated with * a system new line. * @param fields the fields that will be concatenated into the line * @throws IOException if something goes wrong */ private void writeLine(String... fields) { String line = String.join(bbFieldSeparator, fields); Exporter.appendToFile(path, line); } /** * Write a BB2 writer header. * @param enumClass the enumeration class whose members define the column names * @throws IOException if something goes wrong */ public <E extends Enum<E>> void writeHeader(Class<E> enumClass) throws IOException { String[] fields = Arrays.stream(enumClass.getEnumConstants()).map(Enum::name) .toArray(String[]::new); writeLine(fields); } /** * Write a BB2 writer line. * @param enumClass the enumeration class whose members define the column names * @param fieldValues a sparse map of column names to values, missing values will result in * empty values in the corresponding column * @throws IOException if something goes wrong */ public <E extends Enum<E>> void writeValues(Class<E> enumClass, Map<E, String> fieldValues) throws IOException { String[] fields = Arrays.stream(enumClass.getEnumConstants()) .map((e) -> fieldValues.getOrDefault(e, "")).toArray(String[]::new); writeLine(fields); } /** * Get the file that this writer writes to. * @return the file */ public File getFile() { return path.toFile(); } } /** * Class to manage mapping values in the static BFD TSV writer to the exported writers. */ public static class StaticFieldConfig { List<LinkedHashMap<String, String>> config; Map<String, LinkedHashMap<String, String>> configMap; /** * Default constructor that parses the TSV config writer. * @throws IOException if the writer can't be read. */ public StaticFieldConfig() throws IOException { String tsv = Utilities.readResource("export/bfd_field_values.tsv"); config = SimpleCSV.parse(tsv, '\t'); configMap = new HashMap<>(); for (LinkedHashMap<String, String> row: config) { configMap.put(row.get("Field"), row); } } /** * Only used for unit tests. * @param <E> the type parameter * @param field the name of a value in the supplied enum class (e.g. DML_IND). * @param tableEnum one of the exporter enums (e.g. InpatientFields or OutpatientFields). * @return the cell value in the TSV where field identifies the row and tableEnum is the column. */ <E extends Enum<E>> String getValue(String field, Class<E> tableEnum) { return configMap.get(field).get(tableEnum.getSimpleName()); } Set<String> validateTSV() { LinkedHashSet tsvIssues = new LinkedHashSet<>(); Class<?>[] tableEnums = { BeneficiaryFields.class, BeneficiaryHistoryFields.class, InpatientFields.class, OutpatientFields.class, CarrierFields.class, PrescriptionFields.class, DMEFields.class }; for (Class tableEnum: tableEnums) { String columnName = tableEnum.getSimpleName(); Method valueOf; try { valueOf = tableEnum.getMethod("valueOf", String.class); } catch (NoSuchMethodException | SecurityException ex) { // this should never happen since tableEnum has to be an enum which will have a valueOf // method but the compiler isn't clever enought to figure that out throw new IllegalArgumentException(ex); } for (LinkedHashMap<String, String> row: config) { String cellContents = stripComments(row.get(columnName)); if (cellContents.equalsIgnoreCase("N/A") || cellContents.equalsIgnoreCase("Coded") || cellContents.equalsIgnoreCase("[Blank]")) { continue; // Skip fields that aren't used are required to be blank or are hand-coded } else if (isMacro(cellContents)) { tsvIssues.add(String.format( "Skipping macro in TSV line %s [%s] for %s", row.get("Line"), row.get("Field"), columnName)); continue; // Skip unsupported macro's in the TSV } else if (cellContents.isEmpty()) { tsvIssues.add(String.format( "Empty cell in TSV line %s [%s] for %s", row.get("Line"), row.get("Field"), columnName)); continue; // Skip empty cells } try { Enum enumVal = (Enum)valueOf.invoke(null, row.get("Field")); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { // This should only happen if the TSV contains a value for a field when the // columnName enum does not contain that field value. tsvIssues.add(String.format( "Error in TSV line %s [%s] for %s (field not in enum): %s", row.get("Line"), row.get("Field"), columnName, ex.toString())); } } } return tsvIssues; } /** * Set the configured values from the BFD TSV into the supplied map. * @param <E> the type parameter. * @param values the map that will receive the TSV-configured values. * @param tableEnum the enum class for the BFD table (e.g. InpatientFields or OutpatientFields). * @param rand source of randomness */ public <E extends Enum<E>> void setValues(HashMap<E, String> values, Class<E> tableEnum, RandomNumberGenerator rand) { // Get the name of the columnName to populate. This must match a column name in the // config TSV. String columnName = tableEnum.getSimpleName(); // Get the valueOf method for the supplied enum using reflection. // We'll use this to convert the string field name to the corresponding enum value Method valueOf; try { valueOf = tableEnum.getMethod("valueOf", String.class); } catch (NoSuchMethodException | SecurityException ex) { // this should never happen since tableEnum has to be an enum which will have a valueOf // method but the compiler isn't clever enought to figure that out throw new IllegalArgumentException(ex); } // Iterate over all of the rows in the TSV for (LinkedHashMap<String, String> row: config) { String cellContents = stripComments(row.get(columnName)); String value = null; if (cellContents.equalsIgnoreCase("N/A") || cellContents.equalsIgnoreCase("Coded")) { continue; // Skip fields that aren't used or are hand-coded } else if (cellContents.equalsIgnoreCase("[Blank]")) { value = " "; // Literally blank } else if (isMacro(cellContents)) { continue; // Skip unsupported macro's in the TSV } else if (cellContents.isEmpty()) { continue; // Skip empty cells } else { value = processCell(cellContents, rand); } try { E enumVal = (E)valueOf.invoke(null, row.get("Field")); values.put(enumVal, value); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { // This should only happen if the TSV contains a value for a field when the // columnName enum does not contain that field value. } } } /** * Remove comments (that consist of text in braces like this) and white space. Note that * this is greedy so "(foo) bar (baz)" would yield "". * @param str the string to strip * @return str with comments and white space removed. */ private static String stripComments(String str) { str = str.replaceAll("\\(.*\\)", ""); return str.trim(); } private static boolean isMacro(String cellContents) { return cellContents.startsWith("["); } /** * Process a TSV cell. Content should be either a single value or a comma separated list of * value. Single values will be returned unchanged, if a list of values is supplied then one * is chosen at random and returned with any leading or trailing white space removed. * @param cellContents TSV cell contents. * @param rand a source of randomness. * @return the selected value. */ static String processCell(String cellContents, RandomNumberGenerator rand) { String retval = cellContents; if (cellContents.contains(",")) { List<String> values = Arrays.asList(retval.split(",")); int index = rand.randInt(values.size()); retval = values.get(index).trim(); } return retval; } } static class CLIA extends FixedLengthIdentifier { private static final char[][] CLIA_FORMAT = {NUMERIC, NUMERIC, ALPHA, NUMERIC, NUMERIC, NUMERIC, NUMERIC, NUMERIC, NUMERIC, NUMERIC}; static final long MIN_CLIA = 0; static final long MAX_CLIA = maxValue(CLIA_FORMAT); public CLIA(long value) { super(value, CLIA_FORMAT); } static CLIA parse(String str) { return new CLIA(parse(str, CLIA_FORMAT)); } public CLIA next() { return new CLIA(value + 1); } } static class MBI extends FixedLengthIdentifier { private static final char[] FIXED = {'S'}; private static final char[][] MBI_FORMAT = {NON_ZERO_NUMERIC, FIXED, ALPHA_NUMERIC, NUMERIC, NON_NUMERIC_LIKE_ALPHA, ALPHA_NUMERIC, NUMERIC, NON_NUMERIC_LIKE_ALPHA, NON_NUMERIC_LIKE_ALPHA, NUMERIC, NUMERIC}; static final long MIN_MBI = 0; static final long MAX_MBI = maxValue(MBI_FORMAT); public MBI(long value) { super(value, MBI_FORMAT); } static MBI parse(String str) { return new MBI(parse(str, MBI_FORMAT)); } public MBI next() { return new MBI(value + 1); } } /** * Utility class for working with CMS Part D Contract IDs. */ static class PartDContractID extends FixedLengthIdentifier { private static final char[][] PARTD_CONTRACT_FORMAT = { ALPHA, NUMERIC, NUMERIC, NUMERIC, NUMERIC}; static final long MIN_PARTD_CONTRACT_ID = 0; static final long MAX_PARTD_CONTRACT_ID = maxValue(PARTD_CONTRACT_FORMAT); public PartDContractID(long value) { super(value, PARTD_CONTRACT_FORMAT); } static PartDContractID parse(String str) { return new PartDContractID(parse(str, PARTD_CONTRACT_FORMAT)); } public PartDContractID next() { return new PartDContractID(value + 1); } } static class HICN extends FixedLengthIdentifier { private static final char[] START = {'T'}; private static final char[] END = {'A'}; private static final char[][] HICN_FORMAT = {START, NUMERIC, NUMERIC, NUMERIC, NUMERIC, NUMERIC, NUMERIC, NUMERIC, NUMERIC, END}; static final long MIN_HICN = 0; static final long MAX_HICN = maxValue(HICN_FORMAT); public HICN(long value) { super(value, HICN_FORMAT); } static HICN parse(String str) { return new HICN(parse(str, HICN_FORMAT)); } public HICN next() { return new HICN(value + 1); } } private static class FixedLengthIdentifier { static final char[] NUMERIC = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; static final char[] NON_ZERO_NUMERIC = {'1', '2', '3', '4', '5', '6', '7', '8', '9'}; static final char[] ALPHA = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; static final char[] NON_NUMERIC_LIKE_ALPHA = { 'A', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'T', 'U', 'V', 'W', 'X', 'Y' }; static final char[] ALPHA_NUMERIC = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'T', 'U', 'V', 'W', 'X', 'Y' }; private final char[][] format; long value; public FixedLengthIdentifier(long value, char[][] format) { this.format = format; if (value < 0 || value > maxValue(format)) { throw new IllegalArgumentException(String.format("Value (%d) out of range (%d - %d)", value, 0, maxValue(format))); } this.value = value; } protected static long parse(String str, char[][] format) { str = str.replaceAll("-", "").toUpperCase(); if (str.length() != format.length) { throw new IllegalArgumentException(String.format( "Invalid format (%s), must be %d characters", str, format.length)); } long v = 0; for (int i = 0; i < format.length; i++) { int multiplier = format[i].length; v = v * multiplier; char c = str.charAt(i); char[] range = format[i]; int index = indexOf(range, c); if (index == -1) { throw new IllegalArgumentException(String.format( "Unexpected character (%c) at position %d in %s", c, i, str)); } v += index; } return v; } protected static long maxValue(char[][] format) { long max = 1; for (char[] range : format) { max = max * range.length; } return max - 1; } private static int indexOf(char[] arr, char v) { for (int i = 0; i < arr.length; i++) { if (arr[i] == v) { return i; } } return -1; } @Override public String toString() { StringBuilder sb = new StringBuilder(); long v = this.value; for (int i = 0; i < format.length; i++) { char[] range = format[format.length - i - 1]; long p = v % range.length; sb.insert(0, range[(int)p]); v = v / range.length; } return sb.toString(); } @Override public int hashCode() { int hash = 5; hash = 53 * hash + (int) (this.value ^ (this.value >>> 32)); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final FixedLengthIdentifier other = (FixedLengthIdentifier) obj; if (this.value != other.value) { return false; } return true; } } private static class BeneficiaryWriters { private final TreeMap<Integer, SynchronizedBBLineWriter> writers; private final Path dir; public BeneficiaryWriters(Path dir) { this.dir = dir; this.writers = new TreeMap<>(); } public synchronized SynchronizedBBLineWriter getWriter(int year) throws IOException { SynchronizedBBLineWriter writer = writers.get(year); if (writer == null) { Path beneficiaryFile = dir.resolve(String.format("beneficiary_%d.csv", year)); writer = new SynchronizedBBLineWriter(beneficiaryFile); writers.put(year, writer); writer.writeHeader(BeneficiaryFields.class); } return writer; } public synchronized List<File> getFiles() { ArrayList<File> list = new ArrayList<>(writers.size()); writers.values().forEach(writer -> { list.add(writer.getFile()); }); return list; } } }
package org.moonlightcontroller.spammer; import java.util.ArrayList; import java.util.List; import org.moonlightcontroller.managers.models.messages.Alert; import org.moonlightcontroller.managers.models.messages.AlertMessage; import org.moonlightcontroller.managers.models.messages.IMessage; import org.moonlightcontroller.southbound.client.SingleInstanceConnection; public class Spammer { private int xid; private SingleInstanceConnection client; private int sleep; public Spammer(String serverIp, int serverPort, int amountInMinute) { this.client = new SingleInstanceConnection(serverIp, serverPort); this.sleep = (60*1000)/amountInMinute; } public void runSpammer() { while (true) { try { IMessage msg = this.createAlert(); this.client.sendMessage(msg); Thread.sleep(this.sleep); } catch (InterruptedException e) { return; } } } private IMessage createAlert() { int xid = this.fetchAndIncxid(); List<AlertMessage> alerts = new ArrayList<>(); alerts.add(new AlertMessage(1, System.nanoTime(), "Alert from mock OBI", 1, "packet", "AlertChecker.Alert")); Alert alertMessage = new Alert(xid, ObiMock.getInstance().getdpid(), alerts); return alertMessage; } private int fetchAndIncxid(){ int ret = this.xid; this.xid++; return ret; } }
package org.owasp.esapi.util; /** * Conversion to/from byte arrays to/from short, int, long. The assumption * is that they byte arrays are in network byte order (i.e., big-endian * ordered). * * @see org.owasp.esapi.crypto.CipherTextSerializer * @author kevin.w.wall@gmail.com */ public class ByteConversionUtil { ////////// Convert from short, int, long to byte array. ////////// /** * Returns a byte array containing 2 network byte ordered bytes representing * the given {@code short}. * * @param input An {@code short} to convert to a byte array. * @return A byte array representation of an {@code short} in network byte * order (i.e., big-endian order). */ public static byte[] fromShort(short input) { byte[] output = new byte[2]; output[0] = (byte) (input >> 8); output[1] = (byte) input; return output; } /** * Returns a byte array containing 4 network byte-ordered bytes representing the * given {@code int}. * * @param input An {@code int} to convert to a byte array. * @return A byte array representation of an {@code int} in network byte order * (i.e., big-endian order). */ public static byte[] fromInt(int input) { byte[] output = new byte[4]; output[0] = (byte) (input >> 24); output[1] = (byte) (input >> 16); output[2] = (byte) (input >> 8); output[3] = (byte) input; return output; } /** * Returns a byte array containing 8 network byte-ordered bytes representing * the given {@code long}. * * @param input The {@code long} to convert to a {@code byte} array. * @return A byte array representation of a {@code long}. */ public static byte[] fromLong(long input) { byte[] output = new byte[8]; // Note: I've tried using '>>>' instead of '>>' but that seems to // make no difference. The testLongConversion() still fails // in the same manner. output[0] = (byte) (input >> 56); output[1] = (byte) (input >> 48); output[2] = (byte) (input >> 40); output[3] = (byte) (input >> 32); output[4] = (byte) (input >> 24); output[5] = (byte) (input >> 16); output[6] = (byte) (input >> 8); output[7] = (byte) input; return output; } ////////// Convert from byte array to short, int, long. ////////// /** * Converts a given byte array to an {@code short}. Bytes are expected in * network byte * order. * * @param input A network byte-ordered representation of an {@code short}. * @return The {@code short} value represented by the input array. */ public static short toShort(byte[] input) { assert input.length == 2 : "toShort(): Byte array length must be 2."; short output = 0; output = (short)(((input[0] & 0xff) << 8) | (input[1] & 0xff)); return output; } /** * Converts a given byte array to an {@code int}. Bytes are expected in * network byte order. * * @param input A network byte-ordered representation of an {@code int}. * @return The {@code int} value represented by the input array. */ public static int toInt(byte[] input) { assert input.length == 4 : "toInt(): Byte array length must be 4."; int output = 0; output = ((input[0] & 0xff) << 24) | ((input[1] & 0xff) << 16) | ((input[2] & 0xff) << 8) | (input[3] & 0xff); return output; } /** * Converts a given byte array to a {@code long}. Bytes are expected in * network byte * * @param input A network byte-ordered representation of a {@code long}. * @return The {@code long} value represented by the input array */ public static long toLong(byte[] input) { assert input.length == 8 : "toLong(): Byte array length must be 8."; long output = 0; // Tried both of these ways, each w/ and w/out casts, but // testLongConversion() still failing. // output = (long)((input[0] & 0xff) << 56) | ((input[1] & 0xff) << 48) | // ((input[2] & 0xff) << 40) | ((input[3] & 0xff) << 32) | // ((input[4] & 0xff) << 24) | ((input[5] & 0xff) << 16) | // ((input[6] & 0xff) << 8) | (input[7] & 0xff); output = (long)((input[0] & 0xff) << 56); output |= (long)((input[1] & 0xff) << 48); output |= (long)((input[2] & 0xff) << 40); output |= (long)((input[3] & 0xff) << 32); output |= (long)((input[4] & 0xff) << 24); output |= (long)((input[5] & 0xff) << 16); output |= (long)((input[6] & 0xff) << 8); output |= (long)(input[7] & 0xff); return output; } }
package org.owasp.esapi.waf.rules; import java.util.Collection; import java.util.Enumeration; import java.util.Map; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.owasp.esapi.waf.actions.Action; import org.owasp.esapi.waf.actions.DefaultAction; import org.owasp.esapi.waf.actions.DoNothingAction; import org.owasp.esapi.waf.configuration.AppGuardianConfiguration; import org.owasp.esapi.waf.internal.InterceptingHTTPServletRequest; import org.owasp.esapi.waf.internal.InterceptingHTTPServletResponse; /** * This is the Rule subclass executed for &lt;must-match&gt; rules. * @author Arshan Dabirsiaghi * */ public class MustMatchRule extends Rule { private static final String REQUEST_PARAMETERS = "request.parameters."; private static final String REQUEST_HEADERS = "request.headers."; private static final String REQUEST_URI = "request.uri"; private static final String REQUEST_URL = "request.url"; private static final String SESSION_ATTRIBUTES = "session."; private Pattern path; private String variable; private int operator; private String value; public MustMatchRule(String id, Pattern path, String variable, int operator, String value) { this.path = path; this.variable = variable; this.operator = operator; this.value = value; setId(id); } public Action check(HttpServletRequest req, InterceptingHTTPServletResponse response, HttpServletResponse httpResponse) { InterceptingHTTPServletRequest request = (InterceptingHTTPServletRequest)req; String uri = request.getRequestURI(); if ( ! path.matcher(uri).matches() ) { return new DoNothingAction(); } else { String target = null; /* * First check if we're going to be dealing with request parameters */ if ( variable.startsWith( REQUEST_PARAMETERS ) ) { if ( operator == AppGuardianConfiguration.OPERATOR_EXISTS ) { target = variable.substring(REQUEST_PARAMETERS.length()); if ( request.getParameter(target) != null ) { return new DoNothingAction(); } } else if ( operator == AppGuardianConfiguration.OPERATOR_IN_LIST ) { /* * This doesn't make sense. The variable to test is a request parameter * but the rule is looking for a List. Let the control fall through * to the bottom where we'll return false. */ } else if ( operator == AppGuardianConfiguration.OPERATOR_EQ || operator == AppGuardianConfiguration.OPERATOR_CONTAINS ) { /** * Working with request parameters. If we detect * simple regex characters, we treat it as a regex. * Otherwise we treat it as a single parameter. */ target = variable.substring(REQUEST_PARAMETERS.length()); if ( target.contains("*") || target.contains("?") ) { target = target.replaceAll("*", ".*"); Pattern p = Pattern.compile(target); Enumeration e = request.getParameterNames(); while(e.hasMoreElements()) { String param = (String)e.nextElement(); if ( p.matcher(param).matches() ) { String s = request.getParameter(param); if ( ! RuleUtil.testValue(s, value, operator) ) { log(request, "MustMatch rule failed (operator="+operator+"), value='" + value + "', input='" + s + "' parameter='"+param+"'"); return new DefaultAction(); } } } } else { String s = request.getParameter(target); if ( ! RuleUtil.testValue(s, value, operator) ) { log(request, "MustMatch rule failed (operator="+operator+"), value='" + value + "', input='" + s + "', parameter='"+target+"'"); return new DefaultAction(); } } } } else if ( variable.startsWith( REQUEST_HEADERS ) ) { /** * Do the same for request headers. */ if ( operator == AppGuardianConfiguration.OPERATOR_EXISTS ) { target = variable.substring(REQUEST_HEADERS.length()); if ( request.getHeader(target) != null ) { return new DoNothingAction(); } } else if ( operator == AppGuardianConfiguration.OPERATOR_IN_LIST ) { /* * This doesn't make sense. The variable to test is a request header * but the rule is looking for a List. Let the control fall through * to the bottom where we'll return false. */ } else if ( operator == AppGuardianConfiguration.OPERATOR_EQ || operator == AppGuardianConfiguration.OPERATOR_CONTAINS ) { target = variable.substring(REQUEST_HEADERS.length()); if ( target.contains("*") || target.contains("?") ) { target = target.replaceAll("*", ".*"); Pattern p = Pattern.compile(target); Enumeration e = request.getHeaderNames(); while(e.hasMoreElements()) { String header = (String)e.nextElement(); if ( p.matcher(header).matches() ) { String s = request.getHeader(header); if ( ! RuleUtil.testValue(s, value, operator) ) { log(request, "MustMatch rule failed (operator="+operator+"), value='" + value + "', input='" + s + "', header='"+header+"'"); return new DefaultAction(); } } } return new DoNothingAction(); } else { String s = request.getHeader(target); if ( s == null || ! RuleUtil.testValue(s, value, operator) ) { log(request, "MustMatch rule failed (operator="+operator+"), value='" + value + "', input='" + s + "', header='"+target+"'"); return new DefaultAction(); } return new DoNothingAction(); } } } else if ( variable.startsWith(SESSION_ATTRIBUTES) ) { /** * Do the same for session attributes. Can't possibly match * ANY rule if there is no session object. */ if ( request.getSession(false) == null ) { return new DefaultAction(); } target = variable.substring(SESSION_ATTRIBUTES.length()+1); if ( operator == AppGuardianConfiguration.OPERATOR_IN_LIST ) { /* * Want to check if the List/Enumeration/whatever stored * in "target" contains the value in "value". */ Object o = request.getSession(false).getAttribute(target); if ( o instanceof Collection ) { if ( RuleUtil.isInList((Collection)o, value) ) { return new DoNothingAction(); } else { log(request, "MustMatch rule failed - looking for value='" + value + "', in session Collection attribute '" + target + "']"); return new DefaultAction(); } } else if ( o instanceof Map ) { if ( RuleUtil.isInList((Map)o, value) ) { return new DoNothingAction(); } else { log(request, "MustMatch rule failed - looking for value='" + value + "', in session Map attribute '" + target + "']"); return new DefaultAction(); } } else if ( o instanceof Enumeration ) { if ( RuleUtil.isInList((Enumeration)o, value) ) { return new DoNothingAction(); } else { log(request, "MustMatch rule failed - looking for value='" + value + "', in session Enumeration attribute '" + target + "']"); return new DefaultAction(); } } /* * The attribute was not a common list-type of Java object s * let the control fall through to the bottom where it will * fail. */ } else if ( operator == AppGuardianConfiguration.OPERATOR_EXISTS) { Object o = request.getSession(false).getAttribute(target); if ( o != null ) { return new DoNothingAction(); } else { log(request, "MustMatch rule failed - couldn't find required session attribute='" + target + "'"); return new DefaultAction(); } } else if ( operator == AppGuardianConfiguration.OPERATOR_EQ || operator == AppGuardianConfiguration.OPERATOR_CONTAINS ) { if ( target.contains("*") || target.contains("?") ) { target = target.replaceAll("\\*", ".*"); Pattern p = Pattern.compile(target); Enumeration e = request.getSession(false).getAttributeNames(); while(e.hasMoreElements()) { String attr = (String)e.nextElement(); if (p.matcher(attr).matches() ) { Object o = request.getSession(false).getAttribute(attr); if ( ! RuleUtil.testValue((String)o, value, operator) ) { log(request, "MustMatch rule failed (operator="+operator+"), value='" + value + "', session attribute='" + attr + "', attribute value='"+(String)o+"'"); return new DefaultAction(); } else { return new DoNothingAction(); } } } } else { Object o = request.getSession(false).getAttribute(target); if ( ! RuleUtil.testValue((String)o, value, operator) ) { log(request, "MustMatch rule failed (operator="+operator+"), value='" + value + "', session attribute='" + target + "', attribute value='"+(String)o+"'"); return new DefaultAction(); } else { return new DoNothingAction(); } } } } else if ( variable.equals( REQUEST_URI ) ) { if ( operator == AppGuardianConfiguration.OPERATOR_EQ || operator == AppGuardianConfiguration.OPERATOR_CONTAINS ) { if ( RuleUtil.testValue(request.getRequestURI(), value, operator) ) { return new DoNothingAction(); } else { log(request, "MustMatch rule on request URI failed (operator="+operator+"), requestURI='" + request.getRequestURI() + "', value='" + value+ "'"); return new DefaultAction(); } } /* * Any other operator doesn't make sense. */ } else if ( variable.equals( REQUEST_URL ) ) { if ( operator == AppGuardianConfiguration.OPERATOR_EQ || operator == AppGuardianConfiguration.OPERATOR_CONTAINS ) { if ( RuleUtil.testValue(request.getRequestURL().toString(), value, operator) ) { return new DoNothingAction(); } else { log(request, "MustMatch rule on request URL failed (operator="+operator+"), requestURL='" + request.getRequestURL() + "', value='" + value+ "'"); return new DefaultAction(); } } /* * Any other operator doesn't make sense. */ } } log(request, "MustMatch rule failed close on URL '" + request.getRequestURL() + "'"); return new DefaultAction(); } }
package com.akjava.gwt.modelweight.client; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.akjava.bvh.client.BVH; import com.akjava.bvh.client.BVHNode; import com.akjava.bvh.client.BVHParser; import com.akjava.bvh.client.BVHParser.ParserListener; import com.akjava.bvh.client.Vec3; import com.akjava.gwt.bvh.client.threejs.AnimationBoneConverter; import com.akjava.gwt.bvh.client.threejs.AnimationDataConverter; import com.akjava.gwt.bvh.client.threejs.BVHConverter; import com.akjava.gwt.html5.client.InputRangeListener; import com.akjava.gwt.html5.client.InputRangeWidget; import com.akjava.gwt.html5.client.download.HTML5Download; import com.akjava.gwt.html5.client.extra.HTML5Builder; import com.akjava.gwt.html5.client.file.File; import com.akjava.gwt.html5.client.file.FileHandler; import com.akjava.gwt.html5.client.file.FileReader; import com.akjava.gwt.html5.client.file.FileUploadForm; import com.akjava.gwt.html5.client.file.FileUtils; import com.akjava.gwt.html5.client.file.FileUtils.DataURLListener; import com.akjava.gwt.html5.client.file.ui.DropVerticalPanelBase; import com.akjava.gwt.lib.client.IStorageControler; import com.akjava.gwt.lib.client.LogUtils; import com.akjava.gwt.lib.client.StorageControler; import com.akjava.gwt.lib.client.StorageDataList; import com.akjava.gwt.modelweight.client.weight.GWTWeightData; import com.akjava.gwt.modelweight.client.weight.WeighDataParser; import com.akjava.gwt.three.client.gwt.JSONModelFile; import com.akjava.gwt.three.client.gwt.animation.AnimationBone; import com.akjava.gwt.three.client.gwt.animation.AnimationData; import com.akjava.gwt.three.client.gwt.animation.AnimationHierarchyItem; import com.akjava.gwt.three.client.gwt.collada.ColladaData; import com.akjava.gwt.three.client.gwt.core.Intersect; import com.akjava.gwt.three.client.gwt.materials.LineBasicMaterialParameter; import com.akjava.gwt.three.client.gwt.materials.MeshLambertMaterialParameter; import com.akjava.gwt.three.client.java.JClock; import com.akjava.gwt.three.client.java.animation.WeightBuilder; import com.akjava.gwt.three.client.java.ui.SimpleTabDemoEntryPoint; import com.akjava.gwt.three.client.java.utils.GWTGeometryUtils; import com.akjava.gwt.three.client.java.utils.GWTThreeUtils; import com.akjava.gwt.three.client.js.THREE; import com.akjava.gwt.three.client.js.core.Geometry; import com.akjava.gwt.three.client.js.core.Object3D; import com.akjava.gwt.three.client.js.core.Projector; import com.akjava.gwt.three.client.js.extras.GeometryUtils; import com.akjava.gwt.three.client.js.extras.ImageUtils; import com.akjava.gwt.three.client.js.extras.animation.Animation; import com.akjava.gwt.three.client.js.extras.animation.AnimationHandler; import com.akjava.gwt.three.client.js.lights.Light; import com.akjava.gwt.three.client.js.loaders.JSONLoader; import com.akjava.gwt.three.client.js.loaders.JSONLoader.JSONLoadHandler; import com.akjava.gwt.three.client.js.materials.Material; import com.akjava.gwt.three.client.js.math.Euler; import com.akjava.gwt.three.client.js.math.Ray; import com.akjava.gwt.three.client.js.math.Vector3; import com.akjava.gwt.three.client.js.math.Vector4; import com.akjava.gwt.three.client.js.objects.Mesh; import com.akjava.gwt.three.client.js.objects.SkinnedMesh; import com.akjava.gwt.three.client.js.renderers.WebGLRenderer; import com.akjava.gwt.three.client.js.textures.Texture; import com.akjava.lib.common.utils.ColorUtils; import com.akjava.lib.common.utils.FileNames; import com.google.common.collect.Lists; import com.google.gwt.canvas.client.Canvas; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayNumber; import com.google.gwt.core.client.JsArrayString; import com.google.gwt.dom.client.ImageElement; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.DoubleClickEvent; import com.google.gwt.event.dom.client.DropEvent; import com.google.gwt.event.dom.client.LoadEvent; import com.google.gwt.event.dom.client.MouseDownEvent; import com.google.gwt.event.dom.client.MouseMoveEvent; import com.google.gwt.event.dom.client.MouseUpEvent; import com.google.gwt.event.dom.client.MouseWheelEvent; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.http.client.URL; import com.google.gwt.json.client.JSONArray; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONParser; import com.google.gwt.json.client.JSONValue; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.StackLayoutPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class GWTModelWeight extends SimpleTabDemoEntryPoint{ public static final String version="0.5(for r66)";//for three.js r64 double baseScale=10; private double posScale=0.1*baseScale; @Override protected void beforeUpdate(WebGLRenderer renderer) { if(root!=null){ boneAndVertex.getRotation().set(Math.toRadians(rotX),Math.toRadians(rotY),0,Euler.XYZ); boneAndVertex.getPosition().set(posX,posY,0); root.setPosition(posScale*positionXRange.getValue(), posScale*positionYRange.getValue(), posScale*positionZRange.getValue()); root.getRotation().set(Math.toRadians(rotationXRange.getValue()),Math.toRadians(rotationYRange.getValue()),Math.toRadians(rotationZRange.getValue()),Euler.XYZ); } long delta=clock.delta(); //LogUtils.log(""+animation.getCurrentTime()); double v=(double)delta/1000; if(!paused && animation!=null){ AnimationHandler.update(v); currentTime=animation.getCurrentTime(); //LogUtils.log("animation:"+currentTime+","+delta); String check=""+currentTime; if(check.equals("NaN")){ currentTime=0; } if(currentTime<0.25){ //animation.setCurrentTime(0.25); //AnimationHandler.update(v); //skinnedMesh.setVisible(false); }else{ skinnedMesh.setVisible(true); } }else{ if(animation!=null){ currentTime=animation.getCurrentTime(); } } } double currentTime; private IStorageControler storageControler; private JClock clock=new JClock(); private Mesh mouseClickCatcher; @Override protected void initializeOthers(WebGLRenderer renderer) { cameraZ=30; //Window.open("text/plain:test.txt:"+url, "test", null); storageControler = new StorageControler(); canvas.setClearColor(0x333333);//canvas has margin? //scene.add(THREE.AmbientLight(0xffffff)); Light pointLight = THREE.DirectionalLight(0xffffff,1); pointLight.setPosition(0, 10, 300); scene.add(pointLight); Light pointLight2 = THREE.DirectionalLight(0xffffff,1);//for fix back side dark problem pointLight2.setPosition(0, 10, -300); scene.add(pointLight2); projector=THREE.Projector(); //TODO is this really need? mouseClickCatcher=THREE.Mesh(THREE.PlaneGeometry(100, 100, 10, 10), THREE.MeshBasicMaterial().color(0xffff00).wireFrame().build()); mouseClickCatcher.setVisible(false); scene.add(mouseClickCatcher); /* //write test Geometry g=THREE.CubeGeometry(1, 1, 1); LogUtils.log(g); Geometry g2=THREE.CubeGeometry(1, 1, 1); Matrix4 mx=THREE.Matrix4(); mx.setPosition(THREE.Vector3(0,10,0)); //g2.applyMatrix(mx); Mesh tmpM=THREE.Mesh(g2, THREE.MeshBasicMaterial().build()); tmpM.setPosition(0, 10, 0); GeometryUtils.merge(g, tmpM); JSONModelFile model=JSONModelFile.create(); model.setVertices(g.vertices()); model.setFaces(g.faces()); //JSONArray vertices=new JSONArray(nums); JSONObject js=new JSONObject(model); LogUtils.log(js.toString()); scene.add(THREE.AmbientLight(0x888888)); Light pointLight = THREE.PointLight(0xffffff); pointLight.setPosition(0, 10, 300); scene.add(pointLight); */ //loadBVH("14_08.bvh"); /* JSONLoader loader=THREE.JSONLoader(); loader.load("buffalo.js", new LoadHandler() { @Override public void loaded(Geometry geometry) { AnimationHandler.add(geometry.getAnimation()); LogUtils.log(geometry.getBones()); LogUtils.log(geometry.getAnimation()); //JSONObject test=new JSONObject(geometry.getAnimation()); //LogUtils.log(test.toString()); Geometry cube=THREE.CubeGeometry(1, 1, 1); JsArray<Vector4> indices=(JsArray<Vector4>) JsArray.createArray(); JsArray<Vector4> weight=(JsArray<Vector4>) JsArray.createArray(); for(int i=0;i<cube.vertices().length();i++){ Vector4 v4=THREE.Vector4(); v4.set(0, 0, 0, 0); indices.push(v4); Vector4 v4w=THREE.Vector4(); v4w.set(1, 0, 0, 0); weight.push(v4w); } cube.setSkinIndices(indices); cube.setSkinWeight(weight); cube.setBones(geometry.getBones()); //root=boneToCube(geometry.getBones()); //scene.add(root); //SkinnedMesh mesh=THREE.SkinnedMesh(cube, THREE.MeshLambertMaterial().skinning(true).color(0xff0000).build()); //scene.add(mesh); //Animation animation = THREE.Animation( mesh, "take_001" ); //LogUtils.log(animation); //animation.play(); //buffalo } });*/ //stop initial load for test if(debugTab){ LogUtils.log("debug tab mode:main widget not work because of lack of base bvh"); }else{//this action generate skinned mesh and this freeze on debug-mode loadBVH(bvhUrl); } //loadBVH("pose.bvh");//no motion } private boolean debugTab=false; //private PopupPanel bottomPanel;//TODO future private void createTabs(){ tabPanel.addSelectionHandler(new SelectionHandler<Integer>() { @Override public void onSelection(SelectionEvent<Integer> event) { int selection=event.getSelectedItem(); if(selection==0){ stats.setVisible(true); showControl(); //bottomPanel.setVisible(true); popupPanel.setVisible(true); resized(screenWidth,screenHeight);//for some blackout; }else{ stats.setVisible(false); //bottomPanel.setVisible(false); hideControl(); if(popupPanel!=null){//debug mode call this popupPanel.setVisible(false); } } } }); infoPanel = new InfoPanelTab(); infoPanel.setSize("100%", "100%"); tabPanel.add(infoPanel,"Info"); tabPanel.add(new CopyToolPanel(),"Copy"); tabPanel.add(new MergeToolPanel(),"Merge"); tabPanel.add(new ConvertToolPanel(),"Convert"); tabPanel.add(new UvPackToolPanel(),"UvPack"); //for special debug if(debugTab){ tabPanel.selectTab(5); } } Object3D root; //for selection private final int boneJointColor=0x888888; private final int boneCoreColor=0x008800; private final int selectBoneJointColor=0xeeddee; private final int selectBoneCoreColor=0xee88ee; List<Mesh> boneJointMeshs=new ArrayList<Mesh>(); List<Mesh> boneCoreMeshs=new ArrayList<Mesh>(); private List<Mesh> endPointMeshs=new ArrayList<Mesh>(); List<Mesh> tmp=new ArrayList<Mesh>(); private Object3D createBoneObjects(BVH bvh){ boneJointMeshs.clear(); endPointMeshs.clear(); AnimationBoneConverter converter=new AnimationBoneConverter(); JsArray<AnimationBone> bones = converter.convertJsonBone(bvh);//has no endsite List<List<Vector3>> endSites=converter.convertJsonBoneEndSites(bvh); tmp.clear(); Object3D group=THREE.Object3D(); //Vec3 rootBoneOffset=bvh.getHiearchy().getOffset(); //group.getPosition().set(rootBoneOffset.getX(),rootBoneOffset.getY(), rootBoneOffset.getZ()); double boneCoreSize=0.03*baseScale; double halfBonecore=0.02*baseScale; double sitesBonecore=0.02*baseScale; for(int i=0;i<bones.length();i++){ AnimationBone bone=bones.get(i); Geometry cube=THREE.CubeGeometry(boneCoreSize, boneCoreSize, boneCoreSize); Mesh mesh=THREE.Mesh(cube, THREE.MeshLambertMaterial(MeshLambertMaterialParameter.create().color(boneCoreColor))); group.add(mesh); boneCoreMeshs.add(mesh); Vector3 pos=GWTThreeUtils.jsArrayToVector3(bone.getPos()); if(bone.getParent()!=-1){ Vector3 half=pos.clone().multiplyScalar(.5); Vector3 ppos=tmp.get(bone.getParent()).getPosition(); pos.add(ppos); half.add(ppos); double length=ppos.clone().sub(pos).length(); //half Mesh halfMesh=THREE.Mesh(THREE.CubeGeometry(halfBonecore, halfBonecore, length), THREE.MeshLambertMaterial(MeshLambertMaterialParameter.create().color(boneJointColor))); group.add(halfMesh); halfMesh.setPosition(half); halfMesh.lookAt(pos); halfMesh.setName(bones.get(bone.getParent()).getName()); boneJointMeshs.add(halfMesh); } mesh.setPosition(pos); mesh.setName(bone.getName()); //this mesh is for helping auto-weight List<Vector3> sites=endSites.get(i); for(Vector3 end:sites){ Mesh endMesh=THREE.Mesh(THREE.CubeGeometry(sitesBonecore, sitesBonecore, sitesBonecore), THREE.MeshLambertMaterial(MeshLambertMaterialParameter.create().color(0x00a00aa))); if(end.getX()==0 && end.getY()==0 && end.getZ()==0){ continue;//ignore 0 }else{ //LogUtils.log(bone.getName()+":"+ThreeLog.get(end)); } Vector3 epos=end.clone().add(pos); endMesh.setPosition(epos); group.add(GWTGeometryUtils.createLineMesh(pos, epos, 0x888888)); group.add(endMesh); endPointMeshs.add(endMesh); } if(bone.getParent()!=-1){ //AnimationBone parent=bones.get(bone.getParent()); Vector3 ppos=tmp.get(bone.getParent()).getPosition(); Object3D line=THREE.Line(GWTGeometryUtils.createLineGeometry(pos, ppos), THREE.LineBasicMaterial(LineBasicMaterialParameter.create().color(0x888888))); group.add(line); } tmp.add(mesh); } return group; } /* private List<NameAndPosition> boneToNameAndWeight(JsArray<AnimationBone> bones){ return boneToNameAndWeight(bones,null); } private List<NameAndPosition> boneToNameAndWeight(JsArray<AnimationBone> bones,List<List<Vector3>> endSites){ List<NameAndPosition> lists=new ArrayList<NameAndPosition>(); List<Vector3> absolutePos=new ArrayList<Vector3>(); for(int i=0;i<bones.length();i++){ AnimationBone bone=bones.get(i); Vector3 pos=GWTThreeUtils.jsArrayToVector3(bone.getPos()); String parentName=null; //add start //add center Vector3 parentPos=null; Vector3 endPos=null; int parentIndex=0; if(bone.getParent()!=-1){ parentIndex=bone.getParent(); parentName=bones.get(parentIndex).getName(); parentPos=absolutePos.get(parentIndex); if(pos.getX()!=0 || pos.getY()!=0 || pos.getZ()!=0){ endPos=pos.clone().multiplyScalar(.9).addSelf(parentPos); Vector3 half=pos.clone().multiplyScalar(.5).addSelf(parentPos); lists.add(new NameAndPosition(parentName,endPos,parentIndex));//start pos lists.add(new NameAndPosition(parentName,half,parentIndex));//half pos Mesh mesh=THREE.Mesh(THREE.CubeGeometry(.2, .2, .2), THREE.MeshLambertMaterial().color(0x00ff00).build()); mesh.setName(parentName); mesh.setPosition(endPos); //boneAndVertex.add(mesh); Mesh mesh2=THREE.Mesh(THREE.CubeGeometry(.3, .3, .2), THREE.MeshLambertMaterial().color(0x00ff00).build()); mesh2.setName(parentName); mesh2.setPosition(half); //boneAndVertex.add(mesh2); }else{ } } //add end if(parentPos!=null){ pos.addSelf(parentPos); } absolutePos.add(pos); Mesh mesh=THREE.Mesh(THREE.CubeGeometry(.5, .5, .5), THREE.MeshLambertMaterial().color(0x00ff00).build()); mesh.setName(bone.getName()); mesh.setPosition(pos); if(endSites!=null){ List<Vector3> ends=endSites.get(i); for(Vector3 endSite:ends){ lists.add(new NameAndPosition(bone.getName(),pos.clone().addSelf(endSite),i));// } } //boneAndVertex.add(mesh); if(parentPos!=null){ Mesh line=GWTGeometryUtils.createLineMesh(parentPos, pos, 0xff0000); //boneAndVertex.add(line); } lists.add(new NameAndPosition(bone.getName(),pos,i));//end pos } return lists; }*/ private Projector projector; Label debugLabel; List<Integer> selections=new ArrayList<Integer>(); private Object3D selectedObject; private Vector3 offset=THREE.Vector3(); @Override public void onMouseUp(MouseUpEvent event) { super.onMouseUp(event); selectedObject=null; } @Override public void onMouseDown(MouseDownEvent event) { super.onMouseDown(event); int x=event.getX(); int y=event.getY(); /* if(inEdge(x,y)){ screenMove(x,y); return; }*/ //LogUtils.log("screen:"+screenWidth+"x"+screenHeight); JsArray<Intersect> intersects=projector.gwtPickIntersects(event.getX(), event.getY(), screenWidth, screenHeight, camera,objects); //LogUtils.log("intersects:"+intersects.length()); for(int i=0;i<intersects.length();i++){ Intersect sect=intersects.get(i); Object3D target=sect.getObject(); //LogUtils.log(target); if(!target.getName().isEmpty()){//only point: and bone name if(target.getName().startsWith("point:")){ if(!target.getVisible()){ //not selected bone continue; } //changeBoneSelectionColor(null); String[] pv=target.getName().split(":"); int at=Integer.parseInt(pv[1]); if(event.isShiftKeyDown()){ if(selections.contains(at)){ selections.remove(new Integer(at)); //TODO cast material vertexMeshs.get(at).getMaterial().gwtGetColor().setHex(getVertexColor(at)); if(lastSelection==at){ if(selections.size()>0){ //select last selectVertex(selections.get(selections.size()-1)); }else{ indexWeightEditor.setAvailable(false); updateWeightButton.setEnabled(false); } } }else{ //plus if(lastSelection!=-1){ selections.add(lastSelection); } selectVertex(at); } for(int index:selections){ vertexMeshs.get(index).getMaterial().gwtGetColor().setHex(selectColor); } }else{ //clear cache clearBodyPointSelections(); selectVertex(at); } return; }else{//must be bone if(event.isShiftKeyDown()){ continue; } selectedObject=target; Ray ray=projector.gwtCreateRay(x, y, screenWidth, screenHeight, camera); mouseClickCatcher.getPosition().copy( GWTThreeUtils.toPositionVec(target.getMatrixWorld()) ); //mouseClickCatcher.getPosition().copy( target.getPosition() ); mouseClickCatcher.updateMatrixWorld(true);//very important //mouseClickCatcher.lookAt(camera.getPosition()); JsArray<Intersect> pintersects=ray.intersectObject(mouseClickCatcher); //LogUtils.log("plain:"+ThreeLog.get(pintersects.get(0).getPoint())); offset.copy(pintersects.get(0).getPoint()).sub(mouseClickCatcher.getPosition()); clearBodyPointSelections(); selectBone(target); break; } } } //selectionMesh.setVisible(false); //TODO clear selection } private void clearBodyPointSelections(){ for(int index:selections){ vertexMeshs.get(index).getMaterial().gwtGetColor().setHex(getVertexColor(index)); } selections.clear(); } private int getVertexColor(int index){ double index1=bodyIndices.get(index).getX();//first one boolean isIndex1=false; if(index1==selectionBoneIndex){ isIndex1=true; } double v=0; if(isIndex1){ v=bodyWeight.get(index).getX(); }else{ v=bodyWeight.get(index).getY(); } //if both index is same value is 1 if(bodyIndices.get(index).getX()==bodyIndices.get(index).getY()){ v=1; } if(v==1){ return 0xffffff; }else if(v==0){ return 0; } int[] cv=toColorByDouble(v); int color=ColorUtils.toColor(cv); return color; /* if(index==318){ LogUtils.log("isIndex1:"+isIndex1+",index="+index1+",selectBone="+selectionBoneIndex+",v="+v); } if(v==1){ return 0xfffefe; }else if(v>0.949){ return 0xff0000; }else if(v>0.849){ return 0xff977f; }else if(v>0.749){ return 0xffb87f; }else if(v>0.649){ return 0xffd67f; } else if(v>0.549){ return 0xfff17f; } else if(v>0.449){ return 0xffff00; }else if(v>0.349){ return 0xafff7f; }else if(v>0.249){ return 0x82ff7f; }else if(v>0.149){ return 0x7fffbb; }else if(v>0.05){ return 0x7fffee; }else if(v==0){ return 0; }else{ return 0x7fcaff; } */ } private Mesh boneSelectionMesh; private int selectionBoneIndex; private Object3D selectVertex; /** * change bone colors to detect which one selected. * when point selected ,all clear bone selection * @param boneName */ private void changeBoneSelectionColor(String boneName){ for(Mesh mesh:boneCoreMeshs){ if(boneName==null || !boneName.equals(mesh.getName())){ GWTThreeUtils.changeMeshMaterialColor(mesh, boneCoreColor); }else{ GWTThreeUtils.changeMeshMaterialColor(mesh, selectBoneCoreColor); } } for(Mesh mesh:boneJointMeshs){ if(boneName==null || !boneName.equals(mesh.getName())){ GWTThreeUtils.changeMeshMaterialColor(mesh, boneJointColor); }else{ GWTThreeUtils.changeMeshMaterialColor(mesh, selectBoneJointColor); } } } private void selectBone(Object3D target) { lastSelection=-1; //right now off boneSelectionMesh double boneSelectionSize=0.1*baseScale; if(boneSelectionMesh==null){ boneSelectionMesh=THREE.Mesh(THREE.CubeGeometry(boneSelectionSize, boneSelectionSize, boneSelectionSize), THREE.MeshLambertMaterial().color(0x00ff00).build()); boneAndVertex.add(boneSelectionMesh); }else{ } boneSelectionMesh.setVisible(false);//temporaly boneSelectionMesh.setPosition(target.getPosition()); changeBoneSelectionColor(target.getName()); selectionBoneIndex=findBoneIndex(target.getName()); boneListBox.setSelectedIndex(selectionBoneIndex); selectVertexsByBone(selectionBoneIndex); int selectionIndex=indexWeightEditor.getArrayIndex(); if(selectionIndex!=-1 && !vertexMeshs.get(selectionIndex).getVisible()){ indexWeightEditor.setAvailable(false); updateWeightButton.setEnabled(false); selectionPointIndicateMesh.setVisible(false); } } private void selectVertexsByBone(int selectedBoneIndex) { //LogUtils.log("selectVertexsByBone"); for(int i=0;i<bodyGeometry.vertices().length();i++){ Vector4 index=bodyIndices.get(i); Mesh mesh=vertexMeshs.get(i); if(index.getX()==selectedBoneIndex || index.getY()==selectedBoneIndex){ mesh.setVisible(true); mesh.getMaterial().gwtGetColor().setHex(getVertexColor(i)); //mesh.getMaterial().getColor().setHex(getVertexColor(i)); //LogUtils.log(weight.getX()+","+weight.getY()); }else{ mesh.setVisible(false); mesh.getMaterial().gwtGetColor().setHex(getVertexColor(i)); } } } private int findBoneIndex(String name){ int ret=0; for(int i=0;i<bones.length();i++){ if(bones.get(i).getName().equals(name)){ ret=i; break; } } return ret; } int rotX; int rotY; double posX; double posY=-10; @Override public void onMouseMove(MouseMoveEvent event) { /* if(selectedObject!=null && event.getNativeButton()==NativeEvent.BUTTON_MIDDLE){ Ray ray=projector.gwtCreateRay(event.getX(), event.getY(), screenWidth, screenHeight, camera); JsArray<Intersect> intersects = ray.intersectObject( mouseClickCatcher ); Vector3 newPos=intersects.get(0).getPoint().subSelf( offset ); Matrix4 rotM=THREE.Matrix4(); rotM.getInverse(selectedObject.getMatrixRotationWorld()); rotM.multiplyVector3(newPos); selectedObject.getPosition().copy( newPos); return; }*/ if(mouseDown){ int diffX=event.getX()-mouseDownX; int diffY=event.getY()-mouseDownY; mouseDownX=event.getX(); mouseDownY=event.getY(); if(event.getNativeButton()==NativeEvent.BUTTON_MIDDLE){ int newX=rotationXRange.getValue()+diffY; if(newX<-180){ newX=360+newX; } if(newX>180){ newX=360-newX; } rotationXRange.setValue(newX); int newY=rotationYRange.getValue()+diffX; if(newY<-180){ newY=360+newY; } if(newY>180){ newY=360-newY; } rotationYRange.setValue(newY); return; } if(event.isControlKeyDown()){//TODO future function /* int index=indexWeightEditor.getArrayIndex(); if(index!=-1){ loadedGeometry.vertices().get(index).getPosition().incrementX(diffX); loadedGeometry.vertices().get(index).getPosition().incrementX(diffY); createSkinnedMesh(); createWireBody(); }*/ }else if(event.isAltKeyDown()){ posX+=(double)diffX/16*posScale; posY-=(double)diffY/16*posScale; }else{ rotX=(rotX+diffY); rotY=(rotY+diffX); } } } private InputRangeWidget positionXRange; private InputRangeWidget positionYRange; private InputRangeWidget positionZRange; private InputRangeWidget rotationXRange; private InputRangeWidget rotationYRange; private InputRangeWidget rotationZRange; private CheckBox useBone; private Button updateIndexOnlyButton; private Button updateWeightOnlyButton; @Override public void createControl(DropVerticalPanelBase parent) { nearCamera=0.01; debugLabel=new Label(); parent.add(debugLabel); stackPanel = new StackLayoutPanel(Unit.PX); stackPanel.setSize("220px","440px"); parent.add(stackPanel); VerticalPanel modelPositionAndRotation=new VerticalPanel(); modelPositionAndRotation.setWidth("100%"); stackPanel.add(modelPositionAndRotation,"Model Postion&Rotation",30); controlBone = new CheckBox("controlBone"); HorizontalPanel h1=new HorizontalPanel(); rotationXRange = InputRangeWidget.createInputRange(-180,180,0); modelPositionAndRotation.add(HTML5Builder.createRangeLabel("X-Rotate:", rotationXRange)); modelPositionAndRotation.add(h1); h1.add(rotationXRange); Button reset=new Button("Reset"); reset.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rotationXRange.setValue(0); } }); h1.add(reset); HorizontalPanel h2=new HorizontalPanel(); rotationYRange = InputRangeWidget.createInputRange(-180,180,0); modelPositionAndRotation.add(HTML5Builder.createRangeLabel("Y-Rotate:", rotationYRange)); modelPositionAndRotation.add(h2); h2.add(rotationYRange); Button reset2=new Button("Reset"); reset2.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rotationYRange.setValue(0); } }); h2.add(reset2); HorizontalPanel h3=new HorizontalPanel(); rotationZRange = InputRangeWidget.createInputRange(-180,180,0); modelPositionAndRotation.add(HTML5Builder.createRangeLabel("Z-Rotate:", rotationZRange)); modelPositionAndRotation.add(h3); h3.add(rotationZRange); Button reset3=new Button("Reset"); reset3.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { rotationZRange.setValue(0); } }); h3.add(reset3); HorizontalPanel h4=new HorizontalPanel(); positionXRange = InputRangeWidget.createInputRange(-50,50,0); modelPositionAndRotation.add(HTML5Builder.createRangeLabel("X-Position:", positionXRange)); modelPositionAndRotation.add(h4); h4.add(positionXRange); Button reset4=new Button("Reset"); reset4.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { positionXRange.setValue(0); } }); h4.add(reset4); HorizontalPanel h5=new HorizontalPanel(); positionYRange = InputRangeWidget.createInputRange(-50,50,0); modelPositionAndRotation.add(HTML5Builder.createRangeLabel("Y-Position:", positionYRange)); modelPositionAndRotation.add(h5); h5.add(positionYRange); Button reset5=new Button("Reset"); reset5.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { positionYRange.setValue(0); } }); h5.add(reset5); HorizontalPanel h6=new HorizontalPanel(); positionZRange = InputRangeWidget.createInputRange(-50,50,0); modelPositionAndRotation.add(HTML5Builder.createRangeLabel("Z-Position:", positionZRange)); modelPositionAndRotation.add(h6); h6.add(positionZRange); Button reset6=new Button("Reset"); reset6.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { positionZRange.setValue(0); } }); h6.add(reset6); //move left-side //positionYRange.setValue(-13); positionXRange.setValue(-10); pauseBt = new Button("Pause/Play SkinnedMesh"); parent.add(pauseBt); pauseBt.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { paused=!paused; } }); frameRange = InputRangeWidget.createInputRange(0, 0, 0); frameRange.addInputRangeListener(new InputRangeListener() { @Override public void changed(int newValue) { updateFrameRange(); } }); parent.add(frameRange); /* CheckBox do1small=new CheckBox("x 0.1"); do1small.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { onTotalSizeChanged(event.getValue()); } }); parent.add(do1small); */ //editor VerticalPanel boneAndWeight=new VerticalPanel(); boneAndWeight.setWidth("100%"); stackPanel.add(boneAndWeight,"Bone & Weight",30); boneAndWeight.add(new Label("Bone Selection")); boneListBox = new ListBox(); boneAndWeight.add(boneListBox); boneListBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { selectVertexsByBone(boneListBox.getSelectedIndex()); } }); HorizontalPanel prevAndNext=new HorizontalPanel(); boneAndWeight.add(prevAndNext); Button prev=new Button("Prev"); prev.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { selectPrevVertex(); } }); prevAndNext.add(prev); Button next=new Button("Next"); next.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { selectNextVertex(); } }); prevAndNext.add(next); indexWeightEditor = new IndexAndWeightEditor(); indexWeightEditor.setWidth("200px"); boneAndWeight.add(indexWeightEditor); updateWeightButton = new Button("Update Both"); updateWeightButton.setWidth("100%"); updateWeightButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { int index=indexWeightEditor.getArrayIndex(); if(index==-1){ return; } Vector4 in=bodyIndices.get(index); Vector4 we=bodyWeight.get(index); in.setX(indexWeightEditor.getIndex1()); in.setY(indexWeightEditor.getIndex2()); we.setX(indexWeightEditor.getWeight1()); we.setY(indexWeightEditor.getWeight2()); if(selections.size()>0){ for(int selectedIndex:selections){ in=bodyIndices.get(selectedIndex); we=bodyWeight.get(selectedIndex); in.setX(indexWeightEditor.getIndex1()); in.setY(indexWeightEditor.getIndex2()); we.setX(indexWeightEditor.getWeight1()); we.setY(indexWeightEditor.getWeight2()); } } //LogUtils.log("new-ind-weight:"+in.getX()+","+in.getY()+","+we.getX()+","+we.getY()); createSkinnedMesh(); selectVertexsByBone(selectionBoneIndex); } }); boneAndWeight.add(updateWeightButton); HorizontalPanel update2=new HorizontalPanel(); update2.setWidth("100%"); boneAndWeight.add(update2); updateIndexOnlyButton = new Button("Update Index"); //updateIndexOnlyButton.setWidth("50%"); updateIndexOnlyButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { int index=indexWeightEditor.getArrayIndex(); if(index==-1){ return; } Vector4 in=bodyIndices.get(index); in.setX(indexWeightEditor.getIndex1()); in.setY(indexWeightEditor.getIndex2()); if(selections.size()>0){ for(int selectedIndex:selections){ in=bodyIndices.get(selectedIndex); in.setX(indexWeightEditor.getIndex1()); in.setY(indexWeightEditor.getIndex2()); } } //LogUtils.log("new-ind-weight:"+in.getX()+","+in.getY()+","+we.getX()+","+we.getY()); createSkinnedMesh(); selectVertexsByBone(selectionBoneIndex); } }); update2.add(updateIndexOnlyButton); updateWeightOnlyButton = new Button("Update Weight"); //updateWeightOnlyButton.setWidth("50%"); updateWeightOnlyButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { int index=indexWeightEditor.getArrayIndex(); if(index==-1){ return; } Vector4 we=bodyWeight.get(index); we.setX(indexWeightEditor.getWeight1()); we.setY(indexWeightEditor.getWeight2()); if(selections.size()>0){ for(int selectedIndex:selections){ we=bodyWeight.get(selectedIndex); we.setX(indexWeightEditor.getWeight1()); we.setY(indexWeightEditor.getWeight2()); } } createSkinnedMesh(); selectVertexsByBone(selectionBoneIndex); } }); update2.add(updateWeightOnlyButton); boneAndWeight.add(new Label("Re Auto-Weight")); autoWeightListBox = new ListBox(); autoWeightListBox.addItem("From Geometry", "4"); autoWeightListBox.addItem("Half ParentAndChildrenAg", "6"); autoWeightListBox.addItem("ParentAndChildren Agressive", "5"); autoWeightListBox.addItem("ParentAndChildren", "3"); autoWeightListBox.addItem("NearAgressive", "2"); autoWeightListBox.addItem("NearSingleBon", "0"); autoWeightListBox.addItem("NearSpecial", "1"); autoWeightListBox.addItem("Root All", "7"); autoWeightListBox.addItem("Makehuman SecondLife-19", ""+MakehumanWeightBuilder.MODE_MAKEHUMAN_SECOND_LIFE19); autoWeightListBox.setSelectedIndex(1); boneAndWeight.add(autoWeightListBox); autoWeightListBox.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { //if(callAutoWeight){//when model loaded do autoweight and sync the way do it without re-update LogUtils.log("autoweight-changed"); updateAutoWeight(autoWeightListBox.getValue(autoWeightListBox.getSelectedIndex())); createSkinnedMesh(); } }); //DONT need? useBasicMaterial = new CheckBox(); useBasicMaterial.setText("Use Basic Material"); //parent.add(useBasicMaterial); VerticalPanel loadAndExport=new VerticalPanel(); stackPanel.add(loadAndExport,"Load Datas",30); /* bvhUpload.getFileUpload().addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { JsArray<File> files = FileUtils.toFile(event.getNativeEvent()); final FileReader reader=FileReader.createFileReader(); final File file=files.get(0); reader.setOnLoad(new FileHandler() { @Override public void onLoad() { //LogUtils.log("load:"+Benchmark.end("load")); //GWT.log(reader.getResultAsString()); parseBVH(reader.getResultAsString()); bvhSelection.setText("selection:"+file.getFileName()); } }); reader.readAsText(file,"utf-8"); bvhUpload.reset(); } }); */ Label jsonTitleLabel=new Label("Character(Three.js model file)"); //label1.setStylePrimaryName("darkgray"); loadAndExport.add(jsonTitleLabel); modelSelection = new Label("selection:"+modelUrl); modelSelection.setStylePrimaryName("gray"); loadAndExport.add(modelSelection); final FileUploadForm meshUpload=FileUtils.createSingleTextFileUploadForm(new DataURLListener() { @Override public void uploaded(final File file, String value) { onModelFileUploaded(file, value); } }, true); meshUpload.setShowDragOverBorder(true); //meshUpload.getFileUpload().setStylePrimaryName("darkgray"); loadAndExport.add(meshUpload); //makehuman export bvh somehow large,and try to fix it ,but this make problem //force10x = new CheckBox("force multiple x10"); //loadAndExport.add(force10x); useBone = new CheckBox("use bone inside model when load"); useBone.setValue(true); loadAndExport.add(useBone); Label bvhTitleLabel=new Label("Another Bone(BVH Motion file)"); loadAndExport.add(bvhTitleLabel); bvhTitleLabel.setStylePrimaryName("darkgray"); bvhSelection = new Label("selection:"+bvhUrl); bvhSelection.setStylePrimaryName("gray"); loadAndExport.add(bvhSelection); final FileUploadForm bvhUpload=FileUtils.createSingleTextFileUploadForm(new DataURLListener() { @Override public void uploaded(File file, String value) { onBVHFileUploaded(file, value); } }, true); bvhUpload.setShowDragOverBorder(true); loadAndExport.add(bvhUpload); loadAndExport.add(new Label("Texture(PNG or JPEG)")); textureSelection = new Label("selection:"+textureUrl); textureSelection.setStylePrimaryName("gray"); final FileUploadForm textureUpload=FileUtils.createSingleFileUploadForm(new DataURLListener() { @Override public void uploaded(File file, String value) { LogUtils.log("texture upload"); onTextureFileUploaded(file, value); } }, true); textureUpload.setShowDragOverBorder(true); loadAndExport.add(textureSelection); loadAndExport.add(textureUpload); Label label2=new Label("Weights and Idecis(json)"); label2.setStylePrimaryName("darkgray"); loadAndExport.add(label2); weightSelection = new Label("selection:"); weightSelection.setStylePrimaryName("gray"); final FileUploadForm weightUpload=FileUtils.createSingleTextFileUploadForm(new DataURLListener() { @Override public void uploaded(final File file, String value) { onWeightFileUploaded(file, value); } }, true); weightUpload.setShowDragOverBorder(true); weightUpload.setTitle("upload json model but only load weight&indecis"); weightUpload.getFileUpload().setStylePrimaryName("darkgray"); loadAndExport.add(weightSelection); loadAndExport.add(weightUpload); VerticalPanel export=new VerticalPanel(); stackPanel.add(export,"Export Datas",30); export.add(new Label("you can load form pose editor preference")); Button webstorage=new Button("Export in WebStorage"); webstorage.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { exportWebStorage(); } }); export.add(webstorage); export.add(new Label("three.js model format")); HorizontalPanel fileNames=new HorizontalPanel(); export.add(fileNames); fileNames.add(new Label("Name:")); saveFileBox = new TextBox(); saveFileBox.setText("untitled.js"); fileNames.add(saveFileBox); HorizontalPanel exports=new HorizontalPanel(); loadAndExport.add(exports); Button json=new Button("Export as Json"); json.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { exportAsJson(); } }); exports.add(json); withAnimation = new CheckBox("+Animation"); withAnimation.setValue(false); //dont work collectly <--what mean is this? exports.add(withAnimation); export.add(exports); exportLinks = new VerticalPanel(); export.add(exportLinks); stackPanel.showWidget(2);//load //other controls CheckBox showBoneCheck=new CheckBox("showWireBody"); showBoneCheck.setValue(true); parent.add(showBoneCheck); showBoneCheck.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { if(wireBody!=null){ wireBody.setVisible(event.getValue()); } } }); /* Button makeDot=new Button("makedot",new ClickHandler() { @Override public void onClick(ClickEvent event) { // TODO Auto-generated method stub } }); parent.add(makeDot); */ createTabs(); //loadAndExport.add(new Label("Dont export large BVH.large(10M?) text data crash browser")); showControl(); } protected void onTotalSizeChanged(Boolean value) { List<Mesh> meshs=Lists.newArrayList(); meshs.addAll(vertexMeshs); meshs.addAll(boneJointMeshs); meshs.addAll(boneCoreMeshs); meshs.addAll(endPointMeshs); if(selectionPointIndicateMesh!=null){ meshs.add(selectionPointIndicateMesh); } if(boneSelectionMesh!=null){ meshs.add(boneSelectionMesh); } //redo-bone and vertex /* for(Mesh mesh:meshs){ double scale=(1.0/upscale); mesh.getScale().set(scale,scale,scale); } */ } private boolean needFlipY=true;//default private void onModelLoaded(String fileName,Geometry geometry){ LogUtils.log("onModelLoaded"); LogUtils.log(geometry); if(lastJsonObject!=null){ JSONModelFile modelFile=(JSONModelFile) lastJsonObject.getJavaScriptObject(); //old version 3.0 need flip-Y //see https://github.com/mrdoob/three.js/wiki/Migration#r49--r50 if(modelFile.getMetaData().getFormatVersion()==3){ needFlipY=false; }else{ needFlipY=true; } } //set geo bone info if exists. List<AnimationBone> abList=new ArrayList<AnimationBone>(); JsArray<AnimationBone> geoBones=geometry.getBones(); if(geoBones!=null){ for(int i=0;i<geoBones.length();i++){ abList.add(geoBones.get(i)); } } infoPanel.getGeometryAnimationObjects().setDatas(abList); infoPanel.getGeometryAnimationObjects().update(false); LogUtils.log("geometry-bone-info updated"); if(useBone.getValue()){ LogUtils.log(geoBones); /* BVHConverter converter=new BVHConverter(); LogUtils.log("geo-bone:"+geoBones); LogUtils.log("getBones:"+geoBones.get(0).getPos()); BVHNode rootNode=converter.convertBVHNode(geoBones); LogUtils.log("rootNode:"+rootNode.getOffset()); converter.setChannels(rootNode,0,"XYZ"); //TODO support other order BVH inBvh=new BVH(); inBvh.setHiearchy(rootNode); LogUtils.log("1"); BVHMotion motion=new BVHMotion(); motion.setFrameTime(.25); */ //zero /* for(PoseFrameData pose:Lists.newArrayList(new PoseFrameData())){ double[] values=converter.angleAndMatrixsToMotion(pose.getAngleAndMatrixs(),BVHConverter.ROOT_POSITION_ROTATE_ONLY,"XYZ"); motion.add(values); } */ /* motion.add(new double[geoBones.length()*3+3]);//only root has pos,TODO find better way motion.setFrames(motion.getMotions().size());// LogUtils.log("2"); inBvh.setMotion(motion); BVHWriter writer=new BVHWriter(); String bvhText=writer.writeToString(inBvh); */ //because this time not channel setted,TODO setBvh(new BVHConverter().createBVH(geoBones)); /* try { setBvh(new BVHParser().parse(bvhText)); } catch (InvalidLineException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } initializeObject(); loadedGeometry=geometry; //each time model loaded,check model format and set flipY if(texture!=null){ if(!needFlipY){ LogUtils.log("texture flipY:false for old 3.0 format"); } texture.setFlipY(needFlipY); texture.setNeedsUpdate(true); } autoWeight(); createWireBody(); modelSelection.setText("selection:"+fileName); if(fileName.endsWith(".js")){ fileName=FileNames.getRemovedExtensionName(fileName)+".json";//replace .js to .json i prefer } saveFileBox.setText(fileName); updateSelectableObjects(); } /** * on load model for weight&indecis * @param fileName * @param geometry * @param materials */ private void onWeightLoaded(String fileName,Geometry geometry,JsArray<Material> materials){ setWeigthFromGeometry(geometry); weightSelection.setText("selection:"+fileName); } //called when bone changed or mesh changed @SuppressWarnings("unchecked") private void updateSelectableObjects(){ objects=THREE.createJsArray(); //body each point for(Mesh point:wireBodyPoints){ objects.push(point); } //bone for(Mesh mesh:boneJointMeshs){ objects.push(mesh); } for(Mesh mesh:boneCoreMeshs){ objects.push(mesh); } } private void setWeigthFromGeometry(Geometry geometry) { //loadedGeometry //LogUtils.log(geometry); //LogUtils.log(geometry.getSkinIndices()); //LogUtils.log(""+geometry.getSkinIndices().length()); if(geometry.getSkinIndices().length()==0){ LogUtils.log("loaded geometry has no indices:do nothing"); return; } int updated=0; for(int i=0;i<geometry.vertices().length();i++){ int loadedIndex=findSameIndex(loadedGeometry.vertices(), geometry.vertices().get(i)); // LogUtils.log(i+" find:"+loadedIndex); if(loadedIndex!=-1){ bodyIndices.get(loadedIndex).setX(geometry.getSkinIndices().get(i).getX()); bodyIndices.get(loadedIndex).setY(geometry.getSkinIndices().get(i).getY()); bodyWeight.get(loadedIndex).setX(geometry.getSkinWeight().get(i).getX()); bodyWeight.get(loadedIndex).setY(geometry.getSkinWeight().get(i).getY()); updated++; } } LogUtils.log("updated weight:"+updated); updateVertexColor(); } private int findSameIndex(JsArray<Vector3> vertexList,Vector3 checkVertex){ int result=-1; for(int i=0;i<vertexList.length();i++){ boolean same=true; if(vertexList.get(i).getX()!=checkVertex.getX()){ same=false; }else if(vertexList.get(i).getY()!=checkVertex.getY()){ same=false; }else if(vertexList.get(i).getZ()!=checkVertex.getZ()){ same=false; } if(same){ result=i; break; } } return result; } @SuppressWarnings("unchecked") protected void updateAutoWeight(String value) { int selectedValue=Integer.parseInt(value); if(selectedValue!=-1){ //clear Indices & Weight bodyIndices = (JsArray<Vector4>) JsArray.createArray(); bodyWeight = (JsArray<Vector4>) JsArray.createArray(); if(loadedGeometry.getSkinIndices().length()!=0 && loadedGeometry.getSkinWeight().length()!=0){ if(selectedValue<100){ WeightBuilder.autoWeight(loadedGeometry, bones, endSites,selectedValue, bodyIndices, bodyWeight); }else{ MakehumanWeightBuilder.autoWeight(loadedGeometry, bones, endSites,selectedValue, bodyIndices, bodyWeight); } }else{ //cant select geometry if(selectedValue==WeightBuilder.MODE_FROM_GEOMETRY){ Window.alert("This geometry has no weight.choose another way"); }else{ WeightBuilder.autoWeight(loadedGeometry, bones, endSites,selectedValue, bodyIndices, bodyWeight); } } updateVertexColor(); } } private void updateVertexColor(){ for(int i=0;i<bodyGeometry.vertices().length();i++){ Mesh mesh=vertexMeshs.get(i); mesh.getMaterial().gwtGetColor().setHex(getVertexColor(i)); } } protected void updateFrameRange() { paused=true; double time=frameRange.getValue()*bvh.getFrameTime(); //LogUtils.log("bvh-length="+bvh.getFrames()+",ftime="+bvh.getFrameTime()); //LogUtils.log("set-current:"+time+",rangeValue="+frameRange.getValue()+",bvhTime="+bvh.getFrameTime()); //LogUtils.log("animation,length="+animation.getData().getLength()+",fps="+animation.getData().getFps()); double totaltime=animation.getData().getLength(); double animationCurrentTime=animation.getCurrentTime(); //animation.setCurrentTime(time); double delta=0; if(time>animationCurrentTime){ delta=animationCurrentTime=time; }else{ double last=totaltime-animationCurrentTime; delta=last+time; } AnimationHandler.update(delta); //animation.stop(); //animation.play(true, currentTime); //currentTime=0;//to reset? //paused=false; //AnimationHandler.update(0); //animation.stop(); //animation.pause(); //AnimationHandler.update(0); } protected void exportWebStorage() { StorageDataList modelControler=new StorageDataList(storageControler, "MODEL"); String title=Window.prompt("FileName", "Skinning-Exported"); String text=toJsonText(); modelControler.setDataValue(title, text); int id=modelControler.incrementId(); } protected void selectPrevVertex() { int currentSelection=indexWeightEditor.getArrayIndex(); for(int i=currentSelection-1;i>=0;i if(vertexMeshs.get(i).getVisible()){ selectVertex(i); return; } } for(int i=vertexMeshs.size()-1;i>currentSelection;i if(vertexMeshs.get(i).getVisible()){ selectVertex(i); return; } } } protected void selectNextVertex() { int currentSelection=indexWeightEditor.getArrayIndex(); for(int i=currentSelection+1;i<vertexMeshs.size();i++){ if(vertexMeshs.get(i).getVisible()){ selectVertex(i); return; } } for(int i=0;i<currentSelection;i++){ if(vertexMeshs.get(i).getVisible()){ selectVertex(i); return; } } } private int lastSelection=-1; private void selectVertex(int index){ if(lastSelection!=-1){ vertexMeshs.get(lastSelection).getMaterial().gwtGetColor().setHex(getVertexColor(lastSelection)); } Vector4 in=bodyIndices.get(index); Vector4 we=bodyWeight.get(index); LogUtils.log("select:"+index+","+we.getX()+","+we.getY()); //change selected point to selection color,multiple selection is avaiable and to detect change point color. vertexMeshs.get(index).getMaterial().gwtGetColor().setHex(selectColor); indexWeightEditor.setAvailable(true); updateWeightButton.setEnabled(true); indexWeightEditor.setValue(index, in, we); //show which point selection,with wireframe weight-color selectionPointIndicateMesh.setVisible(true); selectionPointIndicateMesh.setPosition(vertexMeshs.get(index).getPosition()); selectionPointIndicateMesh.getMaterial().gwtGetColor().setHex(getVertexColor(index)); stackPanel.showWidget(1); //bone & weight panel lastSelection=index; } public static String get(Vector4 vec){ if(vec==null){ return "Null"; } String ret="x:"+vec.getX(); ret+=",y:"+vec.getY(); ret+=",z:"+vec.getZ(); ret+=",w:"+vec.getW(); return ret; } /* * add bones and skinIndices & skinWeights to last selected model * animation is option. * so model format version keep(not touch uv) */ public String toJsonText(){ JsArray<AnimationBone> clonedBone=cloneBones(bones); JSONArray arrays=new JSONArray(clonedBone); lastJsonObject.put("bones", arrays); //AnimationBoneConverter.setBoneAngles(clonedBone, rawAnimationData, 0); //TODO if(withAnimation.getValue()){ lastJsonObject.put("animation", new JSONObject(rawAnimationData)); } //private JsArray<Vector4> bodyIndices; //private JsArray<Vector4> bodyWeight; /* List<String> lines=new ArrayList<String>(); for(int i=0;i<bodyWeight.length();i++){ lines.add(i+get(bodyWeight.get(i))); } LogUtils.log("after"); LogUtils.log(Joiner.on("\n").join(lines));f */ //LogUtils.log(bodyIndices); //LogUtils.log(bodyWeight); JsArrayNumber indices=(JsArrayNumber) JsArrayNumber.createArray(); for(int i=0;i<bodyIndices.length();i++){ indices.push(bodyIndices.get(i).getX()); indices.push(bodyIndices.get(i).getY()); } lastJsonObject.put("skinIndices", new JSONArray(indices)); JsArrayNumber weights=(JsArrayNumber) JsArrayNumber.createArray(); for(int i=0;i<bodyWeight.length();i++){ weights.push(bodyWeight.get(i).getX()); weights.push(bodyWeight.get(i).getY()); } lastJsonObject.put("skinWeights", new JSONArray(weights)); //rewrite gen JSONModelFile file=(JSONModelFile) lastJsonObject.getJavaScriptObject(); file.getMetaData().setGeneratedBy(getGeneratedBy()); return stringify(lastJsonObject.getJavaScriptObject()); //return lastJsonObject.toString(); } public static String getGeneratedBy(){ return "GWTModel-Weight ver"+GWTModelWeight.version; } private void exportAsJson(){ //set bone String json=toJsonText(); String name=saveFileBox.getText(); if(name.isEmpty()){ name="untitled.js"; } if(anchor!=null){ anchor.removeFromParent(); anchor=null; } anchor = new HTML5Download().generateTextDownloadLink(json, name, "Download File"); exportLinks.add(anchor); anchor.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { anchor.removeFromParent(); } }); //exportTextAsDownloadDataUrl(toJsonText(),"UTF-8","WeightTool"+exportIndex); //exportTextChrome(toJsonText(),"WeightTool"+exportIndex); //exportIndex++; } int exportIndex; public static final void exportTextAsDataUrl(String text,String encode,String wname){ String url="data:text/plain;charset="+encode+","+text; Window.open(url, wname, null); } //export json pretty way public native final String stringify(JavaScriptObject json)/*-{ return $wnd.JSON.stringify(json,null,2); }-*/; public native final void exportTextChrome(String text,String wname)/*-{ win = $wnd.open("", wname) win.document.body.innerText =""+text+""; }-*/; private boolean paused=true; private void loadBVH(String path){ RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(path)); try { builder.sendRequest(null, new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { String bvhText=response.getText(); //LogUtils.log("loaded:"+Benchmark.end("load")); //useless spend allmost time with request and spliting. parseBVH(bvhText); } @Override public void onError(Request request, Throwable exception) { Window.alert("load faild:"); } }); } catch (RequestException e) { LogUtils.log(e.getMessage()); e.printStackTrace(); } } private JsArray<Vector4> bodyIndices; private JsArray<Vector4> bodyWeight; private BVH bvh; private Animation animation; private Geometry bodyGeometry; private Object3D boneAndVertex; private JsArray<AnimationBone> bones; private List<List<Vector3>> endSites; private SkinnedMesh skinnedMesh; private ColladaData rawCollada; private AnimationData rawAnimationData; private void updateBoneListBox(){ boneListBox.clear(); for(int i=0;i<bones.length();i++){ boneListBox.addItem(bones.get(i).getName()); } } public JsArray<AnimationBone> cloneBones(JsArray<AnimationBone> bones){ JsArray<AnimationBone> array=(JsArray<AnimationBone>) JsArray.createArray(); for(int i=0;i<bones.length();i++){ AnimationBone bone=bones.get(i); AnimationBone cloned=(AnimationBone) AnimationBone.createObject(); cloned.setName(bone.getName()); cloned.setParent(bone.getParent()); if(bone.getPos()!=null){ cloned.setPos(GWTThreeUtils.clone(bone.getPos())); } if(bone.getRotq()!=null){ cloned.setRotq(GWTThreeUtils.clone(bone.getRotq())); } if(bone.getRot()!=null){ cloned.setRot(GWTThreeUtils.clone(bone.getRot())); } if(bone.getScl()!=null){ cloned.setScl(GWTThreeUtils.clone(bone.getScl())); } array.push(cloned); } return array; } private int [] toColorByDouble(double v){ return toColor((int) (255*v)); } //i get this somewhere internet //0-255 private int[] toColor(int v){ int[] rgb=new int[3]; double phase = (double)v/255; double shift =Math.PI+Math.PI/4; rgb[2]=(int) (255*(Math.sin(1.5*Math.PI*phase + shift + Math.PI ) + 1)/2.0) ; rgb[1]=(int) (255*(Math.sin(1.5*Math.PI*phase + shift + Math.PI/2 ) + 1)/2.0) ; rgb[0]=(int) (255*(Math.sin(1.5*Math.PI*phase + shift ) + 1)/2.0) ; return rgb; } private void setBvh(BVH bv){ LogUtils.log("setBvh:root-pos:"+bv.getHiearchy().getOffset()); bvh=bv; /* not work bvhVec=bvh.getHiearchy().getOffset(); bvh.getHiearchy().setOffset(new Vec3(0,0,0));//i believe no need. */ List<BVHNode> bvhNodes=new ArrayList<BVHNode>(); addNode(bvh.getHiearchy(),bvhNodes); infoPanel.getBvhObjects().setDatas(bvhNodes); infoPanel.getBvhObjects().update(true); for(int i=0;i<bvhNodes.size();i++){ LogUtils.log(i+","+bvhNodes.get(i).getName()+","+bvhNodes.get(i).getOffset().toString()+","+bvhNodes.get(i).getOffset().getX()); } //bvh.setSkips(10); //bvh.setSkips(skipFrames); AnimationBoneConverter converter=new AnimationBoneConverter(); bones = converter.convertJsonBone(bvh); List<AnimationBone> abList=new ArrayList<AnimationBone>(); for(int i=0;i<bones.length();i++){ abList.add(bones.get(i)); } infoPanel.getBvhAnimationObjects().setDatas(abList); infoPanel.getBvhAnimationObjects().update(true); LogUtils.log(bones); endSites=converter.convertJsonBoneEndSites(bvh); updateBoneListBox(); indexWeightEditor.setBones(bones); /* for(int i=0;i<bones.length();i++){ // LogUtils.log(i+":"+bones.get(i).getName()); } GWT.LogUtils.log("parsed"); */ /* for(int i=0;i<bones.length();i++){ Mesh mesh=THREE.Mesh(THREE.CubeGeometry(.5, .5, .5), THREE.MeshLambertMaterial().color(0x0000ff).build()); scene.add(mesh); JsArrayNumber pos=bones.get(i).getPos(); mesh.setPosition(pos.get(0),pos.get(1),pos.get(2)); } */ AnimationDataConverter dataConverter=new AnimationDataConverter(); if(bvh.getFrames()==1){ dataConverter.setSkipFirst(false); frameRange.setMax(bvh.getFrames()); }else{ dataConverter.setSkipFirst(false);//need skip first option //frameRange.setMax(bvh.getFrames()-1); frameRange.setMax(bvh.getFrames()); } animationData = dataConverter.convertJsonAnimation(bones,bvh); //for(int i=0;i<animationData.getHierarchy().length();i++){ AnimationHierarchyItem item=animationData.getHierarchy().get(0); for(int j=0;j<item.getKeys().length();j++){ item.getKeys().get(j).setPos(0, 0, 0);//dont move; } rawAnimationData=dataConverter.convertJsonAnimation(bones,bvh);//for json if(bvh.getFrames()==1){ animationName=null;//i guess 1 frame bvh usually maked geometry bone which has no animation erase mesh. pauseBt.setEnabled(false); frameRange.setEnabled(false); }else{ pauseBt.setEnabled(true); frameRange.setEnabled(true); animationName=animationData.getName(); } //JsArray<AnimationHierarchyItem> hitem=animationData.getHierarchy(); /* for(int i=0;i<hitem.length();i++){ AnimationHierarchyItem item=hitem.get(i); AnimationHierarchyItem parent=null; if(item.getParent()!=-1){ parent=hitem.get(item.getParent()); } AnimationKey key=item.getKeys().get(keyIndex); Mesh mesh=THREE.Mesh(THREE.CubeGeometry(.5, .5, .5), THREE.MeshLambertMaterial().color(0x00ff00).build()); scene.add(mesh); Vector3 meshPos=AnimationUtils.getPosition(key); mesh.setPosition(meshPos); if(parent!=null){ Vector3 parentPos=AnimationUtils.getPosition(parent.getKeys().get(keyIndex)); Geometry lineG = THREE.Geometry(); lineG.vertices().push(THREE.Vertex(meshPos)); lineG.vertices().push(THREE.Vertex(parentPos)); Mesh line=THREE.Line(lineG, THREE.LineBasicMaterial().color(0xffffff).build()); scene.add(line); } Quaternion q=key.getRot(); Matrix4 rot=THREE.Matrix4(); rot.setRotationFromQuaternion(q); Vector3 rotV=THREE.Vector3(); rotV.setRotationFromMatrix(rot); mesh.setRotation(rotV); } */ /* Geometry cube=THREE.CubeGeometry(1, 1, 1); JsArray<Vector4> indices=(JsArray<Vector4>) JsArray.createArray(); JsArray<Vector4> weight=(JsArray<Vector4>) JsArray.createArray(); for(int i=0;i<cube.vertices().length();i++){ Vector4 v4=THREE.Vector4(); v4.set(0, 0, 0, 0); indices.push(v4); Vector4 v4w=THREE.Vector4(); v4w.set(1, 0, 0, 0); weight.push(v4w); } List<Vector3> parentPos=new ArrayList<Vector3>(); parentPos.add(THREE.Vector3()); for(int j=1;j<bones.length();j++){ Geometry cbone=THREE.CubeGeometry(1, 1, 1); AnimationBone ab=bones.get(j); Vector3 pos=AnimationBone.jsArrayToVector3(ab.getPos()); pos.addSelf(parentPos.get(ab.getParent())); parentPos.add(pos); Matrix4 m4=THREE.Matrix4(); m4.setPosition(pos); cbone.applyMatrix(m4); GeometryUtils.merge(cube, cbone); for(int i=0;i<cbone.vertices().length();i++){ Vector4 v4=THREE.Vector4(); v4.set(j, j, 0, 0); // v4.set(0, 0, 0, 0); indices.push(v4); Vector4 v4w=THREE.Vector4(); v4w.set(1, 0, 0, 0); weight.push(v4w); } } LogUtils.log("cube"); LogUtils.log(cube); cube.setSkinIndices(indices); cube.setSkinWeight(weight); cube.setBones(bones); */ final List<Vector3> bonePositions=new ArrayList<Vector3>(); for(int j=0;j<bones.length();j++){ AnimationBone bone=bones.get(j); Vector3 pos=AnimationBone.jsArrayToVector3(bone.getPos()); if(bone.getParent()!=-1){ pos.addSelf(bonePositions.get(bone.getParent())); } bonePositions.add(pos); } //overwrite same name AnimationHandler.add(animationData); //LogUtils.log(data); //LogUtils.log(bones); JSONArray array=new JSONArray(bones); //LogUtils.log(array.toString()); JSONObject test=new JSONObject(animationData); //LogUtils.log(test.toString()); if(texture==null){ //initial texture load,no need to care flipY,it's care when model loaded. texture=ImageUtils.loadTexture(textureUrl); } initializeObject(); if(loadedGeometry==null){//initial load loadModel(modelUrl, new JSONLoadHandler() { //loader.load("men3smart.js", new LoadHandler() { @Override public void loaded(Geometry geometry,JsArray<Material> materials) { onModelLoaded(modelUrl,geometry); createSkinnedMesh(); } }); }else{ //is this order is important? autoWeight(); createSkinnedMesh(); createWireBody(); updateSelectableObjects(); } //LogUtils.log("before create"); //Mesh mesh=THREE.Mesh(cube, THREE.MeshLambertMaterial().skinning(false).color(0xff0000).build()); //LogUtils.log("create-mesh"); //scene.add(mesh); /* ColladaLoader loader=THREE.ColladaLoader(); loader.load("men3smart_hair.dae#1", new ColladaLoadHandler() { public void colladaReady(ColladaData collada) { rawCollada=collada; LogUtils.log(collada); boneNameMaps=new HashMap<String,Integer>(); for(int i=0;i<bones.length();i++){ boneNameMaps.put(bones.get(i).getName(), i); LogUtils.log(i+":"+bones.get(i).getName()); } Geometry geometry=collada.getGeometry(); colladaJoints=collada.getJoints(); Vector3 xup=THREE.Vector3(Math.toRadians(-90),0,0); Matrix4 mx=THREE.Matrix4(); mx.setRotationFromEuler(xup, "XYZ"); geometry.applyMatrix(mx); */ } private void addNode(BVHNode node,List<BVHNode> container){ container.add(node); for(BVHNode child:node.getJoints()){ child.setParentName(node.getName());//somehow name is empty addNode(child,container); } } private AnimationData animationData; private Vec3 bvhVec; private void parseBVH(String bvhText){ final BVHParser parser=new BVHParser(); parser.parseAsync(bvhText, new ParserListener() { @Override public void onSuccess(BVH bv) { LogUtils.log("BVH Loaded:nameAndChannel="+bv.getNameAndChannels().size()+",frame-size="+bv.getFrames()); setBvh(bv); } @Override public void onFaild(String message) { LogUtils.log(message); } }); } private String animationName; private Geometry loadedGeometry; private Mesh selectionPointIndicateMesh; //used for mouse selection ,added mesh's eash point and bone-joint. JsArray<Object3D> objects; @SuppressWarnings("unchecked") private void initializeObject(){ currentTime=0; //for skinned mesh if(root!=null){ scene.remove(root); } root=THREE.Object3D(); scene.add(root); if(boneAndVertex!=null){ scene.remove(boneAndVertex); if(boneSelectionMesh!=null){ boneSelectionMesh=null; } } boneAndVertex = THREE.Object3D(); //boneAndVertex.setPosition(-15, 0, 0); scene.add(boneAndVertex); Object3D bo=createBoneObjects(bvh); //bo.setPosition(-30, 0, 0); boneAndVertex.add(bo); double selectionSize=0.05*baseScale; selectionPointIndicateMesh=THREE.Mesh(THREE.CubeGeometry(selectionSize, selectionSize, selectionSize), THREE.MeshBasicMaterial().color(selectColor).transparent(true).wireFrame(true).build()); boneAndVertex.add(selectionPointIndicateMesh); selectionPointIndicateMesh.setVisible(false); } private int selectColor=0xb362ff; //for selection private List<Mesh> wireBodyPoints=new ArrayList<Mesh>(); //private int defaultColor=0xffff00; private void createWireBody(){ wireBodyPoints.clear(); bodyGeometry=GeometryUtils.clone(loadedGeometry); wireBody = THREE.Mesh(bodyGeometry, THREE.MeshBasicMaterial().wireFrame(true).color(0xffffff).build()); boneAndVertex.add(wireBody); selectVertex=THREE.Object3D(); vertexMeshs.clear(); boneAndVertex.add(selectVertex); double bmeshSize=0.01*baseScale; Geometry cube=THREE.CubeGeometry(bmeshSize, bmeshSize, bmeshSize); for(int i=0;i<bodyGeometry.vertices().length();i++){ Material mt=THREE.MeshBasicMaterial().color(getVertexColor(i)).build(); Vector3 vx=bodyGeometry.vertices().get(i); Mesh point=THREE.Mesh(cube, mt); point.setVisible(false); point.setName("point:"+i); point.setPosition(vx); selectVertex.add(point); vertexMeshs.add(point); wireBodyPoints.add(point); } } /* call change listener ,this is not good private void changeAutoWeightListBox(int value){ //callAutoWeight=false; autoWeightListBox.setSelectedIndex(value); //callAutoWeight=true; } */ private void autoWeight(){ clearBodyIndicesAndWeightArray(); LogUtils.log(loadedGeometry); //have valid skinIndices and weight use from that. if(GWTGeometryUtils.isValidSkinIndicesAndWeight(loadedGeometry)){ WeightBuilder.autoWeight(loadedGeometry, bones, endSites,WeightBuilder.MODE_FROM_GEOMETRY, bodyIndices, bodyWeight); //changeAutoWeightListBox(0); //wait must be 1.0 for(int i=0;i<bodyWeight.length();i++){ Vector4 vec4=bodyWeight.get(i); double total=vec4.getX()+vec4.getY(); double remain=(1.0-total)/2; //vec4.setX(vec4.getX()+remain);// i guess this is problem //vec4.setY(vec4.getY()+remain); } /* List<String> lines=new ArrayList<String>(); for(int i=0;i<bodyWeight.length();i++){ lines.add(i+get(bodyWeight.get(i))); } LogUtils.log("before:"); LogUtils.log(Joiner.on("\n").join(lines)); */ }else{ LogUtils.log("empty indices&weight auto-weight from geometry:this action take a time"); //can't auto weight algo change? TODO it WeightBuilder.autoWeight(loadedGeometry, bones, endSites,WeightBuilder.MODE_MODE_Start_And_Half_ParentAndChildrenAgressive, bodyIndices, bodyWeight); //changeAutoWeightListBox(1); } } @SuppressWarnings("unchecked") private void clearBodyIndicesAndWeightArray(){ bodyIndices = (JsArray<Vector4>) JsArray.createArray(); bodyWeight = (JsArray<Vector4>) JsArray.createArray(); } private void loadJsonModel(JSONObject object,JSONLoadHandler handler){ JSONLoader loader=THREE.JSONLoader(); JavaScriptObject jsobject=loader.parse(object.getJavaScriptObject(), null); JSONObject newobject=new JSONObject(jsobject); handler.loaded((Geometry) newobject.get("geometry").isObject().getJavaScriptObject(),null); LogUtils.log("json"); LogUtils.log(object.getJavaScriptObject()); //loader.createModel(object.getJavaScriptObject(), handler, ""); //loader.onLoadComplete(); //return object; } //TODO replace to GWTThreeUtils.parseJsonObject private JSONObject parseJsonObject(String jsonText){ JSONValue lastJsonValue = JSONParser.parseStrict(jsonText); JSONObject object=lastJsonValue.isObject(); if(object==null){ LogUtils.log("invalid-json object"); } return object; } //this is original loaded text,dont edit it private String lastLoadedText; private void loadModel(String path,final JSONLoadHandler handler){ RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(path)); try { builder.sendRequest(null, new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { lastLoadedText=response.getText(); JSONObject object=parseJsonObject(lastLoadedText); lastJsonObject=object; loadJsonModel(object,handler); } @Override public void onError(Request request, Throwable exception) { Window.alert("load faild:"); } }); } catch (RequestException e) { LogUtils.log(e.getMessage()); e.printStackTrace(); } } private String textureUrl="asian_blondhair_tshirt.png"; private String bvhUrl="standing2.bvh"; private String modelUrl="model001_female2661_bone19.js"; private Texture texture; private void generateTexture(){ final Image img=new Image(textureUrl); img.setVisible(false); RootPanel.get().add(img); img.addLoadHandler(new com.google.gwt.event.dom.client.LoadHandler() { @Override public void onLoad(LoadEvent event) { Canvas canvas=Canvas.createIfSupported(); canvas.setCoordinateSpaceWidth(img.getWidth()); canvas.setCoordinateSpaceHeight(img.getHeight()); canvas.getContext2d().drawImage(ImageElement.as(img.getElement()),0,0); texture=THREE.Texture(canvas.getCanvasElement()); texture.setNeedsUpdate(true); //Window.open(canvas.toDataUrl(), "test", null); img.removeFromParent(); updateMaterial(); } }); } @Override public void onMouseWheel(MouseWheelEvent event) { double tzoom=0.05*baseScale; //TODO make class long t=System.currentTimeMillis(); if(mouseLast+100>t){ czoom*=2; }else{ czoom=tzoom; } //GWT.log("wheel:"+event.getDeltaY()); double tmp=cameraZ+event.getDeltaY()*czoom; tmp=Math.max(0.2, tmp); tmp=Math.min(4000, tmp); cameraZ=(double)tmp; mouseLast=t; } double czoom; protected void updateMaterial() { Material material=null; texture.setFlipY(needFlipY);//for temporary release //TODO as option for 3.1 format models if(!needFlipY){ LogUtils.log("texture flipY:false for old 3.0 format"); } if(useBasicMaterial.getValue()){ material=THREE.MeshBasicMaterial().skinning(true).color(0xffffff).map(texture).build(); }else{ material=THREE.MeshLambertMaterial().skinning(true).color(0xffffff).map(texture).build(); } if(skinnedMesh!=null){ skinnedMesh.setMaterial(material); } } private void createSkinnedMesh(){ LogUtils.log("createSkinnedMesh"); String json=toJsonText(); JSONObject object=parseJsonObject(json); //JSONObject object=parseJsonObject(lastLoadedText); //try load original loadJsonModel(object,new JSONLoadHandler() { @Override public void loaded(Geometry geometry, JsArray<Material> materials) { if(skinnedMesh!=null){ root.remove(skinnedMesh); } Material material=null; if(useBasicMaterial.getValue()){ material=THREE.MeshBasicMaterial().skinning(true).color(0xffffff).map(texture).build(); }else{ material=THREE.MeshLambertMaterial().skinning(true).color(0xffffff).map(texture).build(); } //try to better ,but seems faild /* LogUtils.log("skinmesh root bone pos changed to 0"); AnimationBone bone=geometry.getBones().get(0); Vector3 rootOffset=THREE.Vector3(bone.getPos().get(0), bone.getPos().get(1),bone.getPos().get(2)); for(int i=0;i<geometry.getVertices().length();i++){ geometry.getVertices().get(i).sub(rootOffset); } bone.setPos(0, 0, 0);//root is 0 is better? */ //trying vertex color /* material=THREE.MeshBasicMaterial(vertexColors()); List<Integer> result=new ArrayList<Integer>(); groupdFaces(result,geometry.getFaces(),0); Color red=THREE.Color(0xff0000); LogUtils.log("size:"+result.size()); for(int index:result){ geometry.getFaces().get(index).setColor(red); } */ LogUtils.log("before skinned"); LogUtils.log(geometry); skinnedMesh = THREE.SkinnedMesh(geometry, material); root.add(skinnedMesh); if(animation!=null){ AnimationHandler.removeFromUpdate(animation); } //i guess this crash,if animation length is 1 if(animationName!=null){//animation setted when set bvh animation = THREE.Animation( skinnedMesh, animationName ); LogUtils.log(animation); animation.play(true,0); } //debug for geometry inside animation /* if(geometry.getAnimations()!=null){ if(geometry.getAnimations().length()>0){ animationName=geometry.getAnimations().get(0).getName(); AnimationHandler.add(geometry.getAnimations().get(0)); LogUtils.log(geometry.getAnimations().get(0)); LogUtils.log("start new animation:"+animationName); LogUtils.log(skinnedMesh); animation = THREE.Animation( skinnedMesh, animationName ); LogUtils.log(animation); animation.play(true,0); }else{ animation=null; LogUtils.log("this bone has no animation"); } } */ } }); } /* public List<Integer> groupdFaces(List<Integer> result,JsArray<Face3> faces,int targetIndex){ result.add(targetIndex); Face3 face=faces.get(targetIndex); int a=(int) face.getA(); for(int i=0;i<faces.length();i++){ if(result.contains(i)){ continue; }else{ if(hasIndex(faces.get(i), a)){ groupdFaces(result,faces,i); } } } int b=(int) face.getB(); for(int i=0;i<faces.length();i++){ if(result.contains(i)){ continue; }else{ if(hasIndex(faces.get(i), b)){ groupdFaces(result,faces,i); } } } int c=(int) face.getC(); for(int i=0;i<faces.length();i++){ if(result.contains(i)){ continue; }else{ if(hasIndex(faces.get(i), c)){ groupdFaces(result,faces,i); } } } if(face.isFace4()){ int d=(int) face.getD(); for(int i=0;i<faces.length();i++){ if(result.contains(i)){ continue; }else{ if(hasIndex(faces.get(i), d)){ groupdFaces(result,faces,i); } } } } return result; } private boolean hasIndex(Face3 face,int index){ if(face.getA()==index){ return true; } if(face.getB()==index){ return true; } if(face.getC()==index){ return true; } if(face.isFace4() && face.getD()==index){ return true; } return false; } */ //for vertex color material public static native final JavaScriptObject vertexColors()/*-{ return {vertexColors: $wnd.THREE.VertexColors }; }-*/; private List<Mesh> vertexMeshs=new ArrayList<Mesh>(); private IndexAndWeightEditor indexWeightEditor; //simple simple near positions only use end point,this is totall not good private int findNear(List<Vector3> bonePositions,Vector3 pos){ Vector3 pt=THREE.Vector3(); Vector3 near=pt.sub(bonePositions.get(0),pos); int index=0; double length=pt.length(); for(int i=1;i<bonePositions.size();i++){ Vector3 npt=THREE.Vector3(); near=npt.sub(bonePositions.get(i),pos); double l=near.length(); if(l<length){ index=i; length=l; } } return index; } private Map<Integer,Integer> createChildMap(JsArray<AnimationBone> bones){ Map<Integer,Integer> childMap=new HashMap<Integer,Integer>(); for(int i=0;i<bones.length();i++){ List<Integer> children=new ArrayList<Integer>(); for(int j=0;j<bones.length();j++){ AnimationBone child=bones.get(j); if(child.getParent()==i){ children.add(j); } } if(children.size()==1){ childMap.put(i, children.get(0)); } } return childMap; } List<List<GWTWeightData>> wdatas; /* * some point totally wrong?or only work on multiple weight points * */ JsArrayString colladaJoints; Map<String,Integer> boneNameMaps; private CheckBox useBasicMaterial; //this is used for export so,not original loaded private JSONObject lastJsonObject; private CheckBox withAnimation; private StackLayoutPanel stackPanel; private ListBox boneListBox; private Button updateWeightButton; private InputRangeWidget frameRange; private TextBox saveFileBox; private VerticalPanel exportLinks; private Anchor anchor; private Label weightSelection; private Label modelSelection; private ListBox autoWeightListBox; private Label bvhSelection; private Label textureSelection; //private boolean callAutoWeight=true; private Vector4 convertWeight(int index,ColladaData collada){ if(wdatas==null){ //wdatas=new WeighDataParser().parse(Bundles.INSTANCE.weight().getText()); wdatas=new WeighDataParser().convert(collada.getWeights()); for(List<GWTWeightData> wd:wdatas){ String log=""; for(GWTWeightData w:wd){ log+=w.getBoneIndex()+":"+w.getWeight()+","; } //LogUtils.log(log); } } List<GWTWeightData> wd=wdatas.get(index); if(wd.size()<2){ int id=wd.get(0).getBoneIndex(); String fname=colladaJoints.get(id); id=boneNameMaps.get(fname); return THREE.Vector4(id,id,1,0); }else{ int fid=wd.get(0).getBoneIndex(); int sid=wd.get(1).getBoneIndex(); String fname=colladaJoints.get(fid); fid=boneNameMaps.get(fname); String sname=colladaJoints.get(sid); sid=boneNameMaps.get(sname); double fw=wd.get(0).getWeight(); double sw=wd.get(1).getWeight(); //LogUtils.log(fid+":"+fw+","+sid+":"+sw); //fw=1; return THREE.Vector4(fid,sid,fw,sw); } } private Vector4 findNearSpecial(List<NameAndPosition> nameAndPositions,Vector3 pos,JsArray<AnimationBone> bones,int vindex){ Vector3 pt=nameAndPositions.get(0).getPosition().clone(); Vector3 near=pt.subSelf(pos); int index1=nameAndPositions.get(0).getIndex(); double near1=near.length(); int index2=index1; double near2=near1; int nameIndex1=0; int nameIndex2=0; for(int i=1;i<nameAndPositions.size();i++){ Vector3 npt=nameAndPositions.get(i).getPosition().clone(); Vector3 subPos=npt.subSelf(pos); double l=subPos.length(); //if(vindex==250)LogUtils.log(nameAndPositions.get(i).getName()+","+l); if(l<near1){ int tmp=index1; double tmpL=near1; int tmpName=nameIndex1; index1=nameAndPositions.get(i).getIndex(); near1=l; nameIndex1=i; if(tmpL<near2){ index2=tmp; near2=tmpL; nameIndex2=tmpName; } }else if(l<near2){ index2=nameAndPositions.get(i).getIndex(); near2=l; nameIndex2=i; } } Map<Integer,Double> totalLength=new HashMap<Integer,Double>(); Map<Integer,Integer> totalIndex=new HashMap<Integer,Integer>(); //zero is largest Vector3 rootNear=nameAndPositions.get(0).getPosition().clone(); rootNear.subSelf(pos); for(int i=0;i<nameAndPositions.size();i++){ int index=nameAndPositions.get(i).getIndex(); Vector3 nearPos=nameAndPositions.get(i).getPosition().clone(); nearPos.subSelf(pos); double l=nearPos.length(); Double target=totalLength.get(index); double cvalue=0; if(target!=null){ cvalue=target.doubleValue(); } cvalue+=l; totalLength.put(index,cvalue); Integer count=totalIndex.get(index); int countV=0; if(count!=null){ countV=count; } countV++; totalIndex.put(index, countV); } //do average for end like head Integer[] keys=totalLength.keySet().toArray(new Integer[0]); for(int i=0;i<keys.length;i++){ int index=keys[i]; int count=totalIndex.get(index); totalLength.put(index, totalLength.get(index)/count); } if(index1==index2){ //LogUtils.log(""+vindex+","+nameIndex1+":"+nameIndex2); if(vindex==250){ // LogUtils.log(nameAndPositions.get(nameIndex1).getPosition()); // LogUtils.log(nameAndPositions.get(nameIndex2).getPosition()); } return THREE.Vector4(index1,index1,1,0); }else{ double near1Length=totalLength.get(index1); double near2Length=totalLength.get(index2); double total=near1Length+near2Length; return THREE.Vector4(index1,index2,(total-near1Length)/total,(total-near2Length)/total); } } private Vector4 findNearThreeBone(List<NameAndPosition> nameAndPositions,Vector3 pos,JsArray<AnimationBone> bones,int vindex){ Map<Integer,Double> totalLength=new HashMap<Integer,Double>(); Map<Integer,Integer> totalIndex=new HashMap<Integer,Integer>(); //LogUtils.log("find-near:"+vindex); for(int i=0;i<nameAndPositions.size();i++){ int index=nameAndPositions.get(i).getIndex(); Vector3 near=nameAndPositions.get(i).getPosition().clone(); near.subSelf(pos); double l=near.length(); Double target=totalLength.get(index); double cvalue=0; if(target!=null){ cvalue=target.doubleValue(); } cvalue+=l; totalLength.put(index,cvalue); Integer count=totalIndex.get(index); int countV=0; if(count!=null){ countV=count; } countV++; totalIndex.put(index, countV); } Integer[] keys=totalLength.keySet().toArray(new Integer[0]); for(int i=0;i<keys.length;i++){ int index=keys[i]; int count=totalIndex.get(index); totalLength.put(index, totalLength.get(index)/count); } int index1=0; double near1=totalLength.get(keys[0]); int index2=0; double near2=totalLength.get(keys[0]); for(int i=1;i<keys.length;i++){ double l=totalLength.get(keys[i]); if(l<near1){ int tmp=index1; double tmpL=near1; index1=keys[i]; near1=l; if(tmpL<near2){ index2=tmp; near2=tmpL; } }else if(l<near2){ index2=keys[i]; near2=l; } } if(index1==index2){ return THREE.Vector4(index1,index1,1,0); }else{ double total=near1+near2; //LogUtils.log("xx:"+index1+","+index2); return THREE.Vector4(index1,index2,(total-near1)/total,(total-near2)/total); } } //use start,center and end position,choose near 2point private Vector4 findNearBoneAggresive(List<NameAndPosition> nameAndPositions,Vector3 pos,JsArray<AnimationBone> bones){ Vector3 pt=nameAndPositions.get(0).getPosition().clone(); Vector3 near=pt.subSelf(pos); int index1=nameAndPositions.get(0).getIndex(); double near1=pt.length(); int index2=nameAndPositions.get(0).getIndex(); double near2=pt.length(); for(int i=1;i<nameAndPositions.size();i++){ Vector3 npt=nameAndPositions.get(i).getPosition().clone(); near=npt.subSelf(pos); double l=near.length(); if(l<near1){ int tmp=index1; double tmpL=near1; index1=nameAndPositions.get(i).getIndex(); near1=l; if(tmpL<near2){ index2=tmp; near2=tmpL; } }else if(l<near2){ index2=nameAndPositions.get(i).getIndex(); near2=l; } } near1*=near1*near1*near1; near2*=near2*near2*near2; if(index1==index2){ return THREE.Vector4(index1,index1,1,0); }else{ double total=near1+near2; return THREE.Vector4(index1,index2,(total-near1)/total,(total-near2)/total); } } /* * find near ,but from three point */ private Vector4 findNearSingleBone(List<NameAndPosition> nameAndPositions,Vector3 pos,JsArray<AnimationBone> bones){ Vector3 pt=nameAndPositions.get(0).getPosition().clone(); Vector3 near=pt.subSelf(pos); int index1=nameAndPositions.get(0).getIndex(); double near1=pt.length(); for(int i=1;i<nameAndPositions.size();i++){ Vector3 npt=nameAndPositions.get(i).getPosition().clone(); near=npt.subSelf(pos); double l=near.length(); if(l<near1){ index1=nameAndPositions.get(i).getIndex(); near1=l; } } return THREE.Vector4(index1,index1,1,0); } //find neard point,choose second from parent or children which near than private Vector4 findNearParentAndChildren(List<Vector3> bonePositions, Vector3 pos,JsArray<AnimationBone> bones){ Map<Integer,Integer> cm=createChildMap(bones); Vector3 pt=THREE.Vector3(); Vector3 near=pt.sub(bonePositions.get(0),pos); int index=0; double length=pt.length(); for(int i=1;i<bonePositions.size();i++){ Vector3 npt=THREE.Vector3(); near=npt.sub(bonePositions.get(i),pos); double l=near.length(); if(l<length){ index=i; length=l; } } if(index!=0){ Vector3 parentPt=THREE.Vector3(); int parentIndex=bones.get(index).getParent(); parentPt=parentPt.sub(bonePositions.get(parentIndex),pos); double plength=parentPt.length(); Integer child=cm.get(index); if(child!=null){ Vector3 childPt=THREE.Vector3(); childPt=childPt.sub(bonePositions.get(child),pos); double clength=childPt.length(); if(clength<plength){ double total=length+clength; return THREE.Vector4(index,child,(total-length)/total,(total-clength)/total); }else{ double total=length+plength; return THREE.Vector4(index,parentIndex,(total-length)/total,(total-plength)/total); } }else{ double total=length+plength; return THREE.Vector4(index,parentIndex,(total-length)/total,(total-plength)/total); } }else{ return THREE.Vector4(index,index,1,0);//root } } /* * find near and choose parent */ private Vector4 findNearParent(List<Vector3> bonePositions, Vector3 pos,JsArray<AnimationBone> bones){ Vector3 pt=THREE.Vector3(); Vector3 near=pt.sub(bonePositions.get(0),pos); int index=0; double length=pt.length(); for(int i=1;i<bonePositions.size();i++){ Vector3 npt=THREE.Vector3(); near=npt.sub(bonePositions.get(i),pos); double l=near.length(); if(l<length){ index=i; length=l; } } if(index!=0){ Vector3 parentPt=THREE.Vector3(); int parentIndex=bones.get(index).getParent(); parentPt=parentPt.sub(bonePositions.get(parentIndex),pos); double plength=parentPt.length(); double total=length+plength; return THREE.Vector4(index,parentIndex,(total-length)/total,(total-plength)/total); }else{ return THREE.Vector4(index,index,1,0);//root } } //choose two point but only near about first * value private Vector4 findNearDouble(List<Vector3> bonePositions, Vector3 pos,double value){ Vector3 pt=THREE.Vector3(); Vector3 near=pt.sub(bonePositions.get(0),pos); int index1=0; double near1=pt.length(); int index2=0; double near2=pt.length(); for(int i=1;i<bonePositions.size();i++){ Vector3 npt=THREE.Vector3(); near=npt.sub(bonePositions.get(i),pos); double l=near.length(); if(l<near1){ int tmp=index1; double tmpL=near1; index1=i; near1=l; if(tmpL<near2){ index2=tmp; near2=tmpL; } }else if(l<near2){ index2=i; near2=l; } } if(index1==index2){ return THREE.Vector4(index1,index1,1,0); }else if(near2>near1*value){ //too fa near2 return THREE.Vector4(index1,index1,1,0); }else{ double total=near1+near2; return THREE.Vector4(index1,index2,near1/total,near2/total); } } @Override public String getTabTitle() { return "Weight Tool"; } @Override public String getHtml(){ String html="Weight Tool ver."+version+" "+super.getHtml(); return html; } @Override public void onMouseClick(ClickEvent event) { // TODO Auto-generated method stub } private void onTextureFileUploaded(final File file,String value){ textureUrl=value; generateTexture(); //createSkinnedMesh(); textureSelection.setText("selection:"+file.getFileName()); } private void onBVHFileUploaded(final File file,String value){ parseBVH(value); bvhSelection.setText("selection:"+file.getFileName()); } private void onWeightFileUploaded(final File file,String value){ JSONObject object=parseJsonObject(value); //dont need json object,just use weights and indecis info loadJsonModel(object,new JSONLoadHandler() { @Override public void loaded(Geometry geometry,JsArray<Material> materials) { onWeightLoaded(file.getFileName(), geometry, materials); } }); } private void onModelFileUploaded(final File file,String value){ lastLoadedText=value; JSONObject object=parseJsonObject(value); lastJsonObject=object;//lastJson object used in exportAsJson LogUtils.log(lastJsonObject.getJavaScriptObject()); /* old code for force scale up if(force10x.getValue()){ JSONNumber jscale=lastJsonObject.get("scale").isNumber(); if(jscale!=null ){ double scale=(int) jscale.doubleValue(); JSONArray jvertices=lastJsonObject.get("vertices").isArray(); LogUtils.log("scale:"+scale); if(jvertices!=null){ LogUtils.log("scale attribute found in json file,and scale it only vertices"); JsArrayNumber numbers=(JsArrayNumber) jvertices.getJavaScriptObject(); for(int i=0;i<numbers.length();i++){ if(scale==1){ numbers.set(i, numbers.get(i)*scale*10); }else{ numbers.set(i, numbers.get(i)*scale); } } } } } */ loadJsonModel(object,new JSONLoadHandler() { @Override public void loaded(Geometry geometry,JsArray<Material> materials) { /* LogUtils.log("force scale up x10,"); for(int i=0;i<geometry.getVertices().length();i++){ Vector3 vec=geometry.getVertices().get(i); vec.multiply(THREE.Vector3(10, 10, 10)); } geometry.setVerticesNeedUpdate(true); */ onModelLoaded(file.getFileName(),geometry); createSkinnedMesh(); } }); } @Override public void onDoubleClick(DoubleClickEvent event) { unselectAll(); } private void unselectAll() { clearBodyPointSelections();//clear only selection selectVertexsByBone(-1);//not bone selected changeBoneSelectionColor(null); //TODO disable bone&weight panel } private static final int TYPE_UNKNOWN=0; private static final int TYPE_IMAGE=1; private static final int TYPE_JSON=2; private static final int TYPE_BVH=3; //private CheckBox force10x; private InfoPanelTab infoPanel; private CheckBox controlBone; private Button pauseBt; private Mesh wireBody; protected void onDrop(DropEvent event){ LogUtils.log("root-drop"); event.preventDefault();//TODO String[] images={"png","jpg","jpeg"}; String[] jsons={"js","json"}; String[] bvhs={"bvh"}; final JsArray<File> files = FileUtils.transferToFile(event .getNativeEvent()); final String fileName=files.get(0).getFileName(); int type=0; for(String name:images){ if(fileName.toLowerCase().endsWith("."+name)){ type=TYPE_IMAGE; break; } } if(type==TYPE_UNKNOWN){ for(String name:jsons){ if(fileName.toLowerCase().endsWith("."+name)){ type=TYPE_JSON; break; } } } if(type==TYPE_UNKNOWN){ for(String name:bvhs){ if(fileName.toLowerCase().endsWith("."+name)){ type=TYPE_BVH; break; } } } final int final_type=type; final FileReader reader = FileReader.createFileReader(); if (files.length() > 0) { reader.setOnLoad(new FileHandler() { @Override public void onLoad() { switch(final_type){ case TYPE_BVH: onBVHFileUploaded(files.get(0), reader.getResultAsString()); break; case TYPE_IMAGE: onTextureFileUploaded(files.get(0), reader.getResultAsString()); break; case TYPE_JSON: onModelFileUploaded(files.get(0), reader.getResultAsString()); break; case TYPE_UNKNOWN://never happen } } }); if(type==TYPE_UNKNOWN){ Window.alert("not supported file-type:"+fileName); }else{ if(type==TYPE_IMAGE){ reader.readAsDataURL(files.get(0)); }else{ reader.readAsText(files.get(0),"UTF-8"); } } //TODO support multiple files } } }
package org.perfcake.pc4idea.editor; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiManager; import com.intellij.ui.EditorTextField; import com.intellij.ui.JBSplitter; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.treeStructure.Tree; import org.jetbrains.annotations.NotNull; import org.perfcake.PerfCakeConst; import org.perfcake.model.Scenario; import org.perfcake.pc4idea.editor.panels.*; import org.xml.sax.SAXException; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import java.awt.*; import java.io.File; public class PCEditorGUI extends JPanel /*implements DataProvider, ModuleProvider TODO ??? */{ // private static final Logger LOG = Logger.getInstance("#main.java..GuiEditor"); /*TODO*/ private final Project project; private Module module; @NotNull private final VirtualFile file; /*TODO final?*/ private Scenario scenarioModel; private JTabbedPane tabbedPane; private JPanel panelDesigner; private JPanel panelSource; private EditorTextField/*JTextArea*/ textAreaForPanelSource; /*TODO*/ private JBSplitter splitterForDesigner; private JPanel panelPCCompsMenu; private JScrollPane scrollPanePCCompsMenu; private JPanel panelPCCompsDesigner; private JScrollPane scrollPanePCCompsDesigner; private JTree treePCcomponents; private AbstractPanel generatorPanel; private AbstractPanel senderPanel; private AbstractPanel messagesPanel; private AbstractPanel validationPanel; private AbstractPanel reportingPanel; private AbstractPanel propertiesPanel; public PCEditorGUI(Project project, @NotNull final Module module, @NotNull final VirtualFile file) { // LOG.assertTrue(file.isValid()); this.project = project; this.module = module; this.file = file; initComponents(); loadScenario(); /*TODO how saving works*/ GridLayout layout = new GridLayout(1,1); this.setLayout(layout); this.add(tabbedPane,new GridLayout(1,1)); } private void initComponents() { tabbedPane = new JTabbedPane(); panelDesigner = new JPanel(new GridLayout(1,1)); panelSource = new JPanel(new GridLayout(1,1)); /*TODO problem with file -> try to get by path, xmlEdtiorProvider.getEditor?*/ textAreaForPanelSource = /*new JTextArea();*/ new EditorTextField(PsiDocumentManager.getInstance(project).getDocument(PsiManager.getInstance(project).findFile(file)),project, StdFileTypes.XML); splitterForDesigner = new JBSplitter(false); panelPCCompsMenu = new JPanel(); panelPCCompsDesigner = new JPanel(); treePCcomponents = new Tree(new DefaultTreeModel(new DefaultMutableTreeNode("root"))); generatorPanel = new GeneratorPanel(project); senderPanel = new SenderPanel(project); messagesPanel = new MessagesPanel(project); validationPanel = new ValidationPanel(project); reportingPanel = new ReportingPanel(project); propertiesPanel = new PropertiesPanel(project); tabbedPane.addTab("Designer", panelDesigner); tabbedPane.addTab("Source", panelSource); tabbedPane.setTabPlacement(JTabbedPane.BOTTOM); panelSource.add(textAreaForPanelSource); panelSource.setBackground(EditorColorsManager.getInstance().getGlobalScheme().getDefaultBackground()); // ApplicationManager.getApplication().runReadAction(new Runnable() { // public void run() { // try { // textAreaForPanelSource.setText(new String(file.contentsToByteArray())); // } catch (IOException e) { // e.printStackTrace(); /*TODO log*/ //textAreaForPanelSource.setEditable(false); //textAreaForPanelSource.setOpaque(false); panelDesigner.add(splitterForDesigner); scrollPanePCCompsDesigner = ScrollPaneFactory.createScrollPane(panelPCCompsDesigner); scrollPanePCCompsDesigner.setMinimumSize(new Dimension(400,0)); scrollPanePCCompsMenu = ScrollPaneFactory.createScrollPane(panelPCCompsMenu); scrollPanePCCompsMenu.setMinimumSize(new Dimension(100,0)); splitterForDesigner.setFirstComponent(scrollPanePCCompsMenu); splitterForDesigner.setSecondComponent(scrollPanePCCompsDesigner); splitterForDesigner.setProportion(0.15f); GroupLayout panelPCCompsMenuLayout = new GroupLayout(panelPCCompsMenu); panelPCCompsMenu.setLayout(panelPCCompsMenuLayout); panelPCCompsMenuLayout.setVerticalGroup(panelPCCompsMenuLayout.createSequentialGroup().addComponent(treePCcomponents)); panelPCCompsMenuLayout.setHorizontalGroup(panelPCCompsMenuLayout.createSequentialGroup().addComponent(treePCcomponents)); panelPCCompsMenu.setBackground(EditorColorsManager.getInstance().getGlobalScheme().getDefaultBackground()); DefaultMutableTreeNode root = (DefaultMutableTreeNode)treePCcomponents.getModel().getRoot(); DefaultMutableTreeNode messages = new DefaultMutableTreeNode("Messages"); messages.add(new DefaultMutableTreeNode("Message")); /*TODO from classpath*/ root.add(messages); DefaultMutableTreeNode validators = new DefaultMutableTreeNode("Validators"); validators.add(new DefaultMutableTreeNode("DictionaryValidator")); validators.add(new DefaultMutableTreeNode("RegExpValidator")); validators.add(new DefaultMutableTreeNode("RulesValidator")); validators.add(new DefaultMutableTreeNode("ScriptValidator")); root.add(validators); DefaultMutableTreeNode reporters = new DefaultMutableTreeNode("Reporters"); reporters.add(new DefaultMutableTreeNode("ThroughputStatsReporter")); reporters.add(new DefaultMutableTreeNode("MemoryUsageReporter")); reporters.add(new DefaultMutableTreeNode("ResponseTimeStatsReporter")); reporters.add(new DefaultMutableTreeNode("WarmUpReporter")); reporters.add(new DefaultMutableTreeNode("ThroughputStatsReporter")); root.add(reporters); DefaultMutableTreeNode destinations = new DefaultMutableTreeNode("Destinations"); destinations.add(new DefaultMutableTreeNode("ConsoleDestination")); destinations.add(new DefaultMutableTreeNode("CsvDestination")); destinations.add(new DefaultMutableTreeNode("Log4jDestination")); root.add(destinations); DefaultMutableTreeNode properties = new DefaultMutableTreeNode("Properties"); properties.add(new DefaultMutableTreeNode("Property")); root.add(properties); DefaultMutableTreeNode connections = new DefaultMutableTreeNode("Connections"); connections.add(new DefaultMutableTreeNode("Attach validator")); root.add(connections); treePCcomponents.expandRow(0); treePCcomponents.setRootVisible(false); //treePCcomponents.setDragEnabled(true); treePCcomponents.setOpaque(false); panelPCCompsDesigner.setBackground(EditorColorsManager.getInstance().getGlobalScheme().getDefaultBackground()); GroupLayout panelPCCompsDesignerLayout = new GroupLayout(panelPCCompsDesigner); panelPCCompsDesigner.setLayout(panelPCCompsDesignerLayout); panelPCCompsDesignerLayout.setHorizontalGroup( panelPCCompsDesignerLayout.createParallelGroup() .addComponent(generatorPanel) .addComponent(senderPanel) .addGroup(panelPCCompsDesignerLayout.createSequentialGroup() .addGroup(panelPCCompsDesignerLayout.createParallelGroup() .addComponent(messagesPanel) .addComponent(validationPanel)) .addComponent(reportingPanel)) .addComponent(propertiesPanel) ); panelPCCompsDesignerLayout.setVerticalGroup( panelPCCompsDesignerLayout.createSequentialGroup() .addComponent(generatorPanel) .addComponent(senderPanel) .addGroup(panelPCCompsDesignerLayout.createParallelGroup() .addGroup(panelPCCompsDesignerLayout.createSequentialGroup() .addComponent(messagesPanel) .addComponent(validationPanel)) .addComponent(reportingPanel)) .addComponent(propertiesPanel) .addContainerGap(0, Short.MAX_VALUE) /*TODO decide*/ ); } private void loadScenario(){ try { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(getClass().getResource("/schemas/" + "perfcake-scenario-" + PerfCakeConst.XSD_SCHEMA_VERSION + ".xsd")); JAXBContext context = JAXBContext.newInstance(org.perfcake.model.Scenario.class); Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setSchema(schema); scenarioModel = (org.perfcake.model.Scenario) unmarshaller.unmarshal(new File(file.getPath())); } catch (JAXBException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } // upadate apanels generatorPanel.setComponent(scenarioModel.getGenerator()); senderPanel.setComponent(scenarioModel.getSender()); reportingPanel.setComponent(scenarioModel.getReporting()); } public JComponent getPreferredFocusedComponent() { return tabbedPane; } public void dispose() { /*TODO */ } }
import static org.bytedeco.javacpp.opencv_core.IPL_DEPTH_8U; import java.awt.Color; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.awt.image.WritableRaster; import org.opencv.core.Mat; import org.opencv.core.Point; import org.opencv.core.Scalar; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; public class ImgUtil { //A image processing helper class that has simple uses and out of the way. private static int LOW_THRESHOLD = 100; private static int HIGH_THRESHOLD = 255; private final static int BOARD_DIMENSION = 9; private final static int BOX_DIMENSION = 3; //remove color data from the image public static Mat toGreyscale(Mat source) { Mat greyscale = new Mat(); Imgproc.cvtColor(source, greyscale, Imgproc.COLOR_BGR2GRAY); return greyscale; } //Remove range of grey to be within the low and high threshold and create an bone structure like image public static Mat toCanny(Mat source) { Mat canny = new Mat(source.size(), IPL_DEPTH_8U); Imgproc.Canny(source, canny, LOW_THRESHOLD, HIGH_THRESHOLD, 3, false); return canny; } //Invert black and white images public static Mat toThreshBinary(Mat source){ Mat threshold = new Mat(); Imgproc.threshold(source, threshold, LOW_THRESHOLD, HIGH_THRESHOLD, Imgproc.THRESH_BINARY_INV); return threshold; } //processed machine view for Developer display public static Mat getMachineView(Mat source){ return toDilate(toCanny(toGreyscale(source.clone())), 2); } //Reduce noise from images public static Mat toDilate(Mat source, int erosion_size) { Size kSize = new Size(2 * erosion_size + 1, 2 * erosion_size + 1); Point anchor = new Point(erosion_size, erosion_size); Mat element = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, kSize, anchor); Mat dilateDes = new Mat(source.size(), IPL_DEPTH_8U); Imgproc.dilate(source, dilateDes, element); return dilateDes; } //invert black and white colors public static Mat getInvert(Mat source, int erosionLvl){ Mat invert = new Mat(); Imgproc.threshold(getUsableImg(source.clone(), erosionLvl), invert, 240, 255, Imgproc.THRESH_BINARY_INV); return invert; } //Clean up Mat image for easier optical character recognition processing private static Mat getUsableImg(Mat sourceImg, int erosion_size) { Mat usableImg = new Mat(sourceImg.size(), IPL_DEPTH_8U); Imgproc.cvtColor(sourceImg.clone(), usableImg, Imgproc.COLOR_BGR2GRAY); Imgproc.Canny(usableImg, usableImg, 150, 255, 3, false); Point erodePoint = new Point(erosion_size, erosion_size); Size erodeSize = new Size(2 * erosion_size + 1, 2 * erosion_size + 1); Mat element = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, erodeSize, erodePoint); Imgproc.dilate(usableImg, usableImg, element); return usableImg; } //Mat to BufferedImage public static BufferedImage ToBufferedImage(Mat frame) { int type = 0; if (frame.channels() == 1) { type = BufferedImage.TYPE_BYTE_GRAY; } else if (frame.channels() == 3) { type = BufferedImage.TYPE_3BYTE_BGR; } BufferedImage image = new BufferedImage(frame.width(), frame.height(), type); WritableRaster raster = image.getRaster(); DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer(); byte[] data = dataBuffer.getData(); frame.get(0, 0, data); return image; } //Provide some colors for display depending on the value given public static Scalar getColor(int i) { Color c; switch(i){ case 0: c = Color.red; break; case 1: c = Color.orange; break; case 2: c = Color.blue; break; case 3: c = Color.black; break; case 4: c = Color.cyan; break; case 5: c = Color.white; break; case 6: c = Color.yellow; break; case 7: c = Color.magenta; break; case 8: c = Color.green; break; default: c = Color.gray; break; } return new Scalar(c.getBlue(), c.getGreen(), c.getRed()); } //Print board to console for Debugging for CellObjects public static void printBoard(int[][] table) { for (int i = 0; i < BOARD_DIMENSION; i++) { if (i%BOX_DIMENSION == 0) System.out.println(" for (int j = 0; j < BOARD_DIMENSION; j++) { if (j%BOX_DIMENSION == 0) System.out.print("| "); System.out.print( (table[i][j] == 0) ? " " : Integer.toString(table[i][j])); System.out.print(' '); } System.out.println("|"); } System.out.println(" System.out.println(); } }
package com.android.deskclock.stopwatch; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.view.View; import android.widget.RemoteViews; import com.android.deskclock.CircleTimerView; import com.android.deskclock.DeskClock; import com.android.deskclock.HandleDeskClockApiCalls; import com.android.deskclock.R; import com.android.deskclock.Utils; /** * TODO: Insert description here. (generated by sblitz) */ public class StopwatchService extends Service { // Member fields private int mNumLaps; private long mElapsedTime; private long mStartTime; private boolean mLoadApp; private NotificationManagerCompat mNotificationManager; // Constants for intent information // Make this a large number to avoid the alarm ID's which seem to be 1, 2, ... // Must also be different than TimerReceiver.IN_USE_NOTIFICATION_ID private static final int NOTIFICATION_ID = Integer.MAX_VALUE - 1; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { mNumLaps = 0; mElapsedTime = 0; mStartTime = 0; mLoadApp = false; mNotificationManager = NotificationManagerCompat.from(this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent == null) { return Service.START_NOT_STICKY; } if (mStartTime == 0 || mElapsedTime == 0 || mNumLaps == 0) { // May not have the most recent values. readFromSharedPrefs(); } String actionType = intent.getAction(); long actionTime = intent.getLongExtra(Stopwatches.MESSAGE_TIME, Utils.getTimeNow()); boolean showNotif = intent.getBooleanExtra(Stopwatches.SHOW_NOTIF, true); // Update the stopwatch circle when the app is open or is being opened. boolean updateCircle = !showNotif || intent.getAction().equals(Stopwatches.RESET_AND_LAUNCH_STOPWATCH); switch(actionType) { case HandleDeskClockApiCalls.ACTION_START_STOPWATCH: SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this) ; prefs.edit().putBoolean(Stopwatches.NOTIF_CLOCK_RUNNING, true).apply(); mStartTime = actionTime; writeSharedPrefsStarted(mStartTime, updateCircle); if (showNotif) { setNotification(mStartTime - mElapsedTime, true, mNumLaps); } else { saveNotification(mStartTime - mElapsedTime, true, mNumLaps); } break; case HandleDeskClockApiCalls.ACTION_LAP_STOPWATCH: mNumLaps++; long lapTimeElapsed = actionTime - mStartTime + mElapsedTime; writeSharedPrefsLap(lapTimeElapsed, updateCircle); if (showNotif) { setNotification(mStartTime - mElapsedTime, true, mNumLaps); } else { saveNotification(mStartTime - mElapsedTime, true, mNumLaps); } break; case HandleDeskClockApiCalls.ACTION_STOP_STOPWATCH: prefs = PreferenceManager.getDefaultSharedPreferences(this); prefs.edit().putBoolean(Stopwatches.NOTIF_CLOCK_RUNNING, false).apply(); mElapsedTime = mElapsedTime + (actionTime - mStartTime); writeSharedPrefsStopped(mElapsedTime, updateCircle); if (showNotif) { setNotification(actionTime - mElapsedTime, false, mNumLaps); } else { saveNotification(mElapsedTime, false, mNumLaps); } break; case HandleDeskClockApiCalls.ACTION_RESET_STOPWATCH: mLoadApp = false; writeSharedPrefsReset(updateCircle); clearSavedNotification(); stopSelf(); break; case Stopwatches.RESET_AND_LAUNCH_STOPWATCH: mLoadApp = true; writeSharedPrefsReset(updateCircle); clearSavedNotification(); closeNotificationShade(); stopSelf(); break; case Stopwatches.SHARE_STOPWATCH: if (mElapsedTime > 0) { closeNotificationShade(); Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_SUBJECT, Stopwatches.getShareTitle( getApplicationContext())); shareIntent.putExtra(Intent.EXTRA_TEXT, Stopwatches.buildShareResults( getApplicationContext(), mElapsedTime, readLapsFromPrefs())); Intent chooserIntent = Intent.createChooser(shareIntent, null); chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getApplication().startActivity(chooserIntent); } break; case Stopwatches.SHOW_NOTIF: // SHOW_NOTIF sent from the DeskClock.onPause // If a notification is not displayed, this service's work is over if (!showSavedNotification()) { stopSelf(); } break; case Stopwatches.KILL_NOTIF: mNotificationManager.cancel(NOTIFICATION_ID); break; } // We want this service to continue running until it is explicitly // stopped, so return sticky. return START_STICKY; } @Override public void onDestroy() { mNotificationManager.cancel(NOTIFICATION_ID); clearSavedNotification(); mNumLaps = 0; mElapsedTime = 0; mStartTime = 0; if (mLoadApp) { Intent activityIntent = new Intent(getApplicationContext(), DeskClock.class); activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); activityIntent.putExtra( DeskClock.SELECT_TAB_INTENT_EXTRA, DeskClock.STOPWATCH_TAB_INDEX); startActivity(activityIntent); mLoadApp = false; } } private void setNotification(long clockBaseTime, boolean clockRunning, int numLaps) { Context context = getApplicationContext(); // Intent to load the app for a non-button click. Intent intent = new Intent(context, DeskClock.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(DeskClock.SELECT_TAB_INTENT_EXTRA, DeskClock.STOPWATCH_TAB_INDEX); // add category to distinguish between stopwatch intents and timer intents intent.addCategory("stopwatch"); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT); // Set up remoteviews for the notification. RemoteViews remoteViewsCollapsed = new RemoteViews(getPackageName(), R.layout.stopwatch_notif_collapsed); remoteViewsCollapsed.setOnClickPendingIntent(R.id.swn_collapsed_hitspace, pendingIntent); remoteViewsCollapsed.setChronometer( R.id.swn_collapsed_chronometer, clockBaseTime, null, clockRunning); remoteViewsCollapsed. setImageViewResource(R.id.notification_icon, R.drawable.stat_notify_stopwatch); RemoteViews remoteViewsExpanded = new RemoteViews(getPackageName(), R.layout.stopwatch_notif_expanded); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_expanded_hitspace, pendingIntent); remoteViewsExpanded.setChronometer( R.id.swn_expanded_chronometer, clockBaseTime, null, clockRunning); remoteViewsExpanded. setImageViewResource(R.id.notification_icon, R.drawable.stat_notify_stopwatch); if (clockRunning) { // Left button: lap remoteViewsExpanded.setTextViewText( R.id.swn_left_button, getResources().getText(R.string.sw_lap_button)); Intent leftButtonIntent = new Intent(context, StopwatchService.class); leftButtonIntent.setAction(HandleDeskClockApiCalls.ACTION_LAP_STOPWATCH); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_left_button, PendingIntent.getService(context, 0, leftButtonIntent, 0)); remoteViewsExpanded. setTextViewCompoundDrawablesRelative(R.id.swn_left_button, R.drawable.ic_lap_24dp, 0, 0, 0); // Right button: stop clock remoteViewsExpanded.setTextViewText( R.id.swn_right_button, getResources().getText(R.string.sw_stop_button)); Intent rightButtonIntent = new Intent(context, StopwatchService.class); rightButtonIntent.setAction(HandleDeskClockApiCalls.ACTION_STOP_STOPWATCH); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_right_button, PendingIntent.getService(context, 0, rightButtonIntent, 0)); remoteViewsExpanded. setTextViewCompoundDrawablesRelative(R.id.swn_right_button, R.drawable.ic_stop_24dp, 0, 0, 0); // Show the laps if applicable. if (numLaps > 0) { String lapText = String.format( context.getString(R.string.sw_notification_lap_number), numLaps); remoteViewsCollapsed.setTextViewText(R.id.swn_collapsed_laps, lapText); remoteViewsCollapsed.setViewVisibility(R.id.swn_collapsed_laps, View.VISIBLE); remoteViewsExpanded.setTextViewText(R.id.swn_expanded_laps, lapText); remoteViewsExpanded.setViewVisibility(R.id.swn_expanded_laps, View.VISIBLE); } else { remoteViewsCollapsed.setViewVisibility(R.id.swn_collapsed_laps, View.GONE); remoteViewsExpanded.setViewVisibility(R.id.swn_expanded_laps, View.GONE); } } else { // Left button: reset clock remoteViewsExpanded.setTextViewText( R.id.swn_left_button, getResources().getText(R.string.sw_reset_button)); Intent leftButtonIntent = new Intent(context, StopwatchService.class); leftButtonIntent.setAction(Stopwatches.RESET_AND_LAUNCH_STOPWATCH); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_left_button, PendingIntent.getService(context, 0, leftButtonIntent, 0)); remoteViewsExpanded. setTextViewCompoundDrawablesRelative(R.id.swn_left_button, R.drawable.ic_reset_24dp, 0, 0, 0); // Right button: start clock remoteViewsExpanded.setTextViewText( R.id.swn_right_button, getResources().getText(R.string.sw_start_button)); Intent rightButtonIntent = new Intent(context, StopwatchService.class); rightButtonIntent.setAction(HandleDeskClockApiCalls.ACTION_START_STOPWATCH); remoteViewsExpanded.setOnClickPendingIntent(R.id.swn_right_button, PendingIntent.getService(context, 0, rightButtonIntent, 0)); remoteViewsExpanded. setTextViewCompoundDrawablesRelative(R.id.swn_right_button, R.drawable.ic_start_24dp, 0, 0, 0); // Show stopped string. remoteViewsCollapsed. setTextViewText(R.id.swn_collapsed_laps, getString(R.string.swn_stopped)); remoteViewsCollapsed.setViewVisibility(R.id.swn_collapsed_laps, View.VISIBLE); remoteViewsExpanded. setTextViewText(R.id.swn_expanded_laps, getString(R.string.swn_stopped)); remoteViewsExpanded.setViewVisibility(R.id.swn_expanded_laps, View.VISIBLE); } Intent dismissIntent = new Intent(context, StopwatchService.class); dismissIntent.setAction(HandleDeskClockApiCalls.ACTION_RESET_STOPWATCH); Notification notification = new NotificationCompat.Builder(context) .setAutoCancel(!clockRunning) .setContent(remoteViewsCollapsed) .setOngoing(clockRunning) .setDeleteIntent(PendingIntent.getService(context, 0, dismissIntent, 0)) .setSmallIcon(R.drawable.ic_tab_stopwatch_activated) .setPriority(Notification.PRIORITY_MAX) .setLocalOnly(true) .build(); notification.bigContentView = remoteViewsExpanded; mNotificationManager.notify(NOTIFICATION_ID, notification); } /** Save the notification to be shown when the app is closed. **/ private void saveNotification(long clockTime, boolean clockRunning, int numLaps) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()); SharedPreferences.Editor editor = prefs.edit(); if (clockRunning) { editor.putLong(Stopwatches.NOTIF_CLOCK_BASE, clockTime); editor.putLong(Stopwatches.NOTIF_CLOCK_ELAPSED, -1); editor.putBoolean(Stopwatches.NOTIF_CLOCK_RUNNING, true); } else { editor.putLong(Stopwatches.NOTIF_CLOCK_ELAPSED, clockTime); editor.putLong(Stopwatches.NOTIF_CLOCK_BASE, -1); editor.putBoolean(Stopwatches.NOTIF_CLOCK_RUNNING, false); } editor.putBoolean(Stopwatches.PREF_UPDATE_CIRCLE, false); editor.apply(); } /** Show the most recently saved notification. **/ private boolean showSavedNotification() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()); long clockBaseTime = prefs.getLong(Stopwatches.NOTIF_CLOCK_BASE, -1); long clockElapsedTime = prefs.getLong(Stopwatches.NOTIF_CLOCK_ELAPSED, -1); boolean clockRunning = prefs.getBoolean(Stopwatches.NOTIF_CLOCK_RUNNING, false); int numLaps = prefs.getInt(Stopwatches.PREF_LAP_NUM, -1); if (clockBaseTime == -1) { if (clockElapsedTime == -1) { return false; } else { // We don't have a clock base time, so the clock is stopped. // Use the elapsed time to figure out what time to show. mElapsedTime = clockElapsedTime; clockBaseTime = Utils.getTimeNow() - clockElapsedTime; } } setNotification(clockBaseTime, clockRunning, numLaps); return true; } private void clearSavedNotification() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()); SharedPreferences.Editor editor = prefs.edit(); editor.remove(Stopwatches.NOTIF_CLOCK_BASE); editor.remove(Stopwatches.NOTIF_CLOCK_RUNNING); editor.remove(Stopwatches.NOTIF_CLOCK_ELAPSED); editor.apply(); } private void closeNotificationShade() { Intent intent = new Intent(); intent.setAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); sendBroadcast(intent); } private void readFromSharedPrefs() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()); mStartTime = prefs.getLong(Stopwatches.PREF_START_TIME, 0); mElapsedTime = prefs.getLong(Stopwatches.PREF_ACCUM_TIME, 0); mNumLaps = prefs.getInt(Stopwatches.PREF_LAP_NUM, Stopwatches.STOPWATCH_RESET); } private long[] readLapsFromPrefs() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()); int numLaps = prefs.getInt(Stopwatches.PREF_LAP_NUM, Stopwatches.STOPWATCH_RESET); long[] laps = new long[numLaps]; long prevLapElapsedTime = 0; for (int lap_i = 0; lap_i < numLaps; lap_i++) { String key = Stopwatches.PREF_LAP_TIME + Integer.toString(lap_i + 1); long lap = prefs.getLong(key, 0); if (lap == prevLapElapsedTime && lap_i == numLaps - 1) { lap = mElapsedTime; } laps[numLaps - lap_i - 1] = lap - prevLapElapsedTime; prevLapElapsedTime = lap; } return laps; } private void writeToSharedPrefs(Long startTime, Long lapTimeElapsed, Long elapsedTime, Integer state, boolean updateCircle) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()); SharedPreferences.Editor editor = prefs.edit(); if (startTime != null) { editor.putLong(Stopwatches.PREF_START_TIME, startTime); mStartTime = startTime; } if (lapTimeElapsed != null) { int numLaps = prefs.getInt(Stopwatches.PREF_LAP_NUM, 0); if (numLaps == 0) { mNumLaps++; numLaps++; } editor.putLong(Stopwatches.PREF_LAP_TIME + Integer.toString(numLaps), lapTimeElapsed); numLaps++; editor.putLong(Stopwatches.PREF_LAP_TIME + Integer.toString(numLaps), lapTimeElapsed); editor.putInt(Stopwatches.PREF_LAP_NUM, numLaps); } if (elapsedTime != null) { editor.putLong(Stopwatches.PREF_ACCUM_TIME, elapsedTime); mElapsedTime = elapsedTime; } if (state != null) { if (state == Stopwatches.STOPWATCH_RESET) { editor.putInt(Stopwatches.PREF_STATE, Stopwatches.STOPWATCH_RESET); } else if (state == Stopwatches.STOPWATCH_RUNNING) { editor.putInt(Stopwatches.PREF_STATE, Stopwatches.STOPWATCH_RUNNING); } else if (state == Stopwatches.STOPWATCH_STOPPED) { editor.putInt(Stopwatches.PREF_STATE, Stopwatches.STOPWATCH_STOPPED); } } editor.putBoolean(Stopwatches.PREF_UPDATE_CIRCLE, updateCircle); editor.apply(); } private void writeSharedPrefsStarted(long startTime, boolean updateCircle) { writeToSharedPrefs(startTime, null, null, Stopwatches.STOPWATCH_RUNNING, updateCircle); if (updateCircle) { long time = Utils.getTimeNow(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()); long intervalStartTime = prefs.getLong( Stopwatches.KEY + CircleTimerView.PREF_CTV_INTERVAL_START, -1); if (intervalStartTime != -1) { intervalStartTime = time; SharedPreferences.Editor editor = prefs.edit(); editor.putLong(Stopwatches.KEY + CircleTimerView.PREF_CTV_INTERVAL_START, intervalStartTime); editor.putBoolean(Stopwatches.KEY + CircleTimerView.PREF_CTV_PAUSED, false); editor.apply(); } } } private void writeSharedPrefsLap(long lapTimeElapsed, boolean updateCircle) { writeToSharedPrefs(null, lapTimeElapsed, null, null, updateCircle); if (updateCircle) { long time = Utils.getTimeNow(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()); SharedPreferences.Editor editor = prefs.edit(); long laps[] = readLapsFromPrefs(); int numLaps = laps.length; long lapTime = laps[1]; if (numLaps == 2) { // Have only hit lap once. editor.putLong(Stopwatches.KEY + CircleTimerView.PREF_CTV_INTERVAL, lapTime); } else { editor.putLong(Stopwatches.KEY + CircleTimerView.PREF_CTV_MARKER_TIME, lapTime); } editor.putLong(Stopwatches.KEY + CircleTimerView.PREF_CTV_ACCUM_TIME, 0); if (numLaps < Stopwatches.MAX_LAPS) { editor.putLong(Stopwatches.KEY + CircleTimerView.PREF_CTV_INTERVAL_START, time); editor.putBoolean(Stopwatches.KEY + CircleTimerView.PREF_CTV_PAUSED, false); } else { editor.putLong(Stopwatches.KEY + CircleTimerView.PREF_CTV_INTERVAL_START, -1); } editor.apply(); } } private void writeSharedPrefsStopped(long elapsedTime, boolean updateCircle) { writeToSharedPrefs(null, null, elapsedTime, Stopwatches.STOPWATCH_STOPPED, updateCircle); if (updateCircle) { long time = Utils.getTimeNow(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext()); long accumulatedTime = prefs.getLong( Stopwatches.KEY + CircleTimerView.PREF_CTV_ACCUM_TIME, 0); long intervalStartTime = prefs.getLong( Stopwatches.KEY + CircleTimerView.PREF_CTV_INTERVAL_START, -1); accumulatedTime += time - intervalStartTime; SharedPreferences.Editor editor = prefs.edit(); editor.putLong(Stopwatches.KEY + CircleTimerView.PREF_CTV_ACCUM_TIME, accumulatedTime); editor.putBoolean(Stopwatches.KEY + CircleTimerView.PREF_CTV_PAUSED, true); editor.putLong( Stopwatches.KEY + CircleTimerView.PREF_CTV_CURRENT_INTERVAL, accumulatedTime); editor.apply(); } } private void writeSharedPrefsReset(boolean updateCircle) { writeToSharedPrefs(null, null, null, Stopwatches.STOPWATCH_RESET, updateCircle); } }
package org.tndata.android.compass.model; import android.os.Parcel; import android.support.annotation.NonNull; import com.google.gson.annotations.SerializedName; import java.util.Calendar; import java.util.Date; /** * Model superclass for anything that can be classified as an action. * * @author Ismael Alonso * @version 1.0.0 */ public abstract class Action extends UserContent implements Comparable<Action>{ @SerializedName("trigger") private Trigger mTrigger; @SerializedName("next_reminder") private String mNextReminder; protected Action(){ } public void setTrigger(Trigger trigger){ mTrigger = trigger; } public Trigger getTrigger(){ return mTrigger != null ? mTrigger : new Trigger(); } public boolean hasTrigger(){ return mTrigger != null; } public boolean isTriggerEnabled(){ return mTrigger.isEnabled(); } public String getNextReminder(){ return mNextReminder != null ? mNextReminder : ""; } public Date getNextReminderDate(){ String year = mNextReminder.substring(0, mNextReminder.indexOf("-")); String temp = mNextReminder.substring(mNextReminder.indexOf("-")+1); String month = temp.substring(0, temp.indexOf("-")); temp = temp.substring(temp.indexOf("-")+1); String day = temp.substring(0, temp.indexOf(" ")); String time = mNextReminder.substring(mNextReminder.indexOf(' ')+1); String hour = time.substring(0, time.indexOf(':')); time = time.substring(time.indexOf(':')+1); String minute = time.substring(0, time.indexOf(':')); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, Integer.valueOf(year)); calendar.set(Calendar.MONTH, Integer.valueOf(month)-1); calendar.set(Calendar.DAY_OF_MONTH, Integer.valueOf(day)); calendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(hour)); calendar.set(Calendar.MINUTE, Integer.valueOf(minute)); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTime(); } @Override public int compareTo(@NonNull Action another){ if (mTrigger == null && another.mTrigger == null){ return getTitle().compareTo(another.getTitle()); } else if (mTrigger == null){ return 1; } else if (another.mTrigger == null){ return -1; } else{ int trigger = mTrigger.compareTo(another.mTrigger); if (trigger == 0){ return getTitle().compareTo(another.getTitle()); } else{ return trigger; } } } @Override public void writeToParcel(Parcel dest, int flags){ super.writeToParcel(dest, flags); dest.writeParcelable(getTrigger(), flags); dest.writeString(getNextReminder()); } protected Action(Parcel src){ super(src); mTrigger = src.readParcelable(Trigger.class.getClassLoader()); mNextReminder = src.readString(); } public abstract String getTitle(); }
package com.benvonderhaar.micromapper.test; import static org.junit.Assert.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.benvonderhaar.micromapper.annotation.RequestMethod; import com.benvonderhaar.micromapper.base.MMMethodPayload; import com.benvonderhaar.micromapper.base.MicroMapperRouter; import com.benvonderhaar.micromapper.test.annotation.MMControllerReference; public class MMTestHarness { private MicroMapperRouter router; /** * Provide this with the class of the MicroMapperRouter configured in web.xml * * @param router the class of the MicroMapperRouter configured in web.xml */ public MMTestHarness(Class<? extends MicroMapperRouter> router) { try { this.router = router.newInstance(); this.router.init(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServletException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // TODO add ability to map url to MMURLPattern for more complete mapping engine testing // TODO can this be more cleanly integrated as an extension of Assert? /** * Method to be used to ensure a certain URL map to a certain controller method. * * @param url a URL segment beginning with "/". This should not contain context path (app name) or server name * @param referenceId a string that matches the one provided in a MMControllerReference annotation to the intended * controller method */ public void assertMapping(String url, String referenceId) { System.out.println("about to fail"); // TODO use context path and requestURL more cleanly? HttpServletRequest req = new HttpServletRequestBuilder("/mm-test-harness", "http://localhost:8080/mm-test-harness" + url); HttpServletResponse resp = new HttpServletResponseBuilder(); try { MMMethodPayload methodPayload = router.getIntendedControllerMethod(req, resp, RequestMethod.Verb.GET); System.out.println(methodPayload.getMethod()); if (null == methodPayload.getMethod().getAnnotation(MMControllerReference.class)) { fail("Matched method (" + methodPayload.getMethod().toGenericString() + ") is not annotated with @MMControllerReference"); } assertTrue("Matched method (" + methodPayload.getMethod().toGenericString() + ") referenceId \"" + methodPayload.getMethod().getAnnotation(MMControllerReference.class).referenceId() + "\" does not match provided referenceId \"" + referenceId + "\"", methodPayload.getMethod().getAnnotation(MMControllerReference.class).referenceId().equals(referenceId)); } catch (ServletException e) { // TODO Auto-generated catch block e.printStackTrace(); fail(); } } }
package org.unigram.docvalidator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.unigram.docvalidator.util.DVCharacter; /** * Contain the default symbols and characters. */ public final class DefaultSymbols { /** * Get the specified character or symbol. * @param name name of symbol * @return specified character */ public static DVCharacter get(String name) { if (!SYMBOL_TABLE.containsKey(name)) { LOG.info(name + " is not defined in DefaultSymbols."); return null; } return SYMBOL_TABLE.get(name); } /** * Return all the names of registered characters. * @return all names of characters */ public static Iterator<String> getAllCharacterNames() { return SYMBOL_TABLE.keySet().iterator(); } private static Map<String, DVCharacter> SYMBOL_TABLE = new HashMap<String, DVCharacter>(); static { SYMBOL_TABLE.put("SPACE", new DVCharacter("SPACE", " ", "", false, false)); SYMBOL_TABLE.put("EXCLAMATION_MARK", new DVCharacter("EXCLAMATION_MARK", "!", "", false, false)); SYMBOL_TABLE.put("LEFT_SINGLE_QUOTATION_MARK", new DVCharacter("LEFT_SINGLE_QUOTATION_MARK", "\'", "", false, false)); SYMBOL_TABLE.put("RIGHT_SINGLE_QUOTATION_MARK", new DVCharacter("RIGHT_SINGLE_QUOTATION_MARK", "\'", "", false, false)); SYMBOL_TABLE.put("LEFT_DOUBLE_QUOTATION_MARK", new DVCharacter("LEFT_DOUBLE_QUOTATION_MARK", "\"", "", false, false)); SYMBOL_TABLE.put("RIGHT_DOBULE_QUOTATION_MARK", new DVCharacter("RIGHT_DOBULE_QUOTATION_MARK", "\"", "", false, false)); SYMBOL_TABLE.put("NUMBER_SIGN", new DVCharacter("NUMBER_SIGN", "#", "", false, false)); SYMBOL_TABLE.put("DOLLAR_SIGN", new DVCharacter("DOLLAR_SIGN", "$", "", false, false)); SYMBOL_TABLE.put("PERCENT_SIGN", new DVCharacter("PERCENT_SIGN", "%", "", false, false)); SYMBOL_TABLE.put("QUESTION_MARK", new DVCharacter("QUESTION_MARK", "?", "", false, false)); SYMBOL_TABLE.put("AMPERSAND", new DVCharacter("AMPERSAND", "&", "", false, false)); SYMBOL_TABLE.put("LEFT_PARENTHESIS", new DVCharacter("LEFT_PARENTHESIS", "(", "", false, false)); SYMBOL_TABLE.put("RIGHT_PARENTHESIS", new DVCharacter("RIGHT_PARENTHESIS", ")", "", false, false)); SYMBOL_TABLE.put("ASTERISK", new DVCharacter("ASTERISK", ",", "", false, false)); SYMBOL_TABLE.put("COMMA", new DVCharacter("COMMA", ",", "", false, false)); SYMBOL_TABLE.put("COMMENT", new DVCharacter("COMMENT", "#", "", false, false)); SYMBOL_TABLE.put("FULL_STOP", new DVCharacter("FULL_STOP", ".", "", false, false)); SYMBOL_TABLE.put("PLUSH_SIGN", new DVCharacter("+", ",", "", false, false)); SYMBOL_TABLE.put("HYPHEN_SIGN", new DVCharacter("-", ",", "", false, false)); SYMBOL_TABLE.put("MINUS_SIGN", new DVCharacter("-", ",", "", false, false)); SYMBOL_TABLE.put("SLASH", new DVCharacter("/", ",", "", false, false)); SYMBOL_TABLE.put("COLON", new DVCharacter(":", ",", "", false, false)); SYMBOL_TABLE.put("semicolon", new DVCharacter(";", ",", "", false, false)); SYMBOL_TABLE.put("LESS_THAN_SIGN", new DVCharacter("<", ",", "", false, false)); SYMBOL_TABLE.put("EQUAL_SIGN", new DVCharacter("=", ",", "", false, false)); SYMBOL_TABLE.put("GREATER_THAN_SIGN", new DVCharacter(">", ",", "", false, false)); SYMBOL_TABLE.put("AT_MARK", new DVCharacter("@", ",", "", false, false)); SYMBOL_TABLE.put("LEFT_SQUARE_BRACKET", new DVCharacter("[", ",", "", false, false)); SYMBOL_TABLE.put("RIGHT_SQUARE_BRACKET", new DVCharacter("[", ",", "", false, false)); SYMBOL_TABLE.put("BACKSLASH", new DVCharacter("\\", ",", "", false, false)); SYMBOL_TABLE.put("CIRCUMFLEX_ACCENT", new DVCharacter("^", ",", "", false, false)); SYMBOL_TABLE.put("LOW_LINE", new DVCharacter("_", ",", "", false, false)); SYMBOL_TABLE.put("LEFT_CURLY_BRACKET", new DVCharacter("{", ",", "", false, false)); SYMBOL_TABLE.put("RIGHT_CURLY_BRACKET", new DVCharacter("}", ",", "", false, false)); SYMBOL_TABLE.put("VERTICAL_BAR", new DVCharacter("|", ",", "", false, false)); SYMBOL_TABLE.put("TILDE", new DVCharacter("TILDE", "~", "", false, false)); SYMBOL_TABLE.put("DIGIT_ZERO", new DVCharacter("0", ",", "", false, false)); SYMBOL_TABLE.put("DIGIT_ONE", new DVCharacter("1", ",", "", false, false)); SYMBOL_TABLE.put("DIGIT_TWO", new DVCharacter("2", ",", "", false, false)); SYMBOL_TABLE.put("DIGIT_THREE", new DVCharacter("3", ",", "", false, false)); SYMBOL_TABLE.put("DIGIT_FOUR", new DVCharacter("4", ",", "", false, false)); SYMBOL_TABLE.put("DIGIT_FIVE", new DVCharacter("5", ",", "", false, false)); SYMBOL_TABLE.put("DIGIT_SIX", new DVCharacter("6", ",", "", false, false)); SYMBOL_TABLE.put("DIGIT_SEVEN", new DVCharacter("7", ",", "", false, false)); SYMBOL_TABLE.put("DIGIT_EIGHT", new DVCharacter("8", ",", "", false, false)); SYMBOL_TABLE.put("DIGIT_NINE", new DVCharacter("9", ",", "", false, false)); } private static Logger LOG = LoggerFactory.getLogger(DefaultSymbols.class); private DefaultSymbols() { } }
package com.dexode.adapter; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class RecyclerAdapterCommandManager { public RecyclerAdapterCommandManager(final AdapterWrapper adapterWrapper) { _adapter = adapterWrapper; } public RecyclerAdapterCommandManager(final RecyclerView.Adapter adapter) { _adapter = new AdapterWrapper() { @Override public void notifyItemInserted(final int position) { adapter.notifyItemInserted(position); } @Override public void notifyItemChanged(final int position) { adapter.notifyItemChanged(position); } @Override public void notifyItemRangeInserted(final int position, final int count) { adapter.notifyItemRangeInserted(position, count); } @Override public void notifyItemRemoved(final int position) { adapter.notifyItemRemoved(position); } @Override public void notifyItemRangeRemoved(final int position, final int count) { adapter.notifyItemRangeRemoved(position, count); } @Override public void notifyDataSetChanged() { adapter.notifyDataSetChanged(); } @Override public void notifyItemMoved(final int fromPosition, final int toPosition) { adapter.notifyItemMoved(fromPosition, toPosition); } }; } public void pushBackOne(final int id) { checkStartChanges(); _changes.add(id); } public void pushBackAll(final ArrayList<Integer> ids) { checkStartChanges(); _changes.addAll(ids); } public void insert(int position, final int id) { checkStartChanges(); _changes.add(position, id); } public void remove(int position) { checkStartChanges(); _changes.remove(position); } public void reset() { checkStartChanges(); _changes.clear(); _updates.clear(); } public void update(final int position, final int id) { _updates.add(id); } public void commit() { commit(false); } public void commit(boolean skipProcessing) { skipProcessing = _stable.isEmpty() || skipProcessing; if (skipProcessing) { _stable = _changes; _changes = null; _updates.clear(); _adapter.notifyDataSetChanged(); return; } if (_changes != null) { process(); _stable = _changes; } _changes = null; for (Integer updateId : _updates) { final int position = _stable.indexOf(updateId); if (position > 0) { _adapter.notifyItemChanged(position); } } _updates.clear(); } private void process() { ArrayList<Range> inserted = new ArrayList<>(32); ArrayList<Range> removed = new ArrayList<>(32); ArrayList<Integer> processed = new ArrayList<>(_stable); int offset = 0; //Search for removed for (int i = 0; i < _stable.size(); ++i) { if (_changes.contains(_stable.get(i))) { continue; } processed.remove(i - offset); appendRange(removed, i, -offset); ++offset; } //Search for added for (int i = 0; i < _changes.size(); ++i) { if (_stable.contains(_changes.get(i)) == false) { processed.add(i, _changes.get(i)); appendRange(inserted, i, 0); } } for (Range range : removed) { if (range.start == range.end) { _adapter.notifyItemRemoved(range.start); } else { _adapter.notifyItemRangeRemoved(range.start, range.end - range.start + 1); } } for (Range range : inserted) { if (range.start == range.end) { _adapter.notifyItemInserted(range.start); } else { _adapter.notifyItemRangeInserted(range.start, range.end - range.start + 1); } } //Search for moved for (int i = 0; i < _changes.size(); ++i) { for (int j = i + 1; j < processed.size(); ++j) { if (processed.get(j) == _changes.get(i)) { _adapter.notifyItemMoved(j, i); break; } } } } private void checkStartChanges() { if (_changes == null) { _changes = new ArrayList<>(_stable); } } private void appendRange(ArrayList<Range> rangeArray, int position, final int offset) { if (rangeArray.isEmpty()) { rangeArray.add(new Range(position + offset, position + offset)); } else { final Range range = rangeArray.get(rangeArray.size() - 1); if (range.end + 1 == position) { range.end = position; } else { rangeArray.add(new Range(position + offset, position + offset)); } } } private ArrayList<Integer> _changes = new ArrayList<>(32); private Set<Integer> _updates = new HashSet<>(32); private ArrayList<Integer> _stable = new ArrayList<>(32); private AdapterWrapper _adapter; private static class Range { public Range(final int start, final int end) { this.start = start; this.end = end; } public int start; public int end; } public interface AdapterWrapper { void notifyItemInserted(final int position); void notifyItemChanged(final int position); void notifyItemRangeInserted(final int position, final int count); void notifyItemRemoved(final int position); void notifyItemRangeRemoved(final int position, final int count); void notifyDataSetChanged(); void notifyItemMoved(int fromPosition, int toPosition); } }
package org.spine3.sample; import com.google.common.base.Function; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spine3.base.CommandRequest; import org.spine3.base.UserId; import org.spine3.eventbus.EventBus; import org.spine3.sample.order.OrderId; import org.spine3.sample.order.OrderRepository; import org.spine3.server.Engine; import org.spine3.server.storage.StorageFactory; import org.spine3.util.Users; import javax.annotation.Nullable; import java.util.List; import static com.google.common.base.Strings.isNullOrEmpty; import static org.spine3.util.Identifiers.IdConverterRegistry; import static org.spine3.util.Identifiers.NULL_ID_OR_FIELD; /** * Framework usage sample. * * @author Mikhail Mikhaylov * @author Alexander Litus */ public class Sample { private final StorageFactory storageFactory; private final EventLogger eventLogger = new EventLogger(); /** * Creates a new sample with the specified storage factory. * @param storageFactory factory used to create and set up storages. */ public Sample(StorageFactory storageFactory) { this.storageFactory = storageFactory; } /** * The entry point of the sample. * To change the storage implementation, change {@link Sample#getStorageFactory()} method implementation. */ public static void main(String[] args) { final StorageFactory factory = getStorageFactory(); final Sample sample = new Sample(factory); sample.execute(); } /** * Executes the sample: generates some command requests and then the {@link Engine} processes them. */ protected void execute() { setUp(); // Generate test requests final List<CommandRequest> requests = generateRequests(); // Process requests for (CommandRequest request : requests) { Engine.getInstance().process(request); } log().info("All the requests were handled."); tearDown(); } /** * Sets up the storage, starts the engine, registers repositories, handlers etc. */ public void setUp() { // Set up the storage storageFactory.setUp(); // Start the engine Engine.start(storageFactory); // Register repository with the engine. This will register it in the CommandDispatcher too. Engine.getInstance().register(new OrderRepository()); // Register event handlers EventBus.getInstance().register(eventLogger); // Register id converters IdConverterRegistry.getInstance().register(OrderId.class, new OrderIdToStringConverter()); } /** * Tear down storages, unregister event handlers and stop the engine. */ public void tearDown() { storageFactory.tearDown(); // Unregister event handlers EventBus.getInstance().unregister(eventLogger); // Stop the engine Engine.stop(); } //TODO:2015-09-23:alexander.yevsyukov: Rename and extend sample data to better reflect the problem domain. // See Amazon screens for correct naming of domain things. /** * Creates several dozens of requests. */ public static List<CommandRequest> generateRequests() { final List<CommandRequest> result = Lists.newArrayList(); for (int i = 0; i < 10; i++) { final OrderId orderId = OrderId.newBuilder().setValue(String.valueOf(i)).build(); final UserId userId = Users.createId("user_" + i); final CommandRequest createOrder = Requests.createOrder(userId, orderId); final CommandRequest addOrderLine = Requests.addOrderLine(userId, orderId); final CommandRequest payForOrder = Requests.payForOrder(userId, orderId); result.add(createOrder); result.add(addOrderLine); result.add(payForOrder); } return result; } /** * Retrieves the storage factory instance. * Change this method implementation if needed. * * @return the {@link StorageFactory} implementation. */ public static StorageFactory getStorageFactory() { return org.spine3.server.storage.memory.InMemoryStorageFactory.getInstance(); /** * To run the sample on the filesystem storage, uncomment the following line (and comment out return statement above). */ // return org.spine3.server.storage.filesystem.FileSystemStorageFactory.newInstance(Sample.class); // return org.spine3.server.storage.datastore.LocalDatastoreStorageFactory.getDefaultInstance(); } private static class OrderIdToStringConverter implements Function<OrderId, String> { @Override public String apply(@Nullable OrderId orderId) { if (orderId == null) { return NULL_ID_OR_FIELD; } final String value = orderId.getValue(); if (isNullOrEmpty(value) || value.trim().isEmpty()) { return NULL_ID_OR_FIELD; } return value; } } private static Logger log() { return LogSingleton.INSTANCE.value; } private enum LogSingleton { INSTANCE; @SuppressWarnings("NonSerializableFieldInSerializableClass") private final Logger value = LoggerFactory.getLogger(Sample.class); } }
package pcl.OpenFM.TileEntity; import cpw.mods.fml.common.Optional; import li.cil.oc.api.Network; import li.cil.oc.api.network.Environment; import li.cil.oc.api.network.Message; import li.cil.oc.api.network.Node; import li.cil.oc.api.network.Visibility; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; @Optional.InterfaceList(value={ @Optional.Interface(iface = "li.cil.oc.api.network.Environment", modid = "OpenComputers") }) public class TileEntitySpeaker extends TileEntity implements Environment { protected Node node; @Optional.Method(modid = "OpenComputers") @Override public Node node() { return node = Network.newNode(this, Visibility.Network).create(); } @Override public void onChunkUnload() { super.onChunkUnload(); if (node != null) node.remove(); } @Override public void invalidate() { super.invalidate(); if (node != null) node.remove(); } @Optional.Method(modid = "OpenComputers") @Override public void onConnect(final Node node) { // TODO Auto-generated method stub } @Optional.Method(modid = "OpenComputers") @Override public void onMessage(Message message) { // TODO Auto-generated method stub } @Optional.Method(modid = "OpenComputers") @Override public void onDisconnect(Node node) { // TODO Auto-generated method stub } @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); if (node != null && node.host() == this) { node.load(nbt.getCompoundTag("oc:node")); } } @Override public void writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); if (node != null && node.host() == this) { final NBTTagCompound nodeNbt = new NBTTagCompound(); node.save(nodeNbt); nbt.setTag("oc:node", nodeNbt); } } @Override public void updateEntity() { super.updateEntity(); if (node != null && node.network() == null) { Network.joinOrCreateNetwork(this); } } }
package pete.metrics.adaptability; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import pete.executables.AnalysisException; public final class BpmnInspector { private static final String BPMN_NAMESPACE = "http: String isCorrectNamespace(Document dom) { Element root = null; try { root = dom.getDocumentElement(); } catch (NullPointerException e) { return "false"; } if (BPMN_NAMESPACE.equals(root.getNamespaceURI())) { return "true"; } else { return "false"; } } String isExecutable(Node process) { NamedNodeMap attributes = process.getAttributes(); for (int j = 0; j < attributes.getLength(); j++) { Node attribute = attributes.item(j); if ("isExecutable".equals(attribute.getLocalName()) && "true".equals(attribute.getNodeValue())) { return "true"; } } return "false"; } int getNumberOfChildren(Node node) { if (node.getLocalName() == null) { return 0; } NodeList children = node.getChildNodes(); int result = 1; if (children == null) { // do noting, result is zero } else { for (int i = 0; i < children.getLength(); i++) { result += getNumberOfChildren(children.item(i)); } } return result; } public Node getProcess(Document dom) throws AnalysisException { NodeList nodes = getChildrenOfDefinitions(dom); if (nodes == null) { throw new AnalysisException( "File cannot be analyzed: no definitions element or definitions element is empty"); } for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if ("process".equals(node.getLocalName())) { return node; } } throw new AnalysisException( "File cannot be analyzed: no process element found"); } private NodeList getChildrenOfDefinitions(Document dom) { NodeList nodes = null; try { nodes = dom.getChildNodes(); } catch (NullPointerException e) { return null; } for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if ("definitions".equals(node.getLocalName())) { return node.getChildNodes(); } } return null; } }
package com.signicat.hystrix.servlet; import com.netflix.hystrix.Hystrix; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandProperties; import com.netflix.hystrix.HystrixThreadPoolProperties; import com.netflix.hystrix.contrib.servopublisher.HystrixServoMetricsPublisher; import com.netflix.hystrix.exception.HystrixRuntimeException; import com.netflix.hystrix.strategy.HystrixPlugins; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.TimeUnit; import javax.servlet.AsyncContext; import javax.servlet.AsyncEvent; import javax.servlet.AsyncListener; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import rx.Observable; import rx.Observer; /** * Wrapper class for executing any {@link javax.servlet.http.HttpServlet} within a Hystrix thread pool. Subclass this, * create a no-arg constructor in the subclass, and pass the HttpServlet to wrap to the superclass. Then configure the * new subclass to run in web.xml, instead of the old (wrapped) servlet. If you want to control which thread pool a * request ends up executing within, make the wrapped servlet implement * {@link com.signicat.hystrix.servlet.HystrixAwareServlet#getCommandGroupKey(javax.servlet.http.HttpServletRequest)}. * * @author Einar Rosenvinge &lt;einros@signicat.com&gt; */ @WebServlet(asyncSupported = true) public class AsyncWrapperServlet extends HttpServlet { public static final String DEFAULT_COMMAND_GROUP_KEY = "default"; private static final Logger log = LoggerFactory.getLogger(AsyncWrapperServlet.class); public static final long DEFAULT_TIMEOUT = 50000L; private static final int HYSTRIX_ADDED_TIMEOUT_DELAY = 10000; //servlet cntnr will time things out bf Hystrix does public static final int DEFAULT_CORE_POOL_SIZE = 100; private final HttpServlet wrappedServlet; private final long timeoutMillis; private final int corePoolSize; static { try { HystrixPlugins.getInstance().registerMetricsPublisher(HystrixServoMetricsPublisher.getInstance()); } catch (IllegalStateException ignored) { } } public AsyncWrapperServlet(final HttpServlet wrappedServlet) { this(wrappedServlet, DEFAULT_TIMEOUT, DEFAULT_CORE_POOL_SIZE); } public AsyncWrapperServlet(final HttpServlet wrappedServlet, final long timeoutMillis, final int corePoolSize) { this.wrappedServlet = wrappedServlet; this.timeoutMillis = timeoutMillis; this.corePoolSize = corePoolSize; } @Override public void init() throws ServletException { super.init(); wrappedServlet.init(); } @Override public void init(ServletConfig config) throws ServletException { super.init(config); wrappedServlet.init(config); } @Override public void destroy() { super.destroy(); Hystrix.reset(5, TimeUnit.SECONDS); wrappedServlet.destroy(); } @Override public void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { AsyncContext asyncContext = req.startAsync(); asyncContext.setTimeout(timeoutMillis); TimeoutAwareHttpServletRequest timeoutAwareHttpServletReq = new TimeoutAwareHttpServletRequest(req); TimeoutAwareHttpServletResponse timeoutAwareHttpServletResp = new TimeoutAwareHttpServletResponse(resp); asyncContext.addListener(new BaseServletAsyncListener(timeoutAwareHttpServletReq, timeoutAwareHttpServletResp)); Runnable runBefore = onBeforeCommandSubmit(); Runnable runAfter = onAfterCommandExecute(); final String key = getCommandGroupKey(wrappedServlet, req); log.info("Scheduling Hystrix command with key '" + key + "'"); //double thread pool size for pool with magic name 'default' final int size = DEFAULT_COMMAND_GROUP_KEY.equals(key) ? (corePoolSize * 2) : corePoolSize; final int queueSize = corePoolSize * 4; final int queueRejectionSize = corePoolSize * 2; BaseServletCommand command = new BaseServletCommand( HystrixCommand.Setter .withGroupKey( HystrixCommandGroupKey.Factory.asKey(key)) .andCommandKey(HystrixCommandKey.Factory.asKey(key)) .andCommandPropertiesDefaults( HystrixCommandProperties.Setter() .withExecutionIsolationThreadTimeoutInMilliseconds( (int) timeoutMillis + HYSTRIX_ADDED_TIMEOUT_DELAY) .withCircuitBreakerEnabled(false) .withExecutionIsolationStrategy( HystrixCommandProperties.ExecutionIsolationStrategy.THREAD) .withFallbackEnabled(false)) .andThreadPoolPropertiesDefaults( HystrixThreadPoolProperties.Setter() .withCoreSize(size) .withMaxQueueSize(queueSize) .withQueueSizeRejectionThreshold(queueRejectionSize)), timeoutAwareHttpServletReq, timeoutAwareHttpServletResp, runBefore, runAfter); Observable<Object> observable = command.observe(); observable.subscribe(new BaseServletObserver(asyncContext)); onAfterCommandSubmit(); } protected String getCommandGroupKey(HttpServlet srv, HttpServletRequest req) { if (srv instanceof HystrixAwareServlet) { return ((HystrixAwareServlet) srv).getCommandGroupKey(req); } return DEFAULT_COMMAND_GROUP_KEY; } /** * Note that this is called from * {@link com.signicat.hystrix.servlet.AsyncWrapperServlet#service(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse)}, i.e. by the servlet container thread. The Runnable returned is called * by the Hystrix thread (in a try-catch block, with logging), at the beginning of * {@link com.netflix.hystrix.HystrixCommand#run()}. */ protected Runnable onBeforeCommandSubmit() { return new Runnable() { @Override public void run() { } }; } /** * Useful? for subclasses, but really mostly for testing. Note that this is called from {@link * com.signicat.hystrix.servlet.AsyncWrapperServlet#service(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse)}, i.e. by the servlet container thread. */ protected void onAfterCommandSubmit() { } /** * Note that this is called from * {@link com.signicat.hystrix.servlet.AsyncWrapperServlet#service(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse)}, i.e. by the servlet container thread. The Runnable returned is called * by the Hystrix thread (in a try-catch block, with logging, inside a finally block), at the end of {@link * com.netflix.hystrix.HystrixCommand#run()}. */ protected Runnable onAfterCommandExecute() { return new Runnable() { @Override public void run() { } }; } /** * Override this method if you want to do some extra work when {@link javax.servlet.AsyncContext#complete()} has * been called. * * @param asyncEvent the AsyncEvent indicating that an asynchronous operation has been completed * @throws IOException if an I/O related error has occurred during the processing of the given AsyncEvent */ protected void onServletCompleted(AsyncEvent asyncEvent) throws IOException { } /** * Override this method if you want to do some extra work when the servlet container has timed out the request. It * is HIGHLY recommended to call the implementation in this superclass as well, to be certain that {@link * javax.servlet.AsyncContext#complete()} is called. Failure to do so will result in strange errors. * * @param asyncEvent the AsyncEvent indicating that an asynchronous operation has timed out * @throws IOException if an I/O related error has occurred during the processing of the given AsyncEvent */ @SuppressWarnings({"EmptyCatchBlock", "ThrowableResultOfMethodCallIgnored"}) protected void onServletTimeout(AsyncEvent asyncEvent) throws IOException { try { final String msg = "Timeout from async listener"; log.debug(msg, asyncEvent.getThrowable()); ((HttpServletResponse) asyncEvent.getAsyncContext().getResponse()) .sendError(HttpServletResponse.SC_GATEWAY_TIMEOUT, msg); } catch (Exception e) { } finally { try { asyncEvent.getAsyncContext().complete(); } catch (Exception e) { } } } /** * Override this method if you want to do some extra work when the servlet container has caught an exception from * {@link com.signicat.hystrix.servlet.AsyncWrapperServlet#service(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse)}. It is HIGHLY recommended to call the implementation in this superclass * as well, to be certain that {@link javax.servlet.AsyncContext#complete()} is called. Failure to do so will result * in strange errors. * * @param asyncEvent the AsyncEvent indicating that an asynchronous operation has failed to complete * @throws IOException if an I/O related error has occurred during the processing of the given AsyncEvent */ @SuppressWarnings({"EmptyCatchBlock", "ThrowableResultOfMethodCallIgnored"}) protected void onServletError(AsyncEvent asyncEvent) throws IOException { try { final String msg = "Error from async listener"; log.warn(msg, asyncEvent.getThrowable()); ((HttpServletResponse) asyncEvent.getAsyncContext().getResponse()) .sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); } catch (Exception e) { } finally { try { asyncEvent.getAsyncContext().complete(); } catch (Exception e) { } } } /** * Override this method if you want to do some extra work when Hystrix is notified that the processing of the * request/response is done. It is HIGHLY recommended to call the implementation in this superclass as well, to be * certain that {@link javax.servlet.AsyncContext#complete()} is called. Failure to do so will result in strange * errors. * * @param asyncContext The AsyncContext to complete. */ @SuppressWarnings("EmptyCatchBlock") protected void onHystrixCompleted(AsyncContext asyncContext) { try { asyncContext.complete(); } catch (Exception e) { } } /** * Override this method if you want to do some extra work when Hystrix has caught an exception from {@link * com.netflix.hystrix.HystrixCommand#run()}, or if the operation has timed out. It is HIGHLY recommended to call * the implementation in this superclass as well, to be certain that {@link javax.servlet.AsyncContext#complete()} * is called. Failure to do so will result in strange errors. * * @param asyncContext The AsyncContext to complete. * @param throwable The Throwable caught. */ @SuppressWarnings("EmptyCatchBlock") protected void onHystrixError(AsyncContext asyncContext, Throwable throwable) { try { final HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse(); final String msg = "Error from async observer"; if (throwable instanceof HystrixRuntimeException) { HystrixRuntimeException hre = (HystrixRuntimeException) throwable; switch (hre.getFailureType()) { case TIMEOUT: log.debug(msg, throwable); response.sendError(HttpServletResponse.SC_GATEWAY_TIMEOUT, msg); break; case COMMAND_EXCEPTION: log.warn(msg, throwable); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); break; default: log.debug(msg, throwable); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, msg); break; } } else { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); } } catch (Exception e) { } try { asyncContext.complete(); } catch (Exception e) { } } /** * Override this method if you want to do some extra work when Hystrix is notified that the processing of the * request/response is done. It is HIGHLY recommended to call the implementation in this superclass as well, to be * certain that {@link javax.servlet.AsyncContext#complete()} is called. Failure to do so will result in strange * errors. * * @param asyncContext The AsyncContext to complete. * @param o In our implementation, a dummy object that is not useful in any way. */ @SuppressWarnings("EmptyCatchBlock") protected void onHystrixNext(AsyncContext asyncContext, Object o) { try { asyncContext.complete(); } catch (Exception e) { } } private class BaseServletAsyncListener implements AsyncListener { private final TimeoutAwareHttpServletRequest timeoutAwareHttpServletReq; private final TimeoutAwareHttpServletResponse timeoutAwareHttpServletResp; private BaseServletAsyncListener(TimeoutAwareHttpServletRequest timeoutAwareHttpServletReq, TimeoutAwareHttpServletResponse timeoutAwareHttpServletResp) { this.timeoutAwareHttpServletReq = timeoutAwareHttpServletReq; this.timeoutAwareHttpServletResp = timeoutAwareHttpServletResp; } @Override public void onComplete(AsyncEvent asyncEvent) throws IOException { timeoutAwareHttpServletReq.resetWrapped(); timeoutAwareHttpServletResp.resetWrapped(); onServletCompleted(asyncEvent); } @Override public void onTimeout(AsyncEvent asyncEvent) throws IOException { timeoutAwareHttpServletReq.resetWrapped(); timeoutAwareHttpServletResp.resetWrapped(); onServletTimeout(asyncEvent); } @Override public void onError(AsyncEvent asyncEvent) throws IOException { timeoutAwareHttpServletReq.resetWrapped(); timeoutAwareHttpServletResp.resetWrapped(); onServletError(asyncEvent); } @Override public void onStartAsync(AsyncEvent asyncEvent) throws IOException { } } private class BaseServletCommand extends HystrixCommand<Object> { private final TimeoutAwareHttpServletRequest timeoutAwareHttpServletReq; private final TimeoutAwareHttpServletResponse timeoutAwareHttpServletResp; private final Runnable runBefore; private final Runnable runAfter; private BaseServletCommand(Setter setter, TimeoutAwareHttpServletRequest timeoutAwareHttpServletReq, TimeoutAwareHttpServletResponse timeoutAwareHttpServletResp, Runnable runBefore, Runnable runAfter) { super(setter); this.timeoutAwareHttpServletReq = timeoutAwareHttpServletReq; this.timeoutAwareHttpServletResp = timeoutAwareHttpServletResp; this.runBefore = runBefore; this.runAfter = runAfter; } @Override public Object run() throws Exception { try { runBefore.run(); } catch (Exception e) { log.info("Exception in Hystrix pre-execute hook", e); } try { wrappedServlet.service(timeoutAwareHttpServletReq, timeoutAwareHttpServletResp); } finally { try { runAfter.run(); } catch (Exception e) { log.info("Exception in Hystrix post-execute hook", e); } } return new Object(); } } private class BaseServletObserver implements Observer<Object> { private final AsyncContext asyncContext; private BaseServletObserver(AsyncContext asyncContext) { this.asyncContext = asyncContext; } @Override public void onCompleted() { onHystrixCompleted(asyncContext); } @Override public void onError(Throwable throwable) { onHystrixError(asyncContext, throwable); } @Override public void onNext(Object o) { onHystrixNext(asyncContext, o); } } }
package com.kyokomi.pazuruquest.scene; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; import org.andengine.engine.handler.timer.ITimerCallback; import org.andengine.engine.handler.timer.TimerHandler; import org.andengine.entity.IEntity; import org.andengine.entity.modifier.DelayModifier; import org.andengine.entity.modifier.IEntityModifier; import org.andengine.entity.modifier.AlphaModifier; import org.andengine.entity.modifier.MoveModifier; import org.andengine.entity.modifier.ParallelEntityModifier; import org.andengine.entity.modifier.ScaleModifier; import org.andengine.entity.modifier.SequenceEntityModifier; import org.andengine.entity.primitive.Rectangle; import org.andengine.entity.scene.IOnSceneTouchListener; import org.andengine.entity.scene.Scene; import org.andengine.entity.sprite.Sprite; import org.andengine.input.touch.TouchEvent; import org.andengine.util.color.Color; import org.andengine.util.modifier.IModifier; import com.kyokomi.core.activity.MultiSceneActivity; import com.kyokomi.core.scene.KeyListenScene; import com.kyokomi.pazuruquest.layer.PanelLayer; import android.graphics.Point; import android.util.Log; import android.view.KeyEvent; public class MjPazuruQuestScene extends KeyListenScene implements IOnSceneTouchListener{ private static final String TAG = "MjPazuruQuestScene"; public MjPazuruQuestScene(MultiSceneActivity baseActivity) { super(baseActivity); init(); // FPS initFps(getWindowWidth() - 100, getWindowHeight() - 20, getFont()); } @Override public void init() { viewWillAppear(); // Scene setOnSceneTouchListener(this); } @Override public void prepareSoundAndMusic() { } @Override public boolean dispatchKeyEvent(KeyEvent e) { return false; } @Override public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) { boolean isEvent = false; switch (pSceneTouchEvent.getAction()) { case TouchEvent.ACTION_DOWN: touchesBegan(pScene, pSceneTouchEvent); isEvent = true; break; case TouchEvent.ACTION_MOVE: touchesMoved(pScene, pSceneTouchEvent); isEvent = true; break; case TouchEvent.ACTION_UP: touchesEnded(pScene, pSceneTouchEvent); isEvent = true; break; default: Log.d(TAG, "onSceneTouchEvent No Action " + pSceneTouchEvent.getAction()); break; } return isEvent; } private Rectangle mTouchBreakLayeer; private Rectangle mBackgroundLayer; private Sprite mBackgroundSprite; private Sprite mKanCutIn; private static final int PANEL_SIZE = 78; private static final int PANEL_BASE_X = 10; private static final int PANEL_BASE_Y = 5; private static final int PANEL_COUNT_X = 6; private static final int PANEL_COUNT_Y = 6; private int mPanelBaseX; private int mPanelBaseY; private void initPanelBase(int pX, int pY) { this.mPanelBaseX = pX; this.mPanelBaseY = pY; } private int getWindowToPanelX(int panelX) { return mPanelBaseX + (PANEL_SIZE + 1) * (panelX); } private int getWindowToPanelY(int panelY) { return mPanelBaseY + (PANEL_SIZE + 1) * (panelY); } private int getPanelToWindowX(int x) { int panelX = (x - mPanelBaseX) / (PANEL_SIZE + 1); if (panelX >= PANEL_COUNT_X) { panelX = PANEL_COUNT_X - 1; } else if (panelX < 0) { panelX = 0; } return panelX; } private int getPanelToWindowY(int y) { int panelY = (y - mPanelBaseY) / (PANEL_SIZE + 1); if (panelY >= PANEL_COUNT_Y) { panelY = PANEL_COUNT_Y - 1; } else if (panelY < 0) { panelY = 0; } return panelY; } enum PlayState { PlayStateChoose, PlayStateChange, }; private PlayState state; private boolean isFinished; // private NSMutableArray *panelLayers; // private int chainCount; // private int score; // private int timeCount; private PanelLayer[][] panelMap; private final Random rand = new Random(new Date().getTime()); private void viewWillAppear() { mBackgroundSprite = getResourceSprite("mj_bk.jpg"); placeToCenter(mBackgroundSprite); attachChild(mBackgroundSprite); mKanCutIn = getResourceSprite("cutin/cut_in_kan.jpg"); placeToCenter(mKanCutIn); mKanCutIn.setZIndex(100); mKanCutIn.setVisible(false); attachChild(mKanCutIn); panelMap = new PanelLayer[PANEL_COUNT_X][PANEL_COUNT_Y]; initPanelBase(0, 0); mBackgroundLayer = new Rectangle(0, 0, PANEL_COUNT_X * (PANEL_SIZE), PANEL_COUNT_Y * (PANEL_SIZE), getBaseActivity().getVertexBufferObjectManager()); mBackgroundLayer.setColor(Color.TRANSPARENT); mBackgroundLayer.setPosition(PANEL_BASE_X, PANEL_BASE_Y); mBackgroundLayer.setZIndex(0); attachChild(mBackgroundLayer); mTouchBreakLayeer = new Rectangle(0, 0, PANEL_COUNT_X * (PANEL_SIZE + 1) - 1 + PANEL_BASE_X + 20, PANEL_COUNT_Y * (PANEL_SIZE + 1) - 1 + PANEL_BASE_Y + 20, getBaseActivity().getVertexBufferObjectManager()); mTouchBreakLayeer.setColor(Color.BLACK); mTouchBreakLayeer.setPosition(-10, -10); mTouchBreakLayeer.setAlpha(0.5f); mTouchBreakLayeer.setZIndex(10); chegeState(PlayState.PlayStateChoose); isFinished = false; // score = 0; // timeCount = 60; // YX6 for (int y = 0; y < PANEL_COUNT_Y; y++) { for (int x = 0; x < PANEL_COUNT_X; x++) { // backViewlayer PanelLayer layer = createPanelLayer(x, y, getWindowToPanelX(x), getWindowToPanelY(y)); mBackgroundLayer.attachChild(layer); panelMap[x][y] = layer; } } mBackgroundLayer.sortChildren(); sortChildren(); // TODO: // [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerProc:) userInfo:nil repeats:YES]; } public enum MjPanel { P1(1, 1, 1,"p_ps1_1.png"), P2(2, 1, 2, "p_ps2_1.png"), P3(3, 1, 3, "p_ps3_1.png"), P4(4, 1, 4, "p_ps4_1.png"), P5(5, 1, 5, "p_ps5_1.png"), P6(6, 1, 6, "p_ps6_1.png"), P7(7, 1, 7, "p_ps7_1.png"), P8(8, 1, 8, "p_ps8_1.png"), P9(9, 1, 9, "p_ps9_1.png"), M1(10, 2, 1, "p_ms1_1.png"), M2(11, 2, 2, "p_ms2_1.png"), M3(12, 2, 3, "p_ms3_1.png"), M4(13, 2, 4, "p_ms4_1.png"), M5(14, 2, 5, "p_ms5_1.png"), M6(15, 2, 6, "p_ms6_1.png"), M7(16, 2, 7, "p_ms7_1.png"), M8(17, 2, 8, "p_ms8_1.png"), M9(18, 2, 9, "p_ms9_1.png"), S1(19, 3, 1, "p_ss1_1.png"), S2(20, 3, 2, "p_ss2_1.png"), S3(21, 3, 3, "p_ss3_1.png"), S4(22, 3, 4, "p_ss4_1.png"), S5(23, 3, 5, "p_ss5_1.png"), S6(24, 3, 6, "p_ss6_1.png"), S7(25, 3, 7, "p_ss7_1.png"), S8(26, 3, 8, "p_ss8_1.png"), S9(27, 3, 9, "p_ss9_1.png"), J1(28, 4, 1, "p_ji_e_1.png"), J2(29, 4, 2, "p_ji_s_1.png"), J3(30, 4, 3, "p_ji_w_1.png"), J4(31, 4, 4, "p_ji_n_1.png"), J5(32, 4, 5, "p_no_1.png"), J6(33, 4, 6, "p_ji_h_1.png"), J7(34, 4, 7, "p_ji_c_1.png"), ; private Integer value; private Integer type; private Integer typeValue; private String fileName; private MjPanel(Integer value, Integer type, Integer typeValue, String fileName) { this.value = value; this.type = type; this.typeValue = typeValue; this.fileName = fileName; } public Integer getValue() { return value; } public String getFileName() { return fileName; } public Integer getType() { return type; } public Integer getTypeValue() { return typeValue; } public static MjPanel get(Integer value) { MjPanel[] values = values(); for (MjPanel type : values) { if (type.getValue() == value) { return type; } } throw new RuntimeException("find not tag type. value =" + value); } } private PanelLayer createPanelLayer(int panelX, int panelY, float x, float y) { PanelLayer layer = new PanelLayer(panelX, panelY, 0, 0, PANEL_SIZE, PANEL_SIZE, getBaseActivity().getVertexBufferObjectManager()); layer.setColor(Color.WHITE); layer.setAlpha(0.5f); layer.setPosition(x, y); int dice = rand.nextInt(MjPanel.values().length - 1); dice += 1; MjPanel mjPanel = MjPanel.get(dice); String layerName = mjPanel.getFileName(); // Log.d(TAG, layerName); Sprite imageSprite = getResourceSprite("mjpanel/" + layerName); imageSprite.setSize(PANEL_SIZE, PANEL_SIZE); layer.attachChild(imageSprite); layer.setName(layerName); layer.setImage(imageSprite); layer.setMjPanel(mjPanel); layer.setPanelPoint(new Point(panelX, panelY)); return layer; } private PanelLayer panelHitTest(float pX, float pY) { if (mBackgroundLayer.contains(pX, pY)) { int count = mBackgroundLayer.getChildCount(); for (int i = 0; i < count; i++) { if (mBackgroundLayer.getChildByIndex(i) instanceof Rectangle) { PanelLayer sprite = (PanelLayer) mBackgroundLayer.getChildByIndex(i); if (sprite.contains(pX, pY)) { return sprite; } } } } return null; } private PanelLayer mMovingLayer1; private void touchesBegan(Scene pScene, TouchEvent pSceneTouchEvent) { if (isFinished || state != PlayState.PlayStateChoose) { return ; } float x = pSceneTouchEvent.getX(); float y = pSceneTouchEvent.getY(); // hitTest PanelLayer layer = panelHitTest(x, y); if (layer == null || (mMovingLayer1 != null && layer.equals(mMovingLayer1))) { return ; } if (mMovingLayer1 == null) { mMovingLayer1 = layer; mMovingLayer1.setAlpha(0.5f); } } /** * . * touchesBegan1 */ private void touchesMoved(Scene pScene, TouchEvent pSceneTouchEvent) { if (isFinished || state != PlayState.PlayStateChoose) { return ; } if (mMovingLayer1 == null) { return; } float x = pSceneTouchEvent.getX(); float y = pSceneTouchEvent.getY(); // float logX = getPanelToWindowX((int)x); // float logY = getPanelToWindowY((int)y); // Log.d(TAG, "move[" + logX + "][" + logY + "]"); if (!mBackgroundLayer.contains(x, y)) { return; } if (mMovingLayer1 != null) { mMovingLayer1.setPosition(x - mMovingLayer1.getWidth() / 2, y - mMovingLayer1.getHeight() /2); int beforePanelX = mMovingLayer1.getPanelPoint().x; int beforePanelY = mMovingLayer1.getPanelPoint().y; float beforeX = getWindowToPanelX(beforePanelX); float beforeY = getWindowToPanelY(beforePanelY); int panelX = getPanelToWindowX((int)x); int panelY = getPanelToWindowY((int)y); if (Math.abs(beforePanelX - panelX) == 0 && Math.abs(beforePanelY - panelY) == 0) { return; } if (beforePanelX != panelX || beforePanelY != panelY) { if ((Math.abs(beforePanelX - panelX) == 1 && Math.abs(beforePanelY - panelY) == 0) || (Math.abs(beforePanelX - panelX) == 1 && Math.abs(beforePanelY - panelY) == 1) || (Math.abs(beforePanelX - panelX) == 0 && Math.abs(beforePanelY - panelY) == 1 )) { PanelLayer temp = panelMap[panelX][panelY]; if (temp != null) { mMovingLayer1.setPanelPoint(new Point(panelX, panelY)); panelMap[panelX][panelY] = mMovingLayer1; temp.setPanelPoint(new Point(beforePanelX, beforePanelY)); panelMap[beforePanelX][beforePanelY] = temp; animationMovePanel(temp, beforeX, beforeY); } } } } } private void touchesEnded(Scene pScene, TouchEvent pSceneTouchEvent) { Log.d(TAG,"touchesEnded"); if (state != PlayState.PlayStateChange) { Log.d(TAG, " " + state); registerUpdateHandler(new TimerHandler(0.01f, new ITimerCallback() { @Override public void onTimePassed(TimerHandler pTimerHandler) { if(mMovingLayer1 != null) { chegeState(PlayState.PlayStateChange); int beforePanelX = mMovingLayer1.getPanelPoint().x; int beforePanelY = mMovingLayer1.getPanelPoint().y; float beforeX = getWindowToPanelX(beforePanelX); float beforeY = getWindowToPanelY(beforePanelY); mMovingLayer1.setPosition(beforeX, beforeY); mMovingLayer1.setAlpha(1.0f); mMovingLayer1.setScale(1.0f); mMovingLayer1 = null; finishChange(); } } })); } } private void animationMovePanel(final PanelLayer pLayer, float moveX, float moveY) { int addMoveX = 0; int addMoveY = 0; if ((pLayer.getX() - moveX) == 0) { if ((pLayer.getY() - moveY) > 0) { addMoveX = (PANEL_SIZE / 2) * -1; addMoveY = (PANEL_SIZE / 2) * -1; } else { addMoveX = (PANEL_SIZE / 2); addMoveY = (PANEL_SIZE / 2); } } else if ((pLayer.getY() - moveY) == 0) { if ((pLayer.getX() - moveX) > 0) { addMoveX = (PANEL_SIZE / 2) * -1; addMoveY = (PANEL_SIZE / 2); } else { addMoveX = (PANEL_SIZE / 2); addMoveY = (PANEL_SIZE / 2) * -1; } } else { if ( (pLayer.getX() - moveX) > 0 && (pLayer.getY() - moveY) > 0) { addMoveX = (PANEL_SIZE / 2); addMoveY = (PANEL_SIZE / 2); } else if ((pLayer.getX() - moveX) > 0 && (pLayer.getY() - moveY) < 0) { addMoveX = (PANEL_SIZE / 2); addMoveY = (PANEL_SIZE / 2) * -1; } else if ((pLayer.getX() - moveX) < 0 && (pLayer.getY() - moveY) < 0) { addMoveX = (PANEL_SIZE / 2) * -1; addMoveY = (PANEL_SIZE / 2) * -1; } else if ((pLayer.getX() - moveX) < 0 && (pLayer.getY() - moveY) > 0) { addMoveX = (PANEL_SIZE / 2) * -1; addMoveY = (PANEL_SIZE / 2); } else { Log.e(TAG, "move Direction Error"); } } pLayer.registerEntityModifier(new SequenceEntityModifier( new MoveModifier(0.05f, pLayer.getX(), pLayer.getX() + addMoveX, pLayer.getY(), pLayer.getY() + addMoveY, new IEntityModifier.IEntityModifierListener() { @Override public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) { pLayer.setZIndex(pLayer.getZIndex() + 1); mBackgroundLayer.sortChildren(); } @Override public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) { } }), new MoveModifier(0.05f, pLayer.getX() + addMoveX, moveX, pLayer.getY() + addMoveY, moveY, new IEntityModifier.IEntityModifierListener() { @Override public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) { } @Override public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) { pLayer.setZIndex(pLayer.getZIndex() - 1); mBackgroundLayer.sortChildren(); } })) ); } private void finishChange() { Log.d(TAG, " // chainCount = 0; if (!checkExplosion()) { chegeState(PlayState.PlayStateChoose); } } private List<PanelLayer> mDeleteLayers; private boolean checkExplosion() { Log.d(TAG, "checkExplosion"); if (mMovingLayer1 != null) { // 2nil mMovingLayer1 = null; } /* * 3deletingLayers * * tempListtempList * tempList3deletingLayers * */ mDeleteLayers = new ArrayList<PanelLayer>(); List<PanelLayer> tempList = new ArrayList<PanelLayer>(); for (int y = 0; y < PANEL_COUNT_Y; y++) { tempList = checkMjExplosion(CheckMJExplosionType.CHECK_X, y); mDeleteLayers.addAll(tempList); } for (int x = 0; x < PANEL_COUNT_X; x++) { tempList = checkMjExplosion(CheckMJExplosionType.CHECK_Y, x); mDeleteLayers.addAll(tempList); } for (PanelLayer layer : mDeleteLayers) { layer.registerEntityModifier(new ParallelEntityModifier( new ScaleModifier(0.3f, 1.0f, 1.5f), new AlphaModifier(0.3f, 1.0f, 0.0f, new IEntityModifier.IEntityModifierListener() { @Override public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) { } @Override public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) { } }))); layer.getImage().registerEntityModifier(new AlphaModifier(0.3f, 1.0f, 0.0f)); } if (mDeleteLayers.size() > 0) { // TODO: // self.score += ([self.deletingLayers count] * 10 * (self.chainCount + 1)); // self.scoreLabel.text = [NSString stringWithFormat:@"%05d", self.score]; // TODO: // self.chainCount++; // (0.3)checkChain // [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(checkChain:) userInfo:nil repeats:NO]; registerUpdateHandler(new TimerHandler(0.3f, new ITimerCallback() { @Override public void onTimePassed(TimerHandler pTimerHandler) { finishExplosion(); } })); return true; } else { return addNewLayers(); } } public enum CheckMJExplosionType { CHECK_X, CHECK_Y, } private List<PanelLayer> checkMjExplosion(CheckMJExplosionType checkType, int baseIdx) { List<PanelLayer> tempList = new ArrayList<PanelLayer>(); List<PanelLayer> deleteList = new ArrayList<PanelLayer>(); int currentTypeValue = 0; int currentType = 0; int check = 1; // 1: 2: int checkDir = 1; // 1:() -1:() int panelCount = 0; if (checkType == CheckMJExplosionType.CHECK_X) { panelCount = PANEL_COUNT_X; } else { panelCount = PANEL_COUNT_Y; } for (int i = 0; i < panelCount; i++) { PanelLayer layer = null; if (checkType == CheckMJExplosionType.CHECK_X) { layer = panelMap[i][baseIdx]; } else if (checkType == CheckMJExplosionType.CHECK_Y) { layer = panelMap[baseIdx][i]; } if (layer == null) { if (tempList.size() >= 3) { if (tempList.size() == 4) { cutInKan(); // TODO: } deleteList.addAll(tempList); } tempList = new ArrayList<PanelLayer>(); currentType = 0; currentTypeValue = 0; check = 0; checkDir = 1; continue; } int mjType = layer.getMjPanel().getType(); int typeValue = layer.getMjPanel().getTypeValue(); if (check == 1 && mjType == currentType && (currentTypeValue) == typeValue && tempList.size() < 4) { tempList.add(layer); }else if (check == 1 && (tempList.size() >= 1 && tempList.size() < 3) && mjType != 4 && mjType == currentType && Math.abs(currentTypeValue - typeValue) == 1) { check = 2; checkDir = typeValue - currentTypeValue; List<PanelLayer> tempList2 = new ArrayList<PanelLayer>(); tempList2.add(tempList.get(tempList.size() - 1)); tempList = tempList2; tempList.add(layer); } else if (check == 2 && ((checkDir == 1 && (currentTypeValue + 1) == typeValue) || (checkDir == -1 && (currentTypeValue - 1) == typeValue)) && mjType == currentType && tempList.size() < 3) { tempList.add(layer); } else if (check == 2 && mjType == currentType && (currentTypeValue) == typeValue && tempList.size() < 3) { check = 1; List<PanelLayer> tempList2 = new ArrayList<PanelLayer>(); for (PanelLayer layer2 : tempList) { if (layer2.getMjPanel().getTypeValue() == typeValue) { tempList2.add(layer2); } } tempList = tempList2; tempList.add(layer); } else { check = 1; checkDir = 1; if (tempList.size() >= 3) { if (tempList.size() == 4) { cutInKan(); // TODO: } deleteList.addAll(tempList); } tempList = new ArrayList<PanelLayer>(); tempList.add(layer); } currentType = mjType; currentTypeValue = typeValue; } if (tempList.size() >= 3) { if (tempList.size() == 4) { cutInKan(); // TODO: } deleteList.addAll(tempList); } return deleteList; } private void cutInKan() { sortChildren(); mKanCutIn.setVisible(true); mKanCutIn.registerEntityModifier(new SequenceEntityModifier( new AlphaModifier(0.1f, 0.0f, 1.0f), new DelayModifier(0.5f, new IEntityModifier.IEntityModifierListener() { @Override public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) { } @Override public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) { mKanCutIn.setVisible(false); } }))); } private void finishExplosion() { Log.d(TAG, "finishExplosion"); for (PanelLayer layer : mDeleteLayers) { panelMap[layer.getPanelPoint().x][layer.getPanelPoint().y] = null; } getBaseActivity().runOnUpdateThread(new Runnable() { @Override public void run() { for (PanelLayer layer : mDeleteLayers) { layer.detachChildren(); layer.detachSelf(); } } }); boolean hasDropped = false; for (int x = 0; x < PANEL_COUNT_X; x++) { int count = 0; for (int y = 0; y < PANEL_COUNT_Y; y++) { PanelLayer layer = panelMap[x][y]; if (layer != null) { count++; } } final int START_Y = PANEL_COUNT_Y - 1; int y = START_Y; for (int i = 0; i < count; i++) { while (y >= 0) { PanelLayer layer = panelMap[x][y]; y if (layer != null) { // panelY if (layer.getPanelPoint().y != (START_Y -i)) { // (0.25) int panelX = layer.getPanelPoint().x; int panelY = layer.getPanelPoint().y; int movePanelY = (START_Y -i); int startX = getWindowToPanelX(panelX); int startY = getWindowToPanelY(panelY); int endY = getWindowToPanelY(movePanelY); layer.setPanelPoint(new Point(panelX, movePanelY)); panelMap[panelX][movePanelY] = layer; panelMap[panelX][panelY] = null; layer.registerEntityModifier(new MoveModifier(0.25f, startX, startX, startY, endY)); hasDropped = true; } break; } } } } // positoncheckExplosion if (hasDropped) { registerUpdateHandler(new TimerHandler(0.25f, new ITimerCallback() { @Override public void onTimePassed(TimerHandler pTimerHandler) { if (!checkExplosion()) { chegeState(PlayState.PlayStateChoose); } } })); } else { if (!addNewLayers()) { chegeState(PlayState.PlayStateChoose); } } } private boolean addNewLayers() { Log.d(TAG, "addNewLayers"); boolean hasAdded = false; final int START_Y = PANEL_COUNT_Y - 1; for (int x = 0; x < PANEL_COUNT_X; x++) { int y = START_Y; for (; y >= 0; y PanelLayer layer = panelMap[x][y]; if (layer == null) { break; } } y += 1; if (y > 0) { hasAdded = true; } for (int i = 0; i < y; i++) { final PanelLayer layer = createPanelLayer(x, y, getWindowToPanelX(x), getWindowToPanelY(i - y)); // backViewlayer mBackgroundLayer.attachChild(layer); int spaceCount = getPanelYCount(x); if (spaceCount >= 0) { final int panelX = x; final int panelY = (START_Y - spaceCount); int startX = getWindowToPanelX(panelX); int startY = getWindowToPanelY(i - y); int endY = getWindowToPanelY(panelY); panelMap[panelX][panelY] = layer; // (0.25) layer.registerEntityModifier(new MoveModifier(0.25f, startX, startX, startY, endY, new IEntityModifier.IEntityModifierListener() { @Override public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) { } @Override public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) { layer.setPanelPoint(new Point(panelX, panelY)); } })); } } } if (hasAdded) { registerUpdateHandler(new TimerHandler(0.5f, new ITimerCallback() { @Override public void onTimePassed(TimerHandler pTimerHandler) { if (!checkExplosion()) { chegeState(PlayState.PlayStateChoose); } } })); return true; } else { return false; } } private int getPanelYCount(int x) { int count = 0; for (int y = 0; y < PANEL_COUNT_Y; y++) { PanelLayer layer = panelMap[x][y]; if (layer != null) { count++; } } return count; } private void chegeState(PlayState pPlayState) { Log.d(TAG, "ChangeState " + state + " >> " + pPlayState); if (state == PlayState.PlayStateChoose && pPlayState == PlayState.PlayStateChange) { attachChild(mTouchBreakLayeer); } else if (state == PlayState.PlayStateChange && pPlayState == PlayState.PlayStateChoose) { detachChild(mTouchBreakLayeer); } state = pPlayState; } }
package com.ray3k.skincomposer.dialog; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Dialog; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.Array; import com.ray3k.skincomposer.DesktopWorker; import com.ray3k.skincomposer.Main; import com.ray3k.skincomposer.data.DrawableData; import com.ray3k.skincomposer.data.FontData; import com.ray3k.skincomposer.utils.Utils; import java.io.File; public class DialogPathErrors extends Dialog { private Array<DrawableData> foundDrawables; private Array<FontData> foundFonts; private Table dataTable; private ScrollPane scrollPane; private Main main; public DialogPathErrors(Main main, Skin skin, String windowStyleName, Array<DrawableData> drawables, Array<FontData> fonts) { super("", skin, windowStyleName); this.main = main; foundDrawables = new Array<>(); foundFonts = new Array<>(); setFillParent(true); key(Keys.ENTER, true); key(Keys.ESCAPE, false); Table table = getContentTable(); table.defaults().pad(10.0f); Label label = new Label("Path Errors", skin, "title"); table.add(label); table.row(); label = new Label("The following assets could not be found. Please resolve by clicking the associated button.", skin); label.setAlignment(Align.center); table.add(label).padBottom(0); table.row(); dataTable = new Table(); scrollPane = new ScrollPane(dataTable, skin); scrollPane.setFlickScroll(false); scrollPane.setFadeScrollBars(false); table.add(scrollPane).grow(); resetDrawableTable(main, skin, drawables, fonts); button("Apply", true); getButtonTable().getCells().first().getActor().addListener(main.getHandListener()); button("Cancel", false); getButtonTable().getCells().get(1).getActor().addListener(main.getHandListener()); getCell(getButtonTable()).padBottom(20.0f); table.setWidth(200); } private void resetDrawableTable(Main main, Skin skin, Array<DrawableData> drawables, Array<FontData> fonts) { dataTable.clear(); if (drawables.size > 0) { Label label = new Label("Drawable Name", skin, "black"); dataTable.add(label); label = new Label("Path", skin, "black"); dataTable.add(label); dataTable.add(); label = new Label("Found?", skin, "black"); dataTable.add(label); dataTable.row(); Image image = new Image(skin, "welcome-separator"); dataTable.add(image).colspan(4).pad(5.0f).padLeft(0.0f).padRight(0.0f).growX(); for (DrawableData drawable : drawables) { dataTable.row(); label = new Label(drawable.name, skin); dataTable.add(label); label = new Label(drawable.file.path(), skin); label.setWrap(true); label.setAlignment(Align.left); dataTable.add(label).growX(); TextButton textButton = new TextButton("browse...", skin); textButton.addListener(main.getHandListener()); dataTable.add(textButton).padLeft(10.0f); textButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { DesktopWorker desktopWorker = main.getDesktopWorker(); String[] filterPatterns = null; if (!Utils.isMac()) { filterPatterns = new String[] {"*.png", "*.jpg", "*.jpeg", "*.bmp", "*.gif"}; } File file = desktopWorker.openDialog("Locate " + drawable.file.name() + "...", drawable.file.path(), filterPatterns, "Image files"); if (file != null) { FileHandle fileHandle = new FileHandle(file); drawable.file = fileHandle; foundDrawables.add(drawable); resolveAssetsFromFolder(fileHandle.parent(), drawables, fonts); resetDrawableTable(main, skin, drawables, fonts); } } }); if (foundDrawables.contains(drawable, true)) { label = new Label("YES", skin, "white"); label.setColor(Color.GREEN); dataTable.add(label); } else { label = new Label("NO", skin, "white"); label.setColor(Color.RED); dataTable.add(label); } dataTable.row(); image = new Image(skin, "welcome-separator"); dataTable.add(image).colspan(4).pad(5.0f).padLeft(0.0f).padRight(0.0f).growX(); } } if (fonts.size > 0) { dataTable.row(); dataTable.defaults().padTop(20.0f); Label label = new Label("Font Name", skin, "black"); dataTable.add(label); label = new Label("Path", skin, "black"); dataTable.add(label); dataTable.add(); label = new Label("Found?", skin, "black"); dataTable.add(label); dataTable.defaults().reset(); dataTable.row(); Image image = new Image(skin, "welcome-separator"); dataTable.add(image).colspan(4).pad(5.0f).padLeft(0.0f).padRight(0.0f).growX(); for (FontData font : fonts) { dataTable.row(); label = new Label(font.getName(), skin); dataTable.add(label); label = new Label(font.file.path(), skin); label.setWrap(true); label.setAlignment(Align.center); dataTable.add(label).growX(); TextButton textButton = new TextButton("browse...", skin); textButton.addListener(main.getHandListener()); dataTable.add(textButton); textButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { DesktopWorker desktopWorker = main.getDesktopWorker(); String[] filterPatterns = null; if (!Utils.isMac()) { filterPatterns = new String[] {"*.fnt"}; } File file = desktopWorker.openDialog("Locate " + font.file.name() + "...", font.file.path(), filterPatterns, "Font files"); if (file != null) { FileHandle fileHandle = new FileHandle(file); font.file = fileHandle; foundFonts.add(font); resolveAssetsFromFolder(fileHandle.parent(), drawables, fonts); resetDrawableTable(main, skin, drawables, fonts); } } }); if (foundFonts.contains(font, true)) { label = new Label("YES", skin, "white"); label.setColor(Color.GREEN); dataTable.add(label); } else { label = new Label("NO", skin, "white"); label.setColor(Color.RED); dataTable.add(label); } dataTable.row(); image = new Image(skin, "welcome-separator"); dataTable.add(image).colspan(4).pad(5.0f).padLeft(0.0f).padRight(0.0f).growX(); } } } private void resolveAssetsFromFolder(FileHandle folder, Array<DrawableData> drawables, Array<FontData> fonts) { if (folder.isDirectory()) { for (DrawableData drawable : drawables) { if (!foundDrawables.contains(drawable, true)) { FileHandle file = folder.child(drawable.file.name()); if (file.exists()) { drawable.file = file; foundDrawables.add(drawable); } } } for (FontData font : fonts) { if (!foundFonts.contains(font, true)) { FileHandle file = folder.child(font.file.name()); if (file.exists()) { font.file = file; foundFonts.add(font); } } } } } @Override public boolean remove() { return super.remove(); } @Override public Dialog show(Stage stage) { super.show(stage); Gdx.app.postRunnable(new Runnable() { @Override public void run() { stage.setScrollFocus(scrollPane); } }); return this; } @Override protected void result(Object object) { if ((boolean) object == true) { main.getProjectData().setChangesSaved(false); main.getRootTable().produceAtlas(); main.getRootTable().populate(); } else { main.getMainListener().newFile(); } } }
package com.mebigfatguy.fbcontrib.detect; import java.util.BitSet; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.bcel.Constants; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.LocalVariable; import org.apache.bcel.classfile.LocalVariableTable; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.Type; import com.mebigfatguy.fbcontrib.utils.BugType; import com.mebigfatguy.fbcontrib.utils.OpcodeUtils; import com.mebigfatguy.fbcontrib.utils.SignatureUtils; import com.mebigfatguy.fbcontrib.utils.UnmodifiableSet; import com.mebigfatguy.fbcontrib.utils.Values; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.OpcodeStack.CustomUserValue; import edu.umd.cs.findbugs.ba.ClassContext; /** * looks for private or static methods that have parameters that aren't used. These parameters can be removed. */ @CustomUserValue public class UnusedParameter extends BytecodeScanningDetector { private static Set<String> IGNORE_METHODS = UnmodifiableSet.create(Values.CONSTRUCTOR, Values.STATIC_INITIALIZER, "main", "premain", "agentmain", "writeObject", "readObject", "readObjectNoData", "writeReplace", "readResolve", "writeExternal", "readExternal"); private BugReporter bugReporter; private BitSet unusedParms; private Map<Integer, Integer> regToParm; private OpcodeStack stack; /** * constructs a UP detector given the reporter to report bugs on * * @param bugReporter * the sync of bug reports */ public UnusedParameter(BugReporter bugReporter) { this.bugReporter = bugReporter; } /** * implements the visitor to create parm bitset * * @param classContext * the context object of the currently parsed class */ @Override public void visitClassContext(ClassContext classContext) { try { unusedParms = new BitSet(); regToParm = new HashMap<>(); stack = new OpcodeStack(); super.visitClassContext(classContext); } finally { stack = null; regToParm = null; unusedParms.clear(); } } /** * implements the visitor to clear the parm set, and check for potential methods * * @param obj * the context object of the currently parsed code block */ @Override public void visitCode(Code obj) { unusedParms.clear(); regToParm.clear(); stack.resetForMethodEntry(this); Method m = getMethod(); String methodName = m.getName(); if (IGNORE_METHODS.contains(methodName)) { return; } int accessFlags = m.getAccessFlags(); if (((accessFlags & (Constants.ACC_STATIC | Constants.ACC_PRIVATE)) != 0) && ((accessFlags & Constants.ACC_SYNTHETIC) == 0)) { Type[] parmTypes = Type.getArgumentTypes(m.getSignature()); if (parmTypes.length > 0) { int firstReg = 0; if ((accessFlags & Constants.ACC_STATIC) == 0) { ++firstReg; } int reg = firstReg; for (int i = 0; i < parmTypes.length; ++i) { unusedParms.set(reg); regToParm.put(Integer.valueOf(reg), Integer.valueOf(i + 1)); String parmSig = parmTypes[i].getSignature(); reg += SignatureUtils.getSignatureSize(parmSig); } super.visitCode(obj); if (!unusedParms.isEmpty()) { LocalVariableTable lvt = m.getLocalVariableTable(); reg = unusedParms.nextSetBit(firstReg); while (reg >= 0) { LocalVariable lv = (lvt != null) ? lvt.getLocalVariable(reg, 0) : null; if (lv != null) { String parmName = lv.getName(); bugReporter.reportBug(new BugInstance(this, BugType.UP_UNUSED_PARAMETER.name(), NORMAL_PRIORITY).addClass(this).addMethod(this) .addString("Parameter " + regToParm.get(Integer.valueOf(reg)) + ": " + parmName)); } reg = unusedParms.nextSetBit(reg + 1); } } } } } /** * implements the visitor to look for usage of parmeter registers. * * @param seen * the opcode of the currently parsed instruction */ @Override public void sawOpcode(int seen) { if (unusedParms.isEmpty()) { return; } try { stack.precomputation(this); if (OpcodeUtils.isStore(seen) || OpcodeUtils.isLoad(seen)) { int reg = getRegisterOperand(); unusedParms.clear(reg); } else if (OpcodeUtils.isReturn(seen)) { if (stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); int reg = item.getRegisterNumber(); if (reg >= 0) { unusedParms.clear(reg); } } } } finally { stack.sawOpcode(this, seen); } } }
package bisq.core.payment; import bisq.core.account.witness.AccountAgeWitnessService; import bisq.core.locale.Country; import bisq.core.offer.Offer; import bisq.core.payment.payload.PaymentMethod; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import javax.annotation.Nullable; @Slf4j public class PaymentAccountUtil { public static boolean isAnyTakerPaymentAccountValidForOffer(Offer offer, Collection<PaymentAccount> takerPaymentAccounts) { for (PaymentAccount takerPaymentAccount : takerPaymentAccounts) { if (isTakerPaymentAccountValidForOffer(offer, takerPaymentAccount)) return true; } return false; } public static ObservableList<PaymentAccount> getPossiblePaymentAccounts(Offer offer, Set<PaymentAccount> paymentAccounts, AccountAgeWitnessService accountAgeWitnessService) { ObservableList<PaymentAccount> result = FXCollections.observableArrayList(); result.addAll(paymentAccounts.stream() .filter(paymentAccount -> isTakerPaymentAccountValidForOffer(offer, paymentAccount)) .filter(paymentAccount -> isAmountValidForOffer(offer, paymentAccount, accountAgeWitnessService)) .collect(Collectors.toList())); return result; } // Return true if paymentAccount can take this offer public static boolean isAmountValidForOffer(Offer offer, PaymentAccount paymentAccount, AccountAgeWitnessService accountAgeWitnessService) { boolean hasChargebackRisk = PaymentMethod.hasChargebackRisk(offer.getPaymentMethod(), offer.getCurrencyCode()); boolean hasValidAccountAgeWitness = accountAgeWitnessService.getMyTradeLimit(paymentAccount, offer.getCurrencyCode(), offer.getMirroredDirection()) >= offer.getMinAmount().value; return !hasChargebackRisk || hasValidAccountAgeWitness; } // TODO might be used to show more details if we get payment methods updates with diff. limits public static String getInfoForMismatchingPaymentMethodLimits(Offer offer, PaymentAccount paymentAccount) { // dont translate atm as it is not used so far in the UI just for logs return "Payment methods have different trade limits or trade periods.\n" + "Our local Payment method: " + paymentAccount.getPaymentMethod().toString() + "\n" + "Payment method from offer: " + offer.getPaymentMethod().toString(); } public static boolean isTakerPaymentAccountValidForOffer(Offer offer, PaymentAccount paymentAccount) { return new ReceiptValidator(offer, paymentAccount).isValid(); } public static Optional<PaymentAccount> getMostMaturePaymentAccountForOffer(Offer offer, Set<PaymentAccount> paymentAccounts, AccountAgeWitnessService service) { PaymentAccounts accounts = new PaymentAccounts(paymentAccounts, service); return Optional.ofNullable(accounts.getOldestPaymentAccountForOffer(offer)); } @Nullable public static ArrayList<String> getAcceptedCountryCodes(PaymentAccount paymentAccount) { ArrayList<String> acceptedCountryCodes = null; if (paymentAccount instanceof SepaAccount) { acceptedCountryCodes = new ArrayList<>(((SepaAccount) paymentAccount).getAcceptedCountryCodes()); } else if (paymentAccount instanceof SepaInstantAccount) { acceptedCountryCodes = new ArrayList<>(((SepaInstantAccount) paymentAccount).getAcceptedCountryCodes()); } else if (paymentAccount instanceof CountryBasedPaymentAccount) { acceptedCountryCodes = new ArrayList<>(); Country country = ((CountryBasedPaymentAccount) paymentAccount).getCountry(); if (country != null) acceptedCountryCodes.add(country.code); } return acceptedCountryCodes; } @Nullable public static List<String> getAcceptedBanks(PaymentAccount paymentAccount) { List<String> acceptedBanks = null; if (paymentAccount instanceof SpecificBanksAccount) { acceptedBanks = new ArrayList<>(((SpecificBanksAccount) paymentAccount).getAcceptedBanks()); } else if (paymentAccount instanceof SameBankAccount) { acceptedBanks = new ArrayList<>(); acceptedBanks.add(((SameBankAccount) paymentAccount).getBankId()); } return acceptedBanks; } @Nullable public static String getBankId(PaymentAccount paymentAccount) { return paymentAccount instanceof BankAccount ? ((BankAccount) paymentAccount).getBankId() : null; } @Nullable public static String getCountryCode(PaymentAccount paymentAccount) { // That is optional and set to null if not supported (AltCoins,...) if (paymentAccount instanceof CountryBasedPaymentAccount) { Country country = (((CountryBasedPaymentAccount) paymentAccount)).getCountry(); return country != null ? country.code : null; } return null; } public static boolean isCryptoCurrencyAccount(PaymentAccount paymentAccount) { return (paymentAccount != null && paymentAccount.getPaymentMethod().equals(PaymentMethod.BLOCK_CHAINS) || paymentAccount != null && paymentAccount.getPaymentMethod().equals(PaymentMethod.BLOCK_CHAINS_INSTANT)); } // TODO no code duplication found in UI code (added for API) // That is optional and set to null if not supported (AltCoins,...) /* public static String getCountryCode(PaymentAccount paymentAccount) { if (paymentAccount instanceof CountryBasedPaymentAccount) { Country country = ((CountryBasedPaymentAccount) paymentAccount).getCountry(); return country != null ? country.code : null; } else { return null; } }*/ // TODO no code duplication found in UI code (added for API) /*public static long getMaxTradeLimit(AccountAgeWitnessService accountAgeWitnessService, PaymentAccount paymentAccount, String currencyCode) { if (paymentAccount != null) return accountAgeWitnessService.getMyTradeLimit(paymentAccount, currencyCode); else return 0; }*/ }
package seedu.jimi.logic.commands; import seedu.jimi.commons.core.Messages; import seedu.jimi.commons.core.UnmodifiableObservableList; import seedu.jimi.model.task.ReadOnlyTask; import seedu.jimi.model.task.UniqueTaskList.TaskNotFoundException; /** * Deletes a task identified using it's last displayed index from Jimi. */ public class DeleteCommand extends Command { public static final String COMMAND_WORD = "delete"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Deletes the specified task/event from Jimi.\n" + "You can specify the task/event by entering its index number given in the last listing. \n" + "If you need to recover your deleted task, you can use the undo command. \n" + "Parameters: INDEX (must be a positive integer)\n" + "Example: " + COMMAND_WORD + " 1"; public static final String MESSAGE_DELETE_TASK_SUCCESS = "Jimi has deleted this task: %1$s"; public static final String MESSAGE_DELETE_EVENT_SUCCESS = "Jimi has deleted this event: %1$s"; public final int targetIndex; public DeleteCommand(int targetIndex) { this.targetIndex = targetIndex; } @Override public CommandResult execute() { UnmodifiableObservableList<ReadOnlyTask> lastShownList = model.getFilteredTaskList(); if (lastShownList.size() < targetIndex) { indicateAttemptToExecuteIncorrectCommand(); return new CommandResult(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); } ReadOnlyTask taskToDelete = lastShownList.get(targetIndex - 1); try { model.deleteTask(taskToDelete); } catch (TaskNotFoundException pnfe) { assert false : "The target task cannot be missing"; } return new CommandResult(String.format(MESSAGE_DELETE_TASK_SUCCESS, taskToDelete)); } }
package net.badlogic.td.game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.box2d.*; import com.badlogic.gdx.physics.box2d.joints.MouseJoint; import com.badlogic.gdx.physics.box2d.joints.MouseJointDef; import com.badlogic.gdx.utils.Disposable; import net.badlogic.td.game.objects.Plate; import net.badlogic.td.screens.DirectedGame; import net.badlogic.td.screens.MenuScreen; import net.badlogic.td.screens.transitions.ScreenTransition; import net.badlogic.td.screens.transitions.ScreenTransitionSlide; import net.badlogic.td.util.CameraHelper; public class WorldController extends InputAdapter implements Disposable{ public CameraHelper cameraHelper; private static final String TAG = WorldController.class.getName(); private DirectedGame game; public Level level; public int score; public float scoreVisual; private String levelID = "levels/level-1.tmx"; public World b2world; /** a hit body **/ protected Body hitBody = null; /** our mouse joint **/ protected MouseJoint mouseJoint = null; /** ground body to connect the mouse joint to **/ protected Body groundBody; public WorldController (DirectedGame game) { this.game = game; init(); } //region LifeCycle private void init() { cameraHelper = new CameraHelper(); initLevel(); } private void initLevel () { score = 0; scoreVisual = score; level = new Level(levelID); initPhysics(); } public void update (float deltaTime) { handleDebugInput(deltaTime); level.update(deltaTime); } @Override public void dispose() { mouseJoint = null; } //endregion public boolean isGameOver () { return false; } private void backToMenu () { // switch to menu screen ScreenTransition transition = ScreenTransitionSlide.init(0.75f, ScreenTransitionSlide.DOWN, false, Interpolation.bounceOut); game.setScreen(new MenuScreen(game), transition); } //region HKeyInput @Override public boolean keyUp (int keycode) { // Reset game world if (keycode == Input.Keys.R) { init(); Gdx.app.debug(TAG, "Game world resetted"); } // Toggle camera follow else if (keycode == Input.Keys.ENTER) { // cameraHelper.setTarget(cameraHelper.hasTarget() ? null: level.bunnyHead); // Gdx.app.debug(TAG, "Camera follow enabled: " + cameraHelper.hasTarget()); } // Back to Menu else if (keycode == Input.Keys.ESCAPE || keycode == Input.Keys.BACK) { backToMenu(); } return false; } private void handleDebugInput (float deltaTime) { // Camera Controls (move) float camMoveSpeed = 5 * deltaTime; float camMoveSpeedAccelerationFactor = 5; if (Gdx.input.isKeyPressed(Input.Keys.SHIFT_LEFT)) camMoveSpeed *= camMoveSpeedAccelerationFactor; if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) moveCamera(-camMoveSpeed, 0); if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) moveCamera(camMoveSpeed, 0); if (Gdx.input.isKeyPressed(Input.Keys.UP)) moveCamera(0, camMoveSpeed); if (Gdx.input.isKeyPressed(Input.Keys.DOWN)) moveCamera(0, -camMoveSpeed); if (Gdx.input.isKeyPressed(Input.Keys.BACKSPACE)) cameraHelper.setPosition(0, 0); // Camera Controls (zoom) float camZoomSpeed = 1 * deltaTime; float camZoomSpeedAccelerationFactor = 5; if (Gdx.input.isKeyPressed(Input.Keys.SHIFT_LEFT)) camZoomSpeed *= camZoomSpeedAccelerationFactor; if (Gdx.input.isKeyPressed(Input.Keys.COMMA)) cameraHelper.addZoom(camZoomSpeed); if (Gdx.input.isKeyPressed(Input.Keys.PERIOD)) cameraHelper.addZoom( -camZoomSpeed); if (Gdx.input.isKeyPressed(Input.Keys.SLASH)) cameraHelper.setZoom(1); } //endregion private void moveCamera (float x, float y) { x += cameraHelper.getPosition().x; y += cameraHelper.getPosition().y; cameraHelper.setPosition(x, y); Gdx.app.debug(TAG, "Camera position: " + x +" " + y); } private void initPhysics () { if (b2world != null) b2world.dispose(); b2world = new World(new Vector2(0, -9.81f), true); BodyDef bodyDef; // we also need an invisible zero size ground body // to which we can connect the mouse joint bodyDef = new BodyDef(); groundBody = b2world.createBody(bodyDef); // Plate Vector2 origin = new Vector2(); for (Plate plate : level.plates) { bodyDef = new BodyDef(); bodyDef.type = BodyDef.BodyType.StaticBody; bodyDef.position.set(plate.position); Body body = b2world.createBody(bodyDef); plate.body = body; PolygonShape polygonShape = new PolygonShape(); origin.x = plate.bounds.width / 2.0f; origin.y = plate.bounds.height / 2.0f; polygonShape.setAsBox(plate.bounds.width / 2.0f, plate.bounds.height / 2.0f, origin, 0); FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = polygonShape; body.createFixture(fixtureDef); polygonShape.dispose(); } } /** we instantiate this vector and the callback here so we don't irritate the GC **/ Vector3 testPoint = new Vector3(); QueryCallback callback = new QueryCallback() { @Override public boolean reportFixture (Fixture fixture) { // if the hit point is inside the fixture of the body // we report it if (fixture.testPoint(testPoint.x, testPoint.y)) { hitBody = fixture.getBody(); return false; } else return true; } }; //region GDetector @Override public boolean touchUp (int x, int y, int pointer, int button) { // if a mouse joint exists we simply destroy it if (mouseJoint != null) { b2world.destroyJoint(mouseJoint); mouseJoint = null; } return false; } @Override public boolean touchDown (int x, int y, int pointer, int button) { Camera camera = CameraHelper.getCurentCamera(); // translate the mouse coordinates to world coordinates camera.unproject(testPoint.set(x, y, 0)); // ask the world which bodies are within the given // bounding box around the mouse pointer hitBody = null; b2world.QueryAABB(callback, testPoint.x - 0.0001f, testPoint.y - 0.0001f, testPoint.x + 0.0001f, testPoint.y + 0.0001f); // if (hitBody == groundBody) hitBody = null; // // ignore kinematic bodies, they don't work with the mouse joint // if (hitBody != null && hitBody.getType() == BodyDef.BodyType.KinematicBody) return false; // if we hit something we create a new mouse joint // and attach it to the hit body. if (hitBody != null) { MouseJointDef def = new MouseJointDef(); def.bodyA = groundBody; def.bodyB = hitBody; def.collideConnected = true; def.target.set(testPoint.x, testPoint.y); def.bodyB.setTransform( hitBody.getPosition() , hitBody.getAngle() +45); mouseJoint = (MouseJoint)b2world.createJoint(def); hitBody.setAwake(true); scoreVisual = scoreVisual +1; } return false; } //endregion }
package com.projects.view; import com.projects.Main; import javafx.fxml.FXML; import javafx.scene.chart.LineChart; import javafx.scene.chart.XYChart; import java.util.List; public class ProductionStatisticsController { @FXML private LineChart<String, Float> priceForDemandChart; @FXML private LineChart<String, Float> emissionsForDemandChart; private XYChart.Series<String, Float> priceForDemandSeries; private XYChart.Series<String, Float> emissionsForDemandSeries; private Main main; private int length = 100; @FXML private void initialize() { priceForDemandSeries= new XYChart.Series<>(); priceForDemandSeries.setName("Price"); priceForDemandChart.getData().add(priceForDemandSeries); emissionsForDemandSeries = new XYChart.Series<>(); emissionsForDemandSeries.setName("Emissions"); emissionsForDemandChart.getData().add(emissionsForDemandSeries); } public void setPriceForDemandData(List<Float> prices) { priceForDemandSeries.getData().clear(); int increments = prices.size() / length; for (int index = 0; index < length; ++index) { int demand = index * increments; if (demand > prices.size()) demand = prices.size() - 1; priceForDemandSeries.getData().add(new XYChart.Data<>(String.valueOf(demand), prices.get(demand))); } } public void setEmissionsForDemandData(List<Float> emissions) { emissionsForDemandSeries.getData().clear(); int increments = emissions.size() / length; for (int index = 0; index < length; ++index) { int demand = index * increments; if (demand > emissions.size()) demand = emissions.size() - 1; emissionsForDemandSeries.getData().add(new XYChart.Data<>(String.valueOf(demand), emissions.get(demand))); } } public void setMain(Main main) { this.main = main; } }
package ui.components.pickers; import backend.resource.TurboIssue; import backend.resource.TurboLabel; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.control.*; import javafx.scene.input.KeyCode; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.util.StringConverter; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class LabelPickerDialog extends Dialog<List<String>> { private TextField textField; private TurboIssue issue; private List<TurboLabel> allLabels; private ObservableList<LabelPicker.Label> labels; private LabelListView labelListView; private Map<String, Boolean> resultList; LabelPickerDialog(TurboIssue issue, List<TurboLabel> allLabels, Stage stage) { this.issue = issue; this.allLabels = allLabels; resultList = new HashMap<>(); allLabels.forEach(label -> resultList.put(label.getActualName(), issue.getLabels().contains(label.getActualName()))); initOwner(stage); initModality(Modality.APPLICATION_MODAL); // TODO change to NONE for multiple dialogs setTitle("Edit Labels for " + (issue.isPullRequest() ? "PR #" : "Issue #") + issue.getId() + " in " + issue.getRepoId()); setHeaderText((issue.isPullRequest() ? "PR #" : "Issue #") + issue.getId() + ": " + issue.getTitle()); ButtonType confirmButtonType = new ButtonType("Confirm", ButtonBar.ButtonData.OK_DONE); getDialogPane().getButtonTypes().addAll(confirmButtonType, ButtonType.CANCEL); VBox vBox = new VBox(); vBox.setPadding(new Insets(10)); textField = new TextField(); textField.setPrefColumnCount(30); setupKeyEvents(); Label instructions = new Label("UP/DOWN to navigate, TAB to toggle selection"); instructions.setPadding(new Insets(0, 0, 10, 0)); updateLabelsList(""); labelListView = new LabelListView(this); labelListView.setItems(labels); labelListView.setCellFactory(LabelPickerCell.forListView(LabelPicker.Label::checkedProperty, new StringConverter<LabelPicker.Label>() { @Override public String toString(LabelPicker.Label object) { return object.getName(); } @Override public LabelPicker.Label fromString(String string) { return null; } })); vBox.getChildren().addAll(instructions, textField, labelListView); getDialogPane().setContent(vBox); setResultConverter(dialogButton -> { if (dialogButton == confirmButtonType) { return allLabels .stream() .filter(label -> resultList.get(label.getName())) .map(TurboLabel::getActualName) .collect(Collectors.toList()); } return null; }); labelListView.setFirstItem(); requestFocus(); } protected void requestFocus() { Platform.runLater(textField::requestFocus); } private void setupKeyEvents() { textField.textProperty().addListener((observable, oldValue, newValue) -> { updateLabelsList(newValue); labelListView.setItems(labels); labelListView.setFirstItem(); labelListView.setItems(null); labelListView.setItems(labels); }); textField.setOnKeyPressed(e -> { if (!e.isAltDown() && !e.isMetaDown() && !e.isControlDown()) { if (e.getCode() == KeyCode.DOWN) { labelListView.handleUpDownKeys(true); labelListView.showSelectedItemChange(); labelListView.setItems(null); labelListView.setItems(labels); e.consume(); } else if (e.getCode() == KeyCode.UP) { labelListView.handleUpDownKeys(false); labelListView.showSelectedItemChange(); labelListView.setItems(null); labelListView.setItems(labels); e.consume(); } else if (e.getCode() == KeyCode.TAB) { labelListView.toggleSelectedItem(); e.consume(); } } }); } private void updateLabelsList(String match) { List<TurboLabel> matchedLabels = allLabels .stream() .filter(label -> label.getActualName().contains(match)) .collect(Collectors.toList()); ObservableList<LabelPicker.Label> selectedLabels = FXCollections.observableArrayList(matchedLabels.stream() .filter(label -> resultList.get(label.getActualName())) .map(label -> new LabelPicker.Label(label.getActualName(), label.getStyle(), true)) .collect(Collectors.toList())); ObservableList<LabelPicker.Label> notSelectedLabels = FXCollections.observableArrayList(matchedLabels.stream() .filter(label -> !resultList.get(label.getActualName())) .map(label -> new LabelPicker.Label(label.getActualName(), label.getStyle(), false)) .collect(Collectors.toList())); labels = FXCollections.concat(selectedLabels, notSelectedLabels); labels.forEach(label -> label.checkedProperty().addListener((observable, wasSelected, isSelected) -> { resultList.put(label.getName(), isSelected); })); } }
package za.redbridge.experiment; import org.encog.ml.CalculateScore; import org.encog.ml.MLMethod; import java.awt.Color; import java.awt.Paint; import sim.display.Console; import za.redbridge.experiment.MMNEAT.MMNEATNetwork; import za.redbridge.simulator.Simulation; import za.redbridge.simulator.SimulationGUI; import za.redbridge.simulator.config.SimConfig; import za.redbridge.simulator.factories.HomogeneousRobotFactory; import za.redbridge.simulator.factories.RobotFactory; public class ScoreCalculator implements CalculateScore { private static final double DEFAULT_ROBOT_MASS = 0.7; private static final double DEFAULT_ROBOT_RADIUS = 0.15; private static final Paint DEFAULT_ROBOT_PAINT = Color.BLACK; private final SimConfig simConfig; private double lastScore; public ScoreCalculator(SimConfig simConfig) { this.simConfig = simConfig; } @Override public double calculateScore(MLMethod method) { MMNEATNetwork network = (MMNEATNetwork) method; // Create the robot and resource factories RobotFactory robotFactory = new HomogeneousRobotFactory(new MMNEATPhenotype(network), DEFAULT_ROBOT_MASS, DEFAULT_ROBOT_RADIUS, DEFAULT_ROBOT_PAINT); // Create the simulation and run it Simulation simulation = new Simulation(simConfig, robotFactory, 15); simulation.run(); // Get the fitness lastScore = simulation.getFitness(); return lastScore; } public void demo(MMNEATNetwork network) { // Create the robot and resource factories RobotFactory robotFactory = new HomogeneousRobotFactory(new MMNEATPhenotype(network), DEFAULT_ROBOT_MASS, DEFAULT_ROBOT_RADIUS, DEFAULT_ROBOT_PAINT); // Create the simulation and run it Simulation simulation = new Simulation(simConfig, robotFactory, 15); SimulationGUI video = new SimulationGUI(simulation); //new console which displays this simulation Console console = new Console(video); console.setVisible(true); } @Override public boolean shouldMinimize() { return false; } @Override public boolean requireSingleThreaded() { return false; } public double getLastScore() { return lastScore; } }
package gov.nih.nci.evs.browser.utils; import java.io.*; import java.util.*; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Vector; import java.util.HashSet; import java.util.Arrays; import javax.faces.model.SelectItem; import org.apache.commons.lang.StringUtils; import org.LexGrid.LexBIG.DataModel.Collections.ResolvedConceptReferenceList; import org.LexGrid.LexBIG.DataModel.Collections.SortOptionList; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeSummary; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag; import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference; import org.LexGrid.LexBIG.Exceptions.LBException; import org.LexGrid.LexBIG.Impl.LexBIGServiceImpl; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet; import org.LexGrid.LexBIG.LexBIGService.LexBIGService; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.PropertyType; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.SearchDesignationOption; import org.LexGrid.LexBIG.Utility.Constructors; import org.LexGrid.LexBIG.Utility.LBConstants.MatchAlgorithms; import org.LexGrid.concepts.Concept; import org.LexGrid.LexBIG.DataModel.Collections.CodingSchemeRenderingList; import org.LexGrid.LexBIG.DataModel.InterfaceElements.CodingSchemeRendering; import org.LexGrid.LexBIG.DataModel.Collections.LocalNameList; import org.LexGrid.LexBIG.DataModel.Collections.ModuleDescriptionList; import org.LexGrid.LexBIG.DataModel.InterfaceElements.ModuleDescription; import org.LexGrid.LexBIG.Utility.Iterators.ResolvedConceptReferencesIterator; import org.LexGrid.LexBIG.DataModel.Collections.ConceptReferenceList; import org.LexGrid.LexBIG.DataModel.Core.ConceptReference; import org.LexGrid.LexBIG.LexBIGService.CodedNodeGraph; import org.LexGrid.LexBIG.DataModel.Collections.NameAndValueList; import org.LexGrid.LexBIG.DataModel.Core.NameAndValue; import org.LexGrid.LexBIG.DataModel.Collections.AssociationList; import org.LexGrid.LexBIG.DataModel.Core.AssociatedConcept; import org.LexGrid.LexBIG.DataModel.Core.Association; import org.LexGrid.LexBIG.DataModel.Collections.AssociatedConceptList; import org.LexGrid.codingSchemes.CodingScheme; import org.LexGrid.concepts.Definition; import org.LexGrid.concepts.Comment; import org.LexGrid.concepts.Presentation; import org.apache.log4j.Logger; import org.LexGrid.LexBIG.Exceptions.LBResourceUnavailableException; import org.LexGrid.LexBIG.Exceptions.LBInvocationException; import org.LexGrid.LexBIG.Utility.ConvenienceMethods; import org.LexGrid.commonTypes.EntityDescription; import org.LexGrid.commonTypes.Property; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag; import org.LexGrid.LexBIG.DataModel.Collections.AssociationList; import org.LexGrid.LexBIG.DataModel.Collections.ConceptReferenceList; import org.LexGrid.LexBIG.DataModel.Collections.LocalNameList; import org.LexGrid.LexBIG.DataModel.Collections.ResolvedConceptReferenceList; import org.LexGrid.LexBIG.DataModel.Core.AssociatedConcept; import org.LexGrid.LexBIG.DataModel.Core.Association; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeSummary; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag; import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference; import org.LexGrid.LexBIG.Exceptions.LBException; import org.LexGrid.LexBIG.Impl.LexBIGServiceImpl; import org.LexGrid.LexBIG.LexBIGService.LexBIGService; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.ActiveOption; import org.LexGrid.LexBIG.Utility.ConvenienceMethods; import org.LexGrid.commonTypes.EntityDescription; import org.LexGrid.commonTypes.Property; import org.LexGrid.concepts.Concept; import org.LexGrid.relations.Relations; import org.LexGrid.commonTypes.PropertyQualifier; import org.LexGrid.commonTypes.Source; import org.LexGrid.naming.SupportedSource; import org.LexGrid.naming.SupportedPropertyQualifier; import org.LexGrid.LexBIG.DataModel.Core.types.CodingSchemeVersionStatus; import org.LexGrid.naming.SupportedAssociation; import org.LexGrid.naming.SupportedAssociationQualifier; import org.LexGrid.naming.SupportedProperty; import org.LexGrid.naming.SupportedPropertyQualifier; import org.LexGrid.naming.SupportedRepresentationalForm; import org.LexGrid.naming.SupportedSource; import org.LexGrid.LexBIG.DataModel.Collections.AssociatedConceptList; import org.LexGrid.LexBIG.DataModel.Collections.AssociationList; import org.LexGrid.LexBIG.DataModel.Core.AssociatedConcept; import org.LexGrid.LexBIG.DataModel.Core.Association; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeSummary; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag; import org.LexGrid.LexBIG.Exceptions.LBException; import org.LexGrid.LexBIG.Extensions.Generic.LexBIGServiceConvenienceMethods; import org.LexGrid.LexBIG.Impl.LexBIGServiceImpl; import org.LexGrid.LexBIG.LexBIGService.LexBIGService; import org.LexGrid.naming.Mappings; import org.LexGrid.naming.SupportedHierarchy; import org.LexGrid.LexBIG.DataModel.InterfaceElements.RenderingDetail; import org.LexGrid.LexBIG.DataModel.Collections.CodingSchemeTagList; import gov.nih.nci.evs.browser.properties.NCImBrowserProperties; import gov.nih.nci.evs.browser.utils.test.DBG; import org.LexGrid.LexBIG.Exceptions.LBParameterException; import org.LexGrid.LexBIG.DataModel.Collections.ResolvedConceptReferenceList; import org.LexGrid.LexBIG.DataModel.Collections.SortOptionList; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeSummary; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag; import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference; import org.LexGrid.LexBIG.Exceptions.LBException; import org.LexGrid.LexBIG.Impl.LexBIGServiceImpl; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet; import org.LexGrid.LexBIG.LexBIGService.LexBIGService; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.PropertyType; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.SearchDesignationOption; import org.LexGrid.LexBIG.Utility.Constructors; import org.LexGrid.LexBIG.Utility.LBConstants.MatchAlgorithms; import org.LexGrid.concepts.Entity; import gov.nih.nci.evs.browser.common.Constants; import org.LexGrid.relations.AssociationQualification; import java.util.Map; import org.LexGrid.LexBIG.LexBIGService.LexBIGService; import org.LexGrid.LexBIG.caCore.interfaces.LexEVSApplicationService; import org.LexGrid.lexevs.metabrowser.MetaBrowserService; import org.LexGrid.lexevs.metabrowser.MetaBrowserService.Direction; import org.LexGrid.lexevs.metabrowser.model.RelationshipTabResults; /** * @author EVS Team * @version 1.0 * * Modification history * Initial implementation kim.ong@ngc.com * */ public class DataUtils { private static Vector<String> sourceListData = null; LocalNameList noopList_ = Constructors.createLocalNameList("_noop_"); static SortOptionList sortByCode_ = Constructors.createSortOptionList(new String[] {"code"}); Connection con; Statement stmt; ResultSet rs; private List supportedStandardReportList = new ArrayList(); private static List standardReportTemplateList = null; private static List adminTaskList = null; private static List userTaskList = null; private static List propertyTypeList = null; private static List _ontologies = null; private static org.LexGrid.LexBIG.LexBIGService.LexBIGService lbSvc = null; public org.LexGrid.LexBIG.Utility.ConvenienceMethods lbConvMethods = null; public CodingSchemeRenderingList csrl = null; private Vector supportedCodingSchemes = null; private static HashMap codingSchemeMap = null; private Vector codingSchemes = null; private static HashMap csnv2codingSchemeNameMap = null; private static HashMap csnv2VersionMap = null; private static List directionList = null; private static String[] ASSOCIATION_NAMES = null; public static String INCOMPLETE = "INCOMPLETE"; // For customized query use private static String SOURCE_OF = "outbound associations"; private static String TARGET_OF = "inbound associations"; public static int ALL = 0; public static int PREFERRED_ONLY = 1; public static int NON_PREFERRED_ONLY = 2; static int RESOLVE_SOURCE = 1; static int RESOLVE_TARGET = -1; static int RESTRICT_SOURCE = -1; static int RESTRICT_TARGET = 1; public static final int SEARCH_NAME_CODE = 1; public static final int SEARCH_DEFINITION = 2; public static final int SEARCH_PROPERTY_VALUE = 3; public static final int SEARCH_ROLE_VALUE = 6; public static final int SEARCH_ASSOCIATION_VALUE = 7; static final List<String> STOP_WORDS = Arrays.asList(new String[] { "a", "an", "and", "by", "for", "of", "on", "in", "nos", "the", "to", "with"}); public static String TYPE_ROLE = "type_role"; public static String TYPE_ASSOCIATION = "type_association"; public static String TYPE_SUPERCONCEPT = "type_superconcept"; public static String TYPE_SUBCONCEPT = "type_subconcept"; public static String TYPE_SIBLINGCONCEPT = "type_siblingconcept"; public static String TYPE_BROADERCONCEPT = "type_broaderconcept"; public static String TYPE_NARROWERCONCEPT = "type_narrowerconcept"; public String NCICBContactURL = null; public String terminologySubsetDownloadURL = null; public String NCIMBuildInfo = null; static String[] hierAssocToParentNodes_ = new String[] { "PAR", "isa", "branch_of", "part_of", "tributary_of" }; static String[] hierAssocToChildNodes_ = new String[] { "CHD", "inverse_isa" }; static String[] assocToSiblingNodes_ = new String[] { "SIB" }; static String[] assocToBTNodes_ = new String[] { "RB" }; static String[] assocToNTNodes_ = new String[] { "RN" }; static String[] relationshipCategories_ = new String[] { "Parent", "Child", "Broader", "Narrower", "Sibling", "Other"}; private static String SOURCE = "source"; static String[] META_ASSOCIATIONS = new String[] {"AQ", "CHD", "RB", "RO", "RQ", "SIB", "SY"}; public DataUtils() { } public static String[] getAllAssociationNames() { if (ASSOCIATION_NAMES != null) return null; Vector<String> v = getSupportedAssociationNames(Constants.CODING_SCHEME_NAME, null); ASSOCIATION_NAMES = new String[v.size()]; for (int i=0; i<v.size(); i++) { String s = (String) v.elementAt(i); ASSOCIATION_NAMES[i] = s; } return ASSOCIATION_NAMES; } /* public static List getOntologyList() { if(_ontologies == null) setCodingSchemeMap(); return _ontologies; } */ /* public static Vector<String> getSupportedAssociationNames(String key) { if (csnv2codingSchemeNameMap == null) { setCodingSchemeMap(); return getSupportedAssociationNames(key); } String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key); if(codingSchemeName == null) return null; String version = (String) csnv2VersionMap.get(key); if(version == null) return null; return getSupportedAssociationNames(codingSchemeName, version); } */ public static Vector<String> getSupportedAssociationNames(String codingSchemeName, String version) { CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag(); if (version != null) { vt.setVersion(version); } CodingScheme scheme = null; try { //RemoteServerUtil rsu = new RemoteServerUtil(); //EVSApplicationService lbSvc = rsu.createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt); if (scheme == null) { System.out.println("scheme is NULL"); return null; } Vector<String> v = new Vector<String>(); SupportedAssociation[] assos = scheme.getMappings().getSupportedAssociation(); for (int i=0; i<assos.length; i++) { SupportedAssociation sa = (SupportedAssociation) assos[i]; v.add(sa.getLocalId()); } return v; } catch (Exception ex) { ex.printStackTrace(); } return null; } /* public static Vector<String> getPropertyNameListData(String key) { if (csnv2codingSchemeNameMap == null) { setCodingSchemeMap(); } String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key); if(codingSchemeName == null) { return null; } String version = (String) csnv2VersionMap.get(key); if(version == null) { return null; } return getPropertyNameListData(codingSchemeName, version); } */ public static Vector<String> getPropertyNameListData(String codingSchemeName, String version) { CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag(); if (version != null) { vt.setVersion(version); } CodingScheme scheme = null; try { //RemoteServerUtil rsu = new RemoteServerUtil(); //EVSApplicationService lbSvc = rsu.createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt); if (scheme == null) return null; Vector<String> propertyNameListData = new Vector<String>(); SupportedProperty[] properties = scheme.getMappings().getSupportedProperty(); for (int i=0; i<properties.length; i++) { SupportedProperty property = properties[i]; propertyNameListData.add(property.getLocalId()); } return propertyNameListData; } catch (Exception ex) { ex.printStackTrace(); } return null; } public static String getCodingSchemeName(String key) { return (String) csnv2codingSchemeNameMap.get(key); } public static String getCodingSchemeVersion(String key) { return (String) csnv2VersionMap.get(key); } public static Vector<String> getRepresentationalFormListData(String key) { String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key); if(codingSchemeName == null) return null; String version = (String) csnv2VersionMap.get(key); if(version == null) return null; return getRepresentationalFormListData(codingSchemeName, version); } public static Vector<String> getRepresentationalFormListData(String codingSchemeName, String version) { CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag(); if (version != null) { vt.setVersion(version); } CodingScheme scheme = null; try { //RemoteServerUtil rsu = new RemoteServerUtil(); //EVSApplicationService lbSvc = rsu.createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt); if (scheme == null) return null; Vector<String> propertyNameListData = new Vector<String>(); SupportedRepresentationalForm[] forms = scheme.getMappings().getSupportedRepresentationalForm(); if (forms != null) { for (int i=0; i<forms.length; i++) { SupportedRepresentationalForm form = forms[i]; propertyNameListData.add(form.getLocalId()); } } return propertyNameListData; } catch (Exception ex) { ex.printStackTrace(); } return null; } public static Vector<String> getPropertyQualifierListData(String key) { String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key); if(codingSchemeName == null) return null; String version = (String) csnv2VersionMap.get(key); if(version == null) return null; return getPropertyQualifierListData(codingSchemeName, version); } public static Vector<String> getPropertyQualifierListData(String codingSchemeName, String version) { CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag(); if (version != null) { vt.setVersion(version); } CodingScheme scheme = null; try { //RemoteServerUtil rsu = new RemoteServerUtil(); //EVSApplicationService lbSvc = rsu.createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt); if (scheme == null) return null; Vector<String> propertyQualifierListData = new Vector<String>(); SupportedPropertyQualifier[] qualifiers = scheme.getMappings().getSupportedPropertyQualifier(); for (int i=0; i<qualifiers.length; i++) { SupportedPropertyQualifier qualifier = qualifiers[i]; propertyQualifierListData.add(qualifier.getLocalId()); } return propertyQualifierListData; } catch (Exception ex) { ex.printStackTrace(); } return null; } /* public static Vector<String> getSourceListData(String key) { if (csnv2codingSchemeNameMap == null) { setCodingSchemeMap(); return getSourceListData(key); } String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key); if(codingSchemeName == null) return null; String version = (String) csnv2VersionMap.get(key); if(version == null) return null; return getSourceListData(codingSchemeName, version); } */ public static Vector<String> getSourceListData(String codingSchemeName, String version) { if (sourceListData != null) return sourceListData; CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag(); if (version != null) { vt.setVersion(version); } CodingScheme scheme = null; try { //RemoteServerUtil rsu = new RemoteServerUtil(); //EVSApplicationService lbSvc = rsu.createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); if (lbSvc == null) return null; scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt); if (scheme == null) return null; sourceListData = new Vector<String>(); if (scheme.getMappings() == null) return null; sourceListData.add("ALL"); //Insert your code here SupportedSource[] sources = scheme.getMappings().getSupportedSource(); if (sources == null) return null; for (int i=0; i<sources.length; i++) { SupportedSource source = sources[i]; sourceListData.add(source.getLocalId()); } return sourceListData; } catch (Exception ex) { ex.printStackTrace(); } return null; } public static String int2String(Integer int_obj) { if (int_obj == null) { return null; } String retstr = Integer.toString(int_obj); return retstr; } public static Concept getConceptByCode(String codingSchemeName, String vers, String ltag, String code) { try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); if (lbSvc == null) { System.out.println("lbSvc == null???"); return null; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(vers); ConceptReferenceList crefs = createConceptReferenceList( new String[] {code}, codingSchemeName); CodedNodeSet cns = null; try { cns = lbSvc.getCodingSchemeConcepts(codingSchemeName, versionOrTag); cns = cns.restrictToCodes(crefs); ResolvedConceptReferenceList matches = cns.resolveToList(null, null, null, 1); if (matches == null) { System.out.println("Concep not found."); return null; } int count = matches.getResolvedConceptReferenceCount(); // Analyze the result ... if (count == 0) return null; if (count > 0) { try { ResolvedConceptReference ref = (ResolvedConceptReference) matches.enumerateResolvedConceptReference().nextElement(); Concept entry = ref.getReferencedEntry(); return entry; } catch (Exception ex1) { System.out.println("Exception entry == null"); return null; } } } catch (Exception e1) { e1.printStackTrace(); return null; } } catch (Exception e) { e.printStackTrace(); return null; } return null; } public static CodedNodeSet restrictToSource(CodedNodeSet cns, String source) { if (cns == null) return cns; if (source == null || source.compareTo("*") == 0 || source.compareTo("") == 0 || source.compareTo("ALL") == 0) return cns; LocalNameList contextList = null; LocalNameList sourceLnL = null; NameAndValueList qualifierList = null; Vector<String> w2 = new Vector<String>(); w2.add(source); sourceLnL = vector2LocalNameList(w2); LocalNameList propertyLnL = null; CodedNodeSet.PropertyType[] types = new PropertyType[] {PropertyType.PRESENTATION}; try { cns = cns.restrictToProperties(propertyLnL, types, sourceLnL, contextList, qualifierList); } catch (Exception ex) { System.out.println("restrictToSource throws exceptions."); return null; } return cns; } public static Concept getConceptByCode(String codingSchemeName, String vers, String ltag, String code, String source) { try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); if (lbSvc == null) { System.out.println("lbSvc == null???"); return null; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (vers != null) versionOrTag.setVersion(vers); ConceptReferenceList crefs = createConceptReferenceList( new String[] {code}, codingSchemeName); CodedNodeSet cns = null; try { cns = lbSvc.getCodingSchemeConcepts(codingSchemeName, versionOrTag); } catch (Exception e1) { //e1.printStackTrace(); } cns = cns.restrictToCodes(crefs); cns = restrictToSource(cns, source); ResolvedConceptReferenceList matches = cns.resolveToList(null, null, null, 1); if (matches == null) { System.out.println("Concep not found."); return null; } // Analyze the result ... if (matches.getResolvedConceptReferenceCount() > 0) { ResolvedConceptReference ref = (ResolvedConceptReference) matches.enumerateResolvedConceptReference().nextElement(); Concept entry = ref.getReferencedEntry(); return entry; } } catch (Exception e) { //e.printStackTrace(); return null; } return null; } public static NameAndValueList createNameAndValueList(String[] names, String[] values) { NameAndValueList nvList = new NameAndValueList(); for (int i=0; i<names.length; i++) { NameAndValue nv = new NameAndValue(); nv.setName(names[i]); if (values != null) { nv.setContent(values[i]); } nvList.addNameAndValue(nv); } return nvList; } public ResolvedConceptReferenceList getNext(ResolvedConceptReferencesIterator iterator) { return iterator.getNext(); } public Vector getParentCodes(String scheme, String version, String code) { Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme, version); if (hierarchicalAssoName_vec == null || hierarchicalAssoName_vec.size() == 0) { return null; } String hierarchicalAssoName = (String) hierarchicalAssoName_vec.elementAt(0); //KLO, 01/23/2009 //Vector<Concept> superconcept_vec = util.getAssociationSources(scheme, version, code, hierarchicalAssoName); Vector superconcept_vec = getAssociationSourceCodes(scheme, version, code, hierarchicalAssoName); if (superconcept_vec == null) return null; //SortUtils.quickSort(superconcept_vec, SortUtils.SORT_BY_CODE); return superconcept_vec; } public Vector getAssociationSourceCodes(String scheme, String version, String code, String assocName) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { //EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); NameAndValueList nameAndValueList = createNameAndValueList( new String[] {assocName}, null); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier); int maxToReturn = NCImBrowserProperties.maxToReturn; matches = cng.resolveAsList( ConvenienceMethods.createConceptReference(code, scheme), false, true, 1, 1, new LocalNameList(), null, null, maxToReturn); if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = matches .enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList targetof = ref.getTargetOf(); Association[] associations = targetof.getAssociation(); for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; //KLO assoc = processForAnonomousNodes(assoc); AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; v.add(ac.getReferencedEntry().getEntityCode()); } } } SortUtils.quickSort(v); } } catch (Exception ex) { ex.printStackTrace(); } return v; } public static ConceptReferenceList createConceptReferenceList(String[] codes, String codingSchemeName) { if (codes == null) { return null; } ConceptReferenceList list = new ConceptReferenceList(); for (int i = 0; i < codes.length; i++) { ConceptReference cr = new ConceptReference(); cr.setCodingSchemeName(codingSchemeName); cr.setConceptCode(codes[i]); list.addConceptReference(cr); } return list; } public Vector getSubconceptCodes(String scheme, String version, String code) { //throws LBException{ Vector v = new Vector(); try { //EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); csvt.setVersion(version); String desc = null; try { desc = lbscm.createCodeNodeSet(new String[] {code}, scheme, csvt) .resolveToList(null, null, null, 1) .getResolvedConceptReference(0) .getEntityDescription().getContent(); } catch (Exception e) { desc = "<not found>"; } // Iterate through all hierarchies and levels ... String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt); for (int k = 0; k < hierarchyIDs.length; k++) { String hierarchyID = hierarchyIDs[k]; AssociationList associations = null; associations = null; try { associations = lbscm.getHierarchyLevelNext(scheme, csvt, hierarchyID, code, false, null); } catch (Exception e) { System.out.println("getSubconceptCodes - Exception lbscm.getHierarchyLevelNext "); return v; } for (int i = 0; i < associations.getAssociationCount(); i++) { Association assoc = associations.getAssociation(i); AssociatedConceptList concepts = assoc.getAssociatedConcepts(); for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) { AssociatedConcept concept = concepts.getAssociatedConcept(j); String nextCode = concept.getConceptCode(); v.add(nextCode); } } } } catch (Exception ex) { //ex.printStackTrace(); } return v; } public Vector getSuperconceptCodes(String scheme, String version, String code) { //throws LBException{ long ms = System.currentTimeMillis(); Vector v = new Vector(); try { //EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); csvt.setVersion(version); String desc = null; try { desc = lbscm.createCodeNodeSet(new String[] {code}, scheme, csvt) .resolveToList(null, null, null, 1) .getResolvedConceptReference(0) .getEntityDescription().getContent(); } catch (Exception e) { desc = "<not found>"; } // Iterate through all hierarchies and levels ... String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt); for (int k = 0; k < hierarchyIDs.length; k++) { String hierarchyID = hierarchyIDs[k]; AssociationList associations = lbscm.getHierarchyLevelPrev(scheme, csvt, hierarchyID, code, false, null); for (int i = 0; i < associations.getAssociationCount(); i++) { Association assoc = associations.getAssociation(i); AssociatedConceptList concepts = assoc.getAssociatedConcepts(); for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) { AssociatedConcept concept = concepts.getAssociatedConcept(j); String nextCode = concept.getConceptCode(); v.add(nextCode); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { System.out.println("Run time (ms): " + (System.currentTimeMillis() - ms)); } return v; } public Vector getHierarchyAssociationId(String scheme, String version) { Vector association_vec = new Vector(); try { //EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); // Will handle secured ontologies later. CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(version); CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag); Mappings mappings = cs.getMappings(); SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy(); java.lang.String[] ids = hierarchies[0].getAssociationNames(); for (int i=0; i<ids.length; i++) { if (!association_vec.contains(ids[i])) { association_vec.add(ids[i]); } } } catch (Exception ex) { ex.printStackTrace(); } return association_vec; } /* public static String getVocabularyVersionByTag(String codingSchemeName, String ltag) { if (codingSchemeName == null) return null; try { //EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeRenderingList lcsrl = lbSvc.getSupportedCodingSchemes(); CodingSchemeRendering[] csra = lcsrl.getCodingSchemeRendering(); for (int i=0; i<csra.length; i++) { CodingSchemeRendering csr = csra[i]; CodingSchemeSummary css = csr.getCodingSchemeSummary(); if (css.getFormalName().compareTo(codingSchemeName) == 0 || css.getLocalName().compareTo(codingSchemeName) == 0) { if (ltag == null) return css.getRepresentsVersion(); RenderingDetail rd = csr.getRenderingDetail(); CodingSchemeTagList cstl = rd.getVersionTags(); java.lang.String[] tags = cstl.getTag(); for (int j=0; j<tags.length; j++) { String version_tag = (String) tags[j]; if (version_tag.compareToIgnoreCase(ltag) == 0) { return css.getRepresentsVersion(); } } } } } catch (Exception e) { e.printStackTrace(); } System.out.println("Version corresponding to tag " + ltag + " is not found " + " in " + codingSchemeName); return null; } */ public static String getVocabularyVersionByTag(String codingSchemeName, String ltag) { System.out.println("getVocabularyVersionByTag: " + codingSchemeName); System.out.println("getVocabularyVersionByTag: ltag " + ltag); if (codingSchemeName == null) return null; String version = null; int knt = 0; try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeRenderingList lcsrl = lbSvc.getSupportedCodingSchemes(); CodingSchemeRendering[] csra = lcsrl.getCodingSchemeRendering(); for (int i=0; i<csra.length; i++) { CodingSchemeRendering csr = csra[i]; CodingSchemeSummary css = csr.getCodingSchemeSummary(); if (css.getFormalName().compareTo(codingSchemeName) == 0 || css.getLocalName().compareTo(codingSchemeName) == 0) { version = css.getRepresentsVersion(); knt++; if (ltag == null) return css.getRepresentsVersion(); RenderingDetail rd = csr.getRenderingDetail(); CodingSchemeTagList cstl = rd.getVersionTags(); java.lang.String[] tags = cstl.getTag(); if (tags != null && tags.length > 0) { for (int j=0; j<tags.length; j++) { String version_tag = (String) tags[j]; if (version_tag.compareToIgnoreCase(ltag) == 0) { return css.getRepresentsVersion(); } } } } } } catch (Exception e) { e.printStackTrace(); } System.out.println("Version corresponding to tag " + ltag + " is not found " + " in " + codingSchemeName); if (ltag != null && ltag.compareToIgnoreCase("PRODUCTION") == 0 & knt == 1) { System.out.println("\tUse " + version + " as default."); return version; } return null; } public static Vector<String> getVersionListData(String codingSchemeName) { Vector<String> v = new Vector(); try { //RemoteServerUtil rsu = new RemoteServerUtil(); //EVSApplicationService lbSvc = rsu.createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeRenderingList csrl = lbSvc.getSupportedCodingSchemes(); if(csrl == null) System.out.println("csrl is NULL"); CodingSchemeRendering[] csrs = csrl.getCodingSchemeRendering(); for (int i=0; i<csrs.length; i++) { CodingSchemeRendering csr = csrs[i]; Boolean isActive = csr.getRenderingDetail().getVersionStatus().equals(CodingSchemeVersionStatus.ACTIVE); if (isActive != null && isActive.equals(Boolean.TRUE)) { CodingSchemeSummary css = csr.getCodingSchemeSummary(); String formalname = css.getFormalName(); if (formalname.compareTo(codingSchemeName) == 0) { String representsVersion = css.getRepresentsVersion(); v.add(representsVersion); } } } } catch (Exception ex) { } return v; } public static String getFileName(String pathname) { File file = new File(pathname); String filename = file.getName(); return filename; } protected static Association processForAnonomousNodes(Association assoc){ //clone Association except associatedConcepts Association temp = new Association(); temp.setAssociatedData(assoc.getAssociatedData()); temp.setAssociationName(assoc.getAssociationName()); temp.setAssociationReference(assoc.getAssociationReference()); temp.setDirectionalName(assoc.getDirectionalName()); temp.setAssociatedConcepts(new AssociatedConceptList()); for(int i = 0; i < assoc.getAssociatedConcepts().getAssociatedConceptCount(); i++) { //Conditionals to deal with anonymous nodes and UMLS top nodes "V-X" //The first three allow UMLS traversal to top node. //The last two are specific to owl anonymous nodes which can act like false //top nodes. if( assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry() != null && assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry().getIsAnonymous() != null && assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry().getIsAnonymous() != false && !assoc.getAssociatedConcepts().getAssociatedConcept(i).getConceptCode().equals("@") && !assoc.getAssociatedConcepts().getAssociatedConcept(i).getConceptCode().equals("@@") ) { //do nothing } else{ temp.getAssociatedConcepts().addAssociatedConcept(assoc.getAssociatedConcepts().getAssociatedConcept(i)); } } return temp; } public static LocalNameList vector2LocalNameList(Vector<String> v) { if (v == null) return null; LocalNameList list = new LocalNameList(); for (int i=0; i<v.size(); i++) { String vEntry = (String) v.elementAt(i); list.addEntry(vEntry); } return list; } protected static NameAndValueList createNameAndValueList(Vector names, Vector values) { if (names == null) return null; NameAndValueList nvList = new NameAndValueList(); for (int i=0; i<names.size(); i++) { String name = (String) names.elementAt(i); String value = (String) values.elementAt(i); NameAndValue nv = new NameAndValue(); nv.setName(name); if (value != null) { nv.setContent(value); } nvList.addNameAndValue(nv); } return nvList; } protected static CodingScheme getCodingScheme(String codingScheme, CodingSchemeVersionOrTag versionOrTag) throws LBException { CodingScheme cs = null; try { //EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); cs = lbSvc.resolveCodingScheme(codingScheme, versionOrTag); } catch (Exception ex) { ex.printStackTrace(); } return cs; } public static Vector<SupportedProperty> getSupportedProperties(CodingScheme cs) { if (cs == null) return null; Vector<SupportedProperty> v = new Vector<SupportedProperty>(); SupportedProperty[] properties = cs.getMappings().getSupportedProperty(); for (int i=0; i<properties.length; i++) { SupportedProperty sp = (SupportedProperty) properties[i]; v.add(sp); } return v; } public static Vector<String> getSupportedPropertyNames(CodingScheme cs) { Vector w = getSupportedProperties(cs); if (w == null) return null; Vector<String> v = new Vector<String>(); for (int i=0; i<w.size(); i++) { SupportedProperty sp = (SupportedProperty) w.elementAt(i); v.add(sp.getLocalId()); } return v; } public static Vector<String> getSupportedPropertyNames(String codingScheme, String version) { CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (version != null) versionOrTag.setVersion(version); try { CodingScheme cs = getCodingScheme(codingScheme, versionOrTag); return getSupportedPropertyNames(cs); } catch (Exception ex) { } return null; } public static Vector getPropertyNamesByType(Concept concept, String property_type) { Vector v = new Vector(); org.LexGrid.commonTypes.Property[] properties = null; if (property_type.compareToIgnoreCase("GENERIC")== 0) { properties = concept.getProperty(); } else if (property_type.compareToIgnoreCase("PRESENTATION")== 0) { properties = concept.getPresentation(); } /* else if (property_type.compareToIgnoreCase("INSTRUCTION")== 0) { properties = concept.getInstruction(); } */ else if (property_type.compareToIgnoreCase("COMMENT")== 0) { properties = concept.getComment(); } else if (property_type.compareToIgnoreCase("DEFINITION")== 0) { properties = concept.getDefinition(); } if (properties == null || properties.length == 0) return v; for (int i=0; i<properties.length; i++) { Property p = (Property) properties[i]; //v.add(p.getValue().getContent()); v.add(p.getPropertyName()); } return v; } public static Vector getPropertyValues(Concept concept, String property_type, String property_name) { Vector v = new Vector(); org.LexGrid.commonTypes.Property[] properties = null; if (property_type.compareToIgnoreCase("GENERIC")== 0) { properties = concept.getProperty(); } else if (property_type.compareToIgnoreCase("PRESENTATION")== 0) { properties = concept.getPresentation(); } /* else if (property_type.compareToIgnoreCase("INSTRUCTION")== 0) { properties = concept.getInstruction(); } */ else if (property_type.compareToIgnoreCase("COMMENT")== 0) { properties = concept.getComment(); } else if (property_type.compareToIgnoreCase("DEFINITION")== 0) { properties = concept.getDefinition(); } else { System.out.println("WARNING: property_type not found -- " + property_type); } if (properties == null || properties.length == 0) return v; for (int i=0; i<properties.length; i++) { Property p = (Property) properties[i]; if (property_name.compareTo(p.getPropertyName()) == 0) { String t = p.getValue().getContent(); //System.out.println(property_name + ": " + p.getValue().getContent()); Source[] sources = p.getSource(); if (sources != null && sources.length > 0) { //System.out.println("sources.length: " + sources.length); Source src = sources[0]; t = t + "|" + src.getContent(); } else { if (property_name.compareToIgnoreCase("definition") == 0) { System.out.println("*** WARNING: " + property_name + " with no source data: " + p.getValue().getContent()); PropertyQualifier[] qualifiers = p.getPropertyQualifier(); if (qualifiers != null && qualifiers.length > 0) { //System.out.println(property_name + " qualifiers.length: " + qualifiers.length); for (int j=0; j<qualifiers.length; j++) { PropertyQualifier q = qualifiers[j]; String qualifier_name = q.getPropertyQualifierName(); String qualifier_value = q.getValue().getContent(); if (qualifier_name.compareTo("source") == 0) { t = t + "|" + qualifier_value; break; } } } else { System.out.println("*** SOURCE NOT FOUND IN qualifiers neither. "); } } } v.add(t); } } return v; } public List getSupportedRoleNames(LexBIGService lbSvc, String scheme, String version) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); List list = new ArrayList(); try { CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt); Relations[] relations = cs.getRelations(); for (int i=0; i<relations.length; i++) { Relations relation = relations[i]; if (relation.getContainerName().compareToIgnoreCase("roles") == 0) { org.LexGrid.relations.Association[] asso_array = relation.getAssociation(); for (int j=0; j<asso_array.length; j++) { org.LexGrid.relations.Association association = (org.LexGrid.relations.Association) asso_array[j]; list.add(association.getAssociationName()); } } } } catch (Exception ex) { } return list; } public static void sortArray(ArrayList list) { String tmp; if (list.size() <= 1) return; for (int i = 0; i < list.size(); i++) { String s1 = (String) list.get(i); for (int j = i + 1; j < list.size(); j++) { String s2 = (String) list.get(j); if(s1.compareToIgnoreCase(s2 ) > 0 ) { tmp = s1; list.set(i, s2); list.set(j, tmp); } } } } public static void sortArray(String[] strArray) { String tmp; if (strArray.length <= 1) return; for (int i = 0; i < strArray.length; i++) { for (int j = i + 1; j < strArray.length; j++) { if(strArray[i].compareToIgnoreCase(strArray[j] ) > 0 ) { tmp = strArray[i]; strArray[i] = strArray[j]; strArray[j] = tmp; } } } } public String[] getSortedKeys(HashMap map) { if (map == null) return null; Set keyset = map.keySet(); String[] names = new String[keyset.size()]; Iterator it = keyset.iterator(); int i = 0; while (it.hasNext()) { String s = (String) it.next(); names[i] = s; i++; } sortArray(names); return names; } public String getPreferredName(Concept c) { Presentation[] presentations = c.getPresentation(); for (int i=0; i<presentations.length; i++) { Presentation p = presentations[i]; if (p.getPropertyName().compareTo("Preferred_Name") == 0) { return p.getValue().getContent(); } } return null; } public HashMap getRelationshipHashMap(String scheme, String version, String code) { return getRelationshipHashMap(scheme, version, code, null); } protected static String getDirectionalLabel(LexBIGServiceConvenienceMethods lbscm, String scheme, CodingSchemeVersionOrTag csvt, Association assoc, boolean navigatedFwd) throws LBException { String assocLabel = navigatedFwd ? lbscm.getAssociationForwardName(assoc.getAssociationName(), scheme, csvt) : lbscm.getAssociationReverseName(assoc.getAssociationName(), scheme, csvt); if (StringUtils.isBlank(assocLabel)) assocLabel = (navigatedFwd ? "" : "[Inverse]") + assoc.getAssociationName(); return assocLabel; } public LexBIGServiceConvenienceMethods createLexBIGServiceConvenienceMethods(LexBIGService lbSvc) { LexBIGServiceConvenienceMethods lbscm = null; try { lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); } catch (Exception ex) { ex.printStackTrace(); } return lbscm; } public HashMap getRelationshipHashMap(String scheme, String version, String code, String sab) { //EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); // Perform the query ... ResolvedConceptReferenceList matches = null; List list = new ArrayList();//getSupportedRoleNames(lbSvc, scheme, version); ArrayList roleList = new ArrayList(); ArrayList associationList = new ArrayList(); ArrayList superconceptList = new ArrayList(); ArrayList siblingList = new ArrayList(); ArrayList subconceptList = new ArrayList(); ArrayList btList = new ArrayList(); ArrayList ntList = new ArrayList(); Vector parent_asso_vec = new Vector(Arrays.asList(hierAssocToParentNodes_)); Vector child_asso_vec = new Vector(Arrays.asList(hierAssocToChildNodes_)); Vector sibling_asso_vec = new Vector(Arrays.asList(assocToSiblingNodes_)); Vector bt_vec = new Vector(Arrays.asList(assocToBTNodes_)); Vector nt_vec = new Vector(Arrays.asList(assocToNTNodes_)); HashMap map = new HashMap(); try { //LexBIGServiceConvenienceMethods lbscm = createLexBIGServiceConvenienceMethods(lbSvc); /* LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); */ CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); if (sab != null) { cng = cng.restrictToAssociations(null, Constructors.createNameAndValueList(sab, SOURCE)); } int maxToReturn = NCImBrowserProperties.maxToReturn; matches = cng.resolveAsList( ConvenienceMethods.createConceptReference(code, scheme), true, false, 1, 1, noopList_, null, null, null, maxToReturn, false); if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = matches .enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList sourceof = ref.getSourceOf(); Association[] associations = sourceof.getAssociation(); for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = assoc.getAssociationName(); //String associationName = lbscm.getAssociationNameFromAssociationCode(scheme, csvt, assoc.getAssociationName()); AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; EntityDescription ed = ac.getEntityDescription(); String name = "No Description"; if (ed != null) name = ed.getContent(); String pt = name; if (associationName.compareToIgnoreCase("equivalentClass") != 0) { String s = associationName + "|" + pt + "|" + ac.getConceptCode(); if (!parent_asso_vec.contains(associationName) && !child_asso_vec.contains(associationName)) { if (sibling_asso_vec.contains(associationName)) { siblingList.add(s); } else if (bt_vec.contains(associationName)) { btList.add(s); } else if (nt_vec.contains(associationName)) { ntList.add(s); } else { associationList.add(s); } } } } } } } if (roleList.size() > 0) { SortUtils.quickSort(roleList); } if (associationList.size() > 0) { //KLO, 052909 associationList = removeRedundantRelationships(associationList, "RO"); SortUtils.quickSort(associationList); } if (siblingList.size() > 0) { SortUtils.quickSort(siblingList); } if (btList.size() > 0) { SortUtils.quickSort(btList); } if (ntList.size() > 0) { SortUtils.quickSort(ntList); } map.put(TYPE_ROLE, roleList); map.put(TYPE_ASSOCIATION, associationList); map.put(TYPE_SIBLINGCONCEPT, siblingList); map.put(TYPE_BROADERCONCEPT, btList); map.put(TYPE_NARROWERCONCEPT, ntList); Vector superconcept_vec = getSuperconcepts(scheme, version, code); for (int i=0; i<superconcept_vec.size(); i++) { Concept c = (Concept) superconcept_vec.elementAt(i); String pt = c.getEntityDescription().getContent(); superconceptList.add(pt + "|" + c.getEntityCode()); } SortUtils.quickSort(superconceptList); map.put(TYPE_SUPERCONCEPT, superconceptList); Vector subconcept_vec = getSubconcepts(scheme, version, code); for (int i=0; i<subconcept_vec.size(); i++) { Concept c = (Concept) subconcept_vec.elementAt(i); String pt = c.getEntityDescription().getContent(); subconceptList.add(pt + "|" + c.getEntityCode()); } SortUtils.quickSort(subconceptList); map.put(TYPE_SUBCONCEPT, subconceptList); } catch (Exception ex) { ex.printStackTrace(); } return map; } public Vector getSuperconcepts(String scheme, String version, String code) { return getAssociationSources(scheme, version, code, hierAssocToChildNodes_); } public Vector getAssociationSources(String scheme, String version, String code, String[] assocNames) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { //EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier); ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme); boolean resolveForward = false; boolean resolveBackward = true; int resolveAssociationDepth = 1; int maxToReturn = -1; ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator( cng, graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); v = resolveIterator(iterator, maxToReturn, code); } catch (Exception ex) { ex.printStackTrace(); } return v; } public Vector getSubconcepts(String scheme, String version, String code) { return getAssociationTargets(scheme, version, code, hierAssocToChildNodes_); } public Vector getAssociationTargets(String scheme, String version, String code, String[] assocNames) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { //EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier); ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme); boolean resolveForward = true; boolean resolveBackward = false; int resolveAssociationDepth = 1; int maxToReturn = -1; ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator( cng, graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); v = resolveIterator(iterator, maxToReturn, code); } catch (Exception ex) { ex.printStackTrace(); } return v; } public ResolvedConceptReferencesIterator codedNodeGraph2CodedNodeSetIterator( CodedNodeGraph cng, ConceptReference graphFocus, boolean resolveForward, boolean resolveBackward, int resolveAssociationDepth, int maxToReturn) { CodedNodeSet cns = null; try { cns = cng.toNodeList(graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); if (cns == null) { System.out.println("cng.toNodeList returns null???"); return null; } SortOptionList sortCriteria = null; //Constructors.createSortOptionList(new String[]{"matchToQuery", "code"}); LocalNameList propertyNames = null; CodedNodeSet.PropertyType[] propertyTypes = null; ResolvedConceptReferencesIterator iterator = null; try { iterator = cns.resolve(sortCriteria, propertyNames, propertyTypes); } catch (Exception e) { e.printStackTrace(); } if(iterator == null) { System.out.println("cns.resolve returns null???"); } return iterator; } catch (Exception ex) { ex.printStackTrace(); return null; } } public Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn) { return resolveIterator(iterator, maxToReturn, null); } public Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn, String code) { Vector v = new Vector(); if (iterator == null) { System.out.println("No match."); return v; } try { int iteration = 0; while (iterator.hasNext()) { iteration++; iterator = iterator.scroll(maxToReturn); ResolvedConceptReferenceList rcrl = iterator.getNext(); ResolvedConceptReference[] rcra = rcrl.getResolvedConceptReference(); for (int i=0; i<rcra.length; i++) { ResolvedConceptReference rcr = rcra[i]; org.LexGrid.concepts.Concept ce = rcr.getReferencedEntry(); if (code == null) { v.add(ce); } else { if (ce.getEntityCode().compareTo(code) != 0) v.add(ce); } } } } catch (Exception e) { e.printStackTrace(); } return v; } public static Vector<String> parseData(String line, String tab) { Vector data_vec = new Vector(); StringTokenizer st = new StringTokenizer(line, tab); while (st.hasMoreTokens()) { String value = st.nextToken(); if (value.compareTo("null") == 0) value = " "; data_vec.add(value); } return data_vec; } public static String getHyperlink(String url, String codingScheme, String code) { codingScheme = codingScheme.replace(" ", "%20"); String link = url + "/ConceptReport.jsp?dictionary=" + codingScheme + "&code=" + code; return link; } public List getHierarchyRoots( String scheme, String version, String hierarchyID) throws LBException { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); return getHierarchyRoots(scheme, csvt, hierarchyID); } public List getHierarchyRoots( String scheme, CodingSchemeVersionOrTag csvt, String hierarchyID) throws LBException { int maxDepth = 1; LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); ResolvedConceptReferenceList roots = lbscm.getHierarchyRoots(scheme, csvt, hierarchyID); List list = ResolvedConceptReferenceList2List(roots); SortUtils.quickSort(list); return list; } public List ResolvedConceptReferenceList2List(ResolvedConceptReferenceList rcrl) { ArrayList list = new ArrayList(); for (int i=0; i<rcrl.getResolvedConceptReferenceCount(); i++) { ResolvedConceptReference rcr = rcrl.getResolvedConceptReference(i); list.add(rcr); } return list; } public static Vector getSynonyms(String scheme, String version, String tag, String code, String sab) { Concept concept = getConceptByCode(scheme, version, tag, code); return getSynonyms(concept, sab); } public static Vector getSynonyms(String scheme, String version, String tag, String code) { Concept concept = getConceptByCode(scheme, version, tag, code); return getSynonyms(concept, null); } public static Vector getSynonyms(Concept concept) { return getSynonyms(concept, null); } public static Vector getSynonyms(Concept concept, String sab) { if (concept == null) return null; Vector v = new Vector(); Presentation[] properties = concept.getPresentation(); int n = 0; for (int i=0; i<properties.length; i++) { Presentation p = properties[i]; // name String term_name = p.getValue().getContent(); String term_type = "null"; String term_source = "null"; String term_source_code = "null"; // source-code PropertyQualifier[] qualifiers = p.getPropertyQualifier(); if (qualifiers != null) { for (int j=0; j<qualifiers.length; j++) { PropertyQualifier q = qualifiers[j]; String qualifier_name = q.getPropertyQualifierName(); String qualifier_value = q.getValue().getContent(); if (qualifier_name.compareTo("source-code") == 0) { term_source_code = qualifier_value; break; } } } // term type term_type = p.getRepresentationalForm(); // source Source[] sources = p.getSource(); if (sources != null && sources.length > 0) { Source src = sources[0]; term_source = src.getContent(); } String t = null; if (sab == null) { t = term_name + "|" + term_type + "|" + term_source + "|" + term_source_code; v.add(t); } else if (term_source != null && sab.compareTo(term_source) == 0) { t = term_name + "|" + term_type + "|" + term_source + "|" + term_source_code; v.add(t); } } SortUtils.quickSort(v); return v; } public String getNCICBContactURL() { if (NCICBContactURL != null) { return NCICBContactURL; } String default_url = "ncicb@pop.nci.nih.gov"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); NCICBContactURL = properties.getProperty(NCImBrowserProperties.NCICB_CONTACT_URL); if (NCICBContactURL == null) { NCICBContactURL = default_url; } } catch (Exception ex) { } System.out.println("getNCICBContactURL returns " + NCICBContactURL); return NCICBContactURL; } public String getTerminologySubsetDownloadURL() { NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); terminologySubsetDownloadURL = properties.getProperty(NCImBrowserProperties.TERMINOLOGY_SUBSET_DOWNLOAD_URL); } catch (Exception ex) { } return terminologySubsetDownloadURL; } public String getNCIMBuildInfo() { if (NCIMBuildInfo != null) { return NCIMBuildInfo; } String default_info = "N/A"; NCImBrowserProperties properties = null; try { properties = NCImBrowserProperties.getInstance(); NCIMBuildInfo = properties.getProperty(NCImBrowserProperties.NCIM_BUILD_INFO); if (NCIMBuildInfo == null) { NCIMBuildInfo = default_info; } } catch (Exception ex) { } System.out.println("getNCIMBuildInfo returns " + NCIMBuildInfo); return NCIMBuildInfo; } public static Vector<String> getMatchTypeListData(String codingSchemeName, String version) { Vector<String> v = new Vector<String>(); v.add("String"); v.add("Code"); v.add("CUI"); return v; } public static Vector getSources(String scheme, String version, String tag, String code) { Vector sources = getSynonyms(scheme, version, tag, code); //GLIOBLASTOMA MULTIFORME|DI|DXP|U000721 HashSet hset = new HashSet(); Vector source_vec = new Vector(); for (int i=0; i<sources.size(); i++) { String s = (String) sources.elementAt(i); Vector ret_vec = DataUtils.parseData(s, "|"); String name = (String) ret_vec.elementAt(0); String type = (String) ret_vec.elementAt(1); String src = (String) ret_vec.elementAt(2); String srccode = (String) ret_vec.elementAt(3); if (!hset.contains(src)) { hset.add(src); source_vec.add(src); } } SortUtils.quickSort(source_vec); return source_vec; } public static boolean containSource(Vector sources, String source) { if (sources == null || sources.size() == 0) return false; String s = null; for (int i=0; i<sources.size(); i++) { s = (String) sources.elementAt(i); if (s.compareTo(source) == 0) return true; } return false; } public Vector getAssociatedConcepts(String scheme, String version, String code, String sab) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); //NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(null, Constructors.createNameAndValueList(sab, SOURCE)); ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme); boolean resolveForward = true; boolean resolveBackward = true; int resolveAssociationDepth = 1; int maxToReturn = -1; ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator( cng, graphFocus, resolveForward, resolveBackward, resolveAssociationDepth, maxToReturn); v = resolveIterator(iterator, maxToReturn, code); } catch (Exception ex) { ex.printStackTrace(); } SortUtils.quickSort(v); return v; } protected boolean isValidForSAB(AssociatedConcept ac, String sab) { for (NameAndValue qualifier : ac.getAssociationQualifiers().getNameAndValue()) if (SOURCE.equalsIgnoreCase(qualifier.getContent()) && sab.equalsIgnoreCase(qualifier.getName())) return true; return false; } public Vector sortSynonyms(Vector synonyms, String sortBy) { if (sortBy == null) sortBy = "name"; HashMap hmap = new HashMap(); Vector key_vec = new Vector(); String delim = " "; for (int n=0; n<synonyms.size(); n++) { String s = (String) synonyms.elementAt(n); Vector synonym_data = DataUtils.parseData(s, "|"); String term_name = (String) synonym_data.elementAt(0); String term_type = (String) synonym_data.elementAt(1); String term_source = (String) synonym_data.elementAt(2); String term_source_code = (String) synonym_data.elementAt(3); String key = term_name + delim + term_source + delim + term_source_code + delim + term_type; if (sortBy.compareTo("type") == 0) key = term_type + delim + term_name + delim + term_source + delim + term_source_code; if (sortBy.compareTo("source") == 0) key = term_source + delim + term_name + delim + term_source_code + delim + term_type; if (sortBy.compareTo("code") == 0) key = term_source_code + delim + term_name + delim + term_source + delim + term_type; hmap.put(key, s); key_vec.add(key); } key_vec = SortUtils.quickSort(key_vec); Vector v = new Vector(); for (int i=0; i<key_vec.size(); i++) { String s = (String) key_vec.elementAt(i); v.add((String) hmap.get(s)); } return v; } /* public Vector sortSynonymDataByRel(Vector synonyms) { Vector parent_asso_vec = new Vector(Arrays.asList(hierAssocToParentNodes_)); Vector child_asso_vec = new Vector(Arrays.asList(hierAssocToChildNodes_)); Vector sibling_asso_vec = new Vector(Arrays.asList(assocToSiblingNodes_)); Vector bt_vec = new Vector(Arrays.asList(assocToBTNodes_)); Vector nt_vec = new Vector(Arrays.asList(assocToNTNodes_)); HashMap hmap = new HashMap(); Vector key_vec = new Vector(); String key = null; for (int n=0; n<synonyms.size(); n++) { String s = (String) synonyms.elementAt(n); Vector synonym_data = DataUtils.parseData(s, "|"); String term_name = (String) synonym_data.elementAt(0); String term_type = (String) synonym_data.elementAt(1); String term_source = (String) synonym_data.elementAt(2); String term_source_code = (String) synonym_data.elementAt(3); String cui = (String) synonym_data.elementAt(4); String rel = (String) synonym_data.elementAt(5); String category = "0"; if (parent_asso_vec.contains(rel)) category = "1"; else if (child_asso_vec.contains(rel)) category = "2"; else if (bt_vec.contains(rel)) category = "3"; else if (nt_vec.contains(rel)) category = "4"; else if (sibling_asso_vec.contains(rel)) category = "5"; else category = "6"; key = category + rel + term_name + term_source_code; hmap.put(key, s); key_vec.add(key); } key_vec = SortUtils.quickSort(key_vec); Vector v = new Vector(); for (int i=0; i<key_vec.size(); i++) { String s = (String) key_vec.elementAt(i); v.add((String) hmap.get(s)); } return v; } */ //ResolvedConceptReferenceList resolveAsList(ConceptReference graphFocus, boolean resolveForward, boolean resolveBackward, int resolveCodedEntryDepth, int resolveAssociationDepth, LocalNameList propertyNames, CodedNodeSet.PropertyType[] propertyTypes, SortOptionList sortOptions, int maxToReturn) public static HashMap getAssociatedConceptsHashMap(String codingSchemeName, String vers, String code, String source) { return getAssociatedConceptsHashMap(codingSchemeName, vers, code, source, 1); } public static HashMap getAssociatedConceptsHashMap(String codingSchemeName, String vers, String code, String source, int resolveCodedEntryDepth) { HashMap hmap = new HashMap(); try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); if (lbSvc == null) { System.out.println("lbSvc == null???"); return hmap; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (vers != null) versionOrTag.setVersion(vers); CodedNodeGraph cng = lbSvc.getNodeGraph(codingSchemeName, null, null); if (source != null) { cng = cng.restrictToAssociations( Constructors.createNameAndValueList(META_ASSOCIATIONS), Constructors.createNameAndValueList("source", source)); } CodedNodeSet.PropertyType[] propertyTypes = new CodedNodeSet.PropertyType[1]; propertyTypes[0] = PropertyType.PRESENTATION; ResolvedConceptReferenceList matches = cng.resolveAsList(Constructors.createConceptReference(code, codingSchemeName), true, false, resolveCodedEntryDepth, 1, null, propertyTypes, null, -1); if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = matches .enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList sourceof = ref.getSourceOf(); if (sourceof != null ) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = lbscm.getAssociationNameFromAssociationCode(codingSchemeName, versionOrTag, assoc.getAssociationName()); Vector v = new Vector(); AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; if (associationName.compareToIgnoreCase("equivalentClass") != 0) { v.add(ac); } } hmap.put(associationName, v); } } } } } cng = lbSvc.getNodeGraph(codingSchemeName, null, null); if (source != null) { cng = cng.restrictToAssociations( Constructors.createNameAndValueList(MetaTreeUtils.hierAssocToChildNodes_), Constructors.createNameAndValueList("source", source)); } else { cng = cng.restrictToAssociations( Constructors.createNameAndValueList(MetaTreeUtils.hierAssocToChildNodes_), null); } matches = cng.resolveAsList(Constructors.createConceptReference(code, codingSchemeName), false, true, resolveCodedEntryDepth, 1, null, propertyTypes, null, -1); if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = matches .enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList sourceof = ref.getTargetOf(); if (sourceof != null ) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = lbscm.getAssociationNameFromAssociationCode(codingSchemeName, versionOrTag, assoc.getAssociationName()); Vector v = new Vector(); AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; if (associationName.compareToIgnoreCase("equivalentClass") != 0) { v.add(ac); } } if (associationName.compareTo("CHD") == 0) { associationName = "PAR"; } hmap.put(associationName, v); } } } } } } catch (Exception ex) { } return hmap; } public static HashMap getRelatedConceptsHashMap(String codingSchemeName, String vers, String code, String source) { return getRelatedConceptsHashMap(codingSchemeName, vers, code, source, 1); } public static HashMap getRelatedConceptsHashMap(String codingSchemeName, String vers, String code, String source, int resolveCodedEntryDepth) { HashMap hmap = new HashMap(); try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); if (lbSvc == null) { Debug.println("lbSvc == null???"); return hmap; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (vers != null) versionOrTag.setVersion(vers); CodedNodeGraph cng = lbSvc.getNodeGraph(codingSchemeName, null, null); if (source != null) { cng = cng.restrictToAssociations( Constructors.createNameAndValueList(META_ASSOCIATIONS), Constructors.createNameAndValueList("source", source)); } CodedNodeSet.PropertyType[] propertyTypes = new CodedNodeSet.PropertyType[1]; propertyTypes[0] = PropertyType.PRESENTATION; ResolvedConceptReferenceList matches = cng.resolveAsList(Constructors.createConceptReference(code, codingSchemeName), true, true, resolveCodedEntryDepth, 1, null, propertyTypes, null, -1); if (matches != null) { java.lang.Boolean incomplete = matches.getIncomplete(); //System.out.println("(*) Number of matches: " + matches.getResolvedConceptReferenceCount()); //System.out.println("(*) Incomplete? " + incomplete); hmap.put(INCOMPLETE, incomplete.toString()); } if (matches.getResolvedConceptReferenceCount() > 0) { Enumeration<ResolvedConceptReference> refEnum = matches .enumerateResolvedConceptReference(); while (refEnum.hasMoreElements()) { ResolvedConceptReference ref = refEnum.nextElement(); AssociationList sourceof = ref.getSourceOf(); if (sourceof != null ) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = lbscm.getAssociationNameFromAssociationCode(codingSchemeName, versionOrTag, assoc.getAssociationName()); String associationName0 = associationName; String directionalLabel = associationName; boolean navigatedFwd = true; try { directionalLabel = getDirectionalLabel(lbscm, codingSchemeName, versionOrTag, assoc, navigatedFwd); } catch (Exception e) { Debug.println("(*) getDirectionalLabel throws exceptions: " + directionalLabel); } Vector v = new Vector(); AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; String asso_label = associationName; String qualifier_name = null; String qualifier_value = null; if (associationName.compareToIgnoreCase("equivalentClass") != 0) { for(NameAndValue qual : ac.getAssociationQualifiers().getNameAndValue()){ qualifier_name = qual.getName(); qualifier_value = qual.getContent(); if (qualifier_name.compareToIgnoreCase("rela") == 0) { asso_label = qualifier_value; // replace associationName by Rela value break; } } Vector w = null; String asso_key = directionalLabel + "|" + asso_label; if (hmap.containsKey(asso_key)) { w = (Vector) hmap.get(asso_key); } else { w = new Vector(); } w.add(ac); hmap.put(asso_key, w); } } } } } sourceof = ref.getTargetOf(); if (sourceof != null ) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; String associationName = lbscm.getAssociationNameFromAssociationCode(codingSchemeName, versionOrTag, assoc.getAssociationName()); String associationName0 = associationName; if (associationName.compareTo("CHD") == 0 || associationName.compareTo("RB") == 0) { String directionalLabel = associationName; boolean navigatedFwd = false; try { directionalLabel = getDirectionalLabel(lbscm, codingSchemeName, versionOrTag, assoc, navigatedFwd); //Debug.println("(**) directionalLabel: associationName " + associationName + " directionalLabel: " + directionalLabel); } catch (Exception e) { Debug.println("(**) getDirectionalLabel throws exceptions: " + directionalLabel); } Vector v = new Vector(); AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept(); for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; String asso_label = associationName; String qualifier_name = null; String qualifier_value = null; if (associationName.compareToIgnoreCase("equivalentClass") != 0) { for(NameAndValue qual : ac.getAssociationQualifiers().getNameAndValue()){ qualifier_name = qual.getName(); qualifier_value = qual.getContent(); if (qualifier_name.compareToIgnoreCase("rela") == 0) { //associationName = qualifier_value; // replace associationName by Rela value asso_label = qualifier_value; break; } } Vector w = null; String asso_key = directionalLabel + "|" + asso_label; if (hmap.containsKey(asso_key)) { w = (Vector) hmap.get(asso_key); } else { w = new Vector(); } w.add(ac); hmap.put(asso_key, w); } } } } } } } } } catch (Exception ex) { } return hmap; } private String findRepresentativeTerm(Concept c, String sab) { Vector synonyms = getSynonyms(c, sab); if(synonyms == null || synonyms.size() == 0) { //return null; //t = term_name + "|" + term_type + "|" + term_source + "|" + term_source_code; return c.getEntityDescription().getContent() + "|" + Constants.EXTERNAL_TERM_TYPE + "|" + Constants.EXTERNAL_TERM_SOURCE + "|" + Constants.EXTERNAL_TERM_SOURCE_CODE; } return NCImBrowserProperties.getHighestTermGroupRank(synonyms); } String getAssociationDirectionalName(LexBIGServiceConvenienceMethods lbscm, String scheme, CodingSchemeVersionOrTag csvt, String associationName, boolean navigatedFwd) { String assocLabel = null; try { assocLabel = navigatedFwd ? lbscm.getAssociationForwardName(associationName, scheme, csvt) : lbscm.getAssociationReverseName(associationName, scheme, csvt); } catch (Exception ex) { } return assocLabel; } // Method for populating By Source tab relationships table public Vector getNeighborhoodSynonyms(String scheme, String version, String code, String sab) { Debug.println("(*) getNeighborhoodSynonyms ..." + sab); Vector parent_asso_vec = new Vector(Arrays.asList(hierAssocToParentNodes_)); Vector child_asso_vec = new Vector(Arrays.asList(hierAssocToChildNodes_)); Vector sibling_asso_vec = new Vector(Arrays.asList(assocToSiblingNodes_)); Vector bt_vec = new Vector(Arrays.asList(assocToBTNodes_)); Vector nt_vec = new Vector(Arrays.asList(assocToNTNodes_)); Vector w = new Vector(); HashSet hset = new HashSet(); long ms = System.currentTimeMillis(), delay=0; String action = "Retrieving distance-one relationships from the server"; //HashMap hmap = getAssociatedConceptsHashMap(scheme, version, code, sab); HashMap hmap = getRelatedConceptsHashMap(scheme, version, code, sab); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); Set keyset = hmap.keySet(); Iterator it = keyset.iterator(); HashSet rel_hset = new HashSet(); HashSet hasSubtype_hset = new HashSet(); long ms_categorization_delay = 0; long ms_categorization; long ms_find_highest_rank_atom_delay = 0; long ms_find_highest_rank_atom; long ms_remove_RO_delay = 0; long ms_remove_RO; long ms_all_delay = 0; long ms_all; ms_all = System.currentTimeMillis(); while (it.hasNext()) { ms_categorization = System.currentTimeMillis(); String rel_rela = (String) it.next(); if (rel_rela.compareTo(INCOMPLETE) != 0) { Vector u = DataUtils.parseData(rel_rela, "|"); String rel = (String) u.elementAt(0); String rela = (String) u.elementAt(1); String category = "Other"; if (parent_asso_vec.contains(rel)) category = "Parent"; else if (child_asso_vec.contains(rel)) category = "Child"; else if (bt_vec.contains(rel)) category = "Broader"; else if (nt_vec.contains(rel)) category = "Narrower"; else if (sibling_asso_vec.contains(rel)) category = "Sibling"; ms_categorization_delay = ms_categorization_delay + (System.currentTimeMillis() - ms_categorization); //Vector v = (Vector) hmap.get(rel); //Vector v = (Vector) hmap.get(rel_rela); Object obj = hmap.get(rel_rela); if (obj != null) { Vector v = (Vector) obj; // For each related concept: for (int i=0; i<v.size(); i++) { AssociatedConcept ac = (AssociatedConcept) v.elementAt(i); EntityDescription ed = ac.getEntityDescription(); Concept c = ac.getReferencedEntry(); if (!hset.contains(c.getEntityCode())) { hset.add(c.getEntityCode()); // Find the highest ranked atom data ms_find_highest_rank_atom = System.currentTimeMillis(); String t = findRepresentativeTerm(c, sab); ms_find_highest_rank_atom_delay = ms_find_highest_rank_atom_delay + (System.currentTimeMillis() - ms_find_highest_rank_atom); //t = t + "|" + c.getEntityCode() + "|" + rel + "|" + category; t = t + "|" + c.getEntityCode() + "|" + rela + "|" + category; w.add(t); // Temporarily save non-RO other relationships if(category.compareTo("Other") == 0 && category.compareTo("RO") != 0) { if (rel_hset.contains(c.getEntityCode())) { rel_hset.add(c.getEntityCode()); } } if(category.compareTo("Child") == 0 && category.compareTo("CHD") != 0) { if (hasSubtype_hset.contains(c.getEntityCode())) { hasSubtype_hset.add(c.getEntityCode()); } } } } } } } Vector u = new Vector(); // Remove redundant RO relationships for (int i=0; i<w.size(); i++) { String s = (String) w.elementAt(i); Vector<String> v = parseData(s, "|"); if (v.size() >=5) { String associationName = v.elementAt(5); if (associationName.compareTo("RO") != 0) { u.add(s); } else { String associationTargetCode = v.elementAt(4); if (!rel_hset.contains(associationTargetCode)) { u.add(s); } } } } // Remove redundant CHD relationships for (int i=0; i<w.size(); i++) { String s = (String) w.elementAt(i); Vector<String> v = parseData(s, "|"); if (v.size() >=5) { String associationName = v.elementAt(5); if (associationName.compareTo("CHD") != 0) { u.add(s); } else { String associationTargetCode = v.elementAt(4); if (!rel_hset.contains(associationTargetCode)) { u.add(s); } } } } ms_all_delay = System.currentTimeMillis() - ms_all; action = "categorizing relationships into six categories"; Debug.println("Run time (ms) for " + action + " " + ms_categorization_delay); DBG.debugDetails(ms_categorization_delay, action, "getNeighborhoodSynonyms"); action = "finding highest ranked atoms"; Debug.println("Run time (ms) for " + action + " " + ms_find_highest_rank_atom_delay); DBG.debugDetails(ms_find_highest_rank_atom_delay, action, "getNeighborhoodSynonyms"); ms_remove_RO_delay = ms_all_delay - ms_categorization_delay - ms_find_highest_rank_atom_delay; action = "removing redundant RO relationships"; Debug.println("Run time (ms) for " + action + " " + ms_remove_RO_delay); DBG.debugDetails(ms_remove_RO_delay, action, "getNeighborhoodSynonyms"); // Initial sort (refer to sortSynonymData method for sorting by a specific column) long ms_sort_delay = System.currentTimeMillis(); u = removeRedundantRecords(u); SortUtils.quickSort(u); action = "initial sorting"; delay = System.currentTimeMillis() - ms_sort_delay; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getNeighborhoodSynonyms"); DBG.debugDetails("Max Return", NCImBrowserProperties.maxToReturn); return u; } public static String getRelationshipCode(String id) { if (id.compareTo("Parent") == 0) return "1"; else if (id.compareTo("Child") == 0) return "2"; else if (id.compareTo("Broader") == 0) return "3"; else if (id.compareTo("Narrower") == 0) return "4"; else if (id.compareTo("Sibling") == 0) return "5"; else return "6"; } public static boolean containsAllUpperCaseChars(String s) { for (int i=0; i<s.length(); i++) { char ch = s.charAt(i); if (ch < 65 || ch > 90) return false; } return true; } public static Vector sortSynonymData(Vector synonyms, String sortBy) { if (sortBy == null) sortBy = "name"; HashMap hmap = new HashMap(); Vector key_vec = new Vector(); String delim = " "; for (int n=0; n<synonyms.size(); n++) { String s = (String) synonyms.elementAt(n); Vector synonym_data = DataUtils.parseData(s, "|"); String term_name = (String) synonym_data.elementAt(0); String term_type = (String) synonym_data.elementAt(1); String term_source = (String) synonym_data.elementAt(2); String term_source_code = (String) synonym_data.elementAt(3); String cui = (String) synonym_data.elementAt(4); String rel = (String) synonym_data.elementAt(5); String rel_type = (String) synonym_data.elementAt(6); String rel_type_str = getRelationshipCode(rel_type); String key = term_name + delim + term_type + delim + term_source + delim + term_source_code +delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("type") == 0) key = term_type +delim + term_name + delim + term_source + delim + term_source_code + delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("source") == 0) key = term_source +delim + term_name + delim + term_type + delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("code") == 0) key = term_source_code + delim + term_name + delim + term_type + delim + term_source + delim + cui + delim + rel + delim + rel_type_str; if (sortBy.compareTo("rel") == 0) { String rel_key = rel; if (containsAllUpperCaseChars(rel)) rel_key = "|"; key = rel + term_name + delim + term_type + delim + term_source + delim + term_source_code +delim + cui + delim + rel_type_str; } if (sortBy.compareTo("cui") == 0) key = cui + term_name + delim + term_type + delim + term_source + delim + term_source_code +delim + rel + delim + rel_type_str; if (sortBy.compareTo("rel_type") == 0) key = rel_type_str + delim + rel + delim + term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + cui; hmap.put(key, s); key_vec.add(key); } key_vec = SortUtils.quickSort(key_vec); Vector v = new Vector(); for (int i=0; i<key_vec.size(); i++) { String s = (String) key_vec.elementAt(i); v.add((String) hmap.get(s)); } return v; } //KLO, 052909 private ArrayList removeRedundantRelationships(ArrayList associationList, String rel) { ArrayList a = new ArrayList(); HashSet target_set = new HashSet(); for (int i=0; i<associationList.size(); i++) { String s = (String) associationList.get(i); Vector<String> w = parseData(s, "|"); String associationName = w.elementAt(0); if (associationName.compareTo(rel) != 0) { String associationTargetCode = w.elementAt(2); target_set.add(associationTargetCode); } } for (int i=0; i<associationList.size(); i++) { String s = (String) associationList.get(i); Vector<String> w = parseData(s, "|"); String associationName = w.elementAt(0); if (associationName.compareTo(rel) != 0) { a.add(s); } else { String associationTargetCode = w.elementAt(2); if (!target_set.contains(associationTargetCode)) { a.add(s); } } } return a; } public static Vector sortRelationshipData(Vector relationships, String sortBy) { if (sortBy == null) sortBy = "name"; HashMap hmap = new HashMap(); Vector key_vec = new Vector(); String delim = " "; for (int n=0; n<relationships.size(); n++) { String s = (String) relationships.elementAt(n); Vector ret_vec = DataUtils.parseData(s, "|"); String relationship_name = (String) ret_vec.elementAt(0); String target_concept_name = (String) ret_vec.elementAt(1); String target_concept_code = (String) ret_vec.elementAt(2); String rel_sab = (String) ret_vec.elementAt(3); String key = target_concept_name + delim + relationship_name + delim + target_concept_code + delim + rel_sab; if (sortBy.compareTo("source") == 0) { key = rel_sab + delim + target_concept_name + delim + relationship_name + delim + target_concept_code; } else if (sortBy.compareTo("rela") == 0) { key = relationship_name + delim + target_concept_name + delim + target_concept_code + delim + rel_sab; } else if (sortBy.compareTo("code") == 0) { key = target_concept_code + delim + target_concept_name + delim + relationship_name + delim + rel_sab; } hmap.put(key, s); key_vec.add(key); } key_vec = SortUtils.quickSort(key_vec); Vector v = new Vector(); for (int i=0; i<key_vec.size(); i++) { String s = (String) key_vec.elementAt(i); v.add((String) hmap.get(s)); } return v; } public void removeRedundantRecords(HashMap hmap) { Set keyset = hmap.keySet(); Iterator it = keyset.iterator(); while (it.hasNext()) { String rel = (String) it.next(); Vector v = (Vector) hmap.get(rel); HashSet hset = new HashSet(); Vector u = new Vector(); for (int k=0; k<v.size(); k++) { String t = (String) v.elementAt(k); if (!hset.contains(t)) { u.add(t); hset.add(t); } } hmap.put(rel, u); } } public Vector removeRedundantRecords(Vector v) { HashSet hset = new HashSet(); Vector u = new Vector(); for (int k=0; k<v.size(); k++) { String t = (String) v.elementAt(k); if (!hset.contains(t)) { u.add(t); hset.add(t); } } return u; } public HashMap getAssociationTargetHashMap(String scheme, String version, String code, Vector sort_option) { Debug.println("(*) DataUtils getAssociationTargetHashMap "); Vector parent_asso_vec = new Vector(Arrays.asList(hierAssocToParentNodes_)); Vector child_asso_vec = new Vector(Arrays.asList(hierAssocToChildNodes_)); Vector sibling_asso_vec = new Vector(Arrays.asList(assocToSiblingNodes_)); Vector bt_vec = new Vector(Arrays.asList(assocToBTNodes_)); Vector nt_vec = new Vector(Arrays.asList(assocToNTNodes_)); Vector category_vec = new Vector(Arrays.asList(relationshipCategories_)); HashMap rel_hmap = new HashMap(); for (int k=0; k<category_vec.size(); k++) { String category = (String) category_vec.elementAt(k); Vector vec = new Vector(); rel_hmap.put(category, vec); } Vector w = new Vector(); HashSet hset = new HashSet(); long ms = System.currentTimeMillis(), delay=0; String action = "Retrieving all relationships from the server"; HashMap hmap = getRelatedConceptsHashMap(scheme, version, code, null, 0); // resolveCodedEntryDepth = 0; delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); Set keyset = hmap.keySet(); Iterator it = keyset.iterator(); // Categorize relationships into six categories and find association source data ms = System.currentTimeMillis(); action = "Categorizing relationships into six categories; finding source data for each relationship"; while (it.hasNext()) { String rel_rela = (String) it.next(); if (rel_rela.compareTo(INCOMPLETE) != 0) { Vector u = DataUtils.parseData(rel_rela, "|"); String rel = (String) u.elementAt(0); String rela = (String) u.elementAt(1); String category = "Other"; if (parent_asso_vec.contains(rel)) category = "Parent"; else if (child_asso_vec.contains(rel)) category = "Child"; else if (bt_vec.contains(rel)) category = "Broader"; else if (nt_vec.contains(rel)) category = "Narrower"; else if (sibling_asso_vec.contains(rel)) category = "Sibling"; Vector v = (Vector) hmap.get(rel_rela); for (int i=0; i<v.size(); i++) { AssociatedConcept ac = (AssociatedConcept) v.elementAt(i); EntityDescription ed = ac.getEntityDescription(); String source = "unspecified"; for (NameAndValue qualifier : ac.getAssociationQualifiers().getNameAndValue()) { if (SOURCE.equalsIgnoreCase(qualifier.getName())) { source = qualifier.getContent(); w = (Vector) rel_hmap.get(category); if (w == null) { w = new Vector(); } String str = rela + "|" + ac.getEntityDescription().getContent() + "|" + ac.getCode() + "|" + source; if (!w.contains(str)) { w.add(str); rel_hmap.put(category, w); } } } } } } delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); // Remove redundant RO relationships ms = System.currentTimeMillis(); action = "Removing redundant RO and CHD relationships"; HashSet other_hset = new HashSet(); Vector w2 = (Vector) rel_hmap.get("Other"); for (int k=0; k<w2.size(); k++) { String s = (String) w2.elementAt(k); //System.out.println("(*) getAssociationTargetHashMap s " + s); Vector ret_vec = DataUtils.parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); String t = name + "|" + target_code + "|" + src; if (rel.compareTo("RO") != 0 && !other_hset.contains(t)) { other_hset.add(t); } } Vector w3 = new Vector(); for (int k=0; k<w2.size(); k++) { String s = (String) w2.elementAt(k); Vector ret_vec = DataUtils.parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); if (rel.compareTo("RO") != 0) { w3.add(s); } else { String t = name + "|" + target_code + "|" + src; if (!other_hset.contains(t)) { w3.add(s); } } } rel_hmap.put("Other", w3); other_hset = new HashSet(); w2 = (Vector) rel_hmap.get("Child"); for (int k=0; k<w2.size(); k++) { String s = (String) w2.elementAt(k); //System.out.println("(*) getAssociationTargetHashMap s " + s); Vector ret_vec = DataUtils.parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); String t = name + "|" + target_code + "|" + src; if (rel.compareTo("CHD") != 0 && !other_hset.contains(t)) { other_hset.add(t); } } w3 = new Vector(); for (int k=0; k<w2.size(); k++) { String s = (String) w2.elementAt(k); //System.out.println("(*) getAssociationTargetHashMap s " + s); Vector ret_vec = DataUtils.parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); if (rel.compareTo("CHD") != 0) { w3.add(s); } else { String t = name + "|" + target_code + "|" + src; if (!other_hset.contains(t)) { w3.add(s); } } } rel_hmap.put("Child", w3); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); ms = System.currentTimeMillis(); action = "Sorting relationships by sort options (columns)"; // Sort relationships by sort options (columns) if (sort_option == null) { for (int k=0; k<category_vec.size(); k++) { String category = (String) category_vec.elementAt(k); w = (Vector) rel_hmap.get(category); SortUtils.quickSort(w); rel_hmap.put(category, w); } } else { for (int k=0; k<category_vec.size(); k++) { String category = (String) category_vec.elementAt(k); w = (Vector) rel_hmap.get(category); String sortOption = (String) sort_option.elementAt(k); //SortUtils.quickSort(w); w = sortRelationshipData(w, sortOption); rel_hmap.put(category, w); } } delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); removeRedundantRecords(rel_hmap); String incomplete = (String) hmap.get(INCOMPLETE); if (incomplete != null) rel_hmap.put(INCOMPLETE, incomplete); return rel_hmap; } public HashMap getAssociationTargetHashMap(String scheme, String version, String code) { return getAssociationTargetHashMap(scheme, version, code, null); } public HashMap getAssociationTargetHashMap(String CUI, Vector sort_option) { Debug.println("(*) DataUtils getAssociationTargetHashMap "); List<String> par_chd_assoc_list = new ArrayList(); par_chd_assoc_list.add("CHD"); par_chd_assoc_list.add("RB"); Vector parent_asso_vec = new Vector(Arrays.asList(hierAssocToParentNodes_)); Vector child_asso_vec = new Vector(Arrays.asList(hierAssocToChildNodes_)); Vector sibling_asso_vec = new Vector(Arrays.asList(assocToSiblingNodes_)); Vector bt_vec = new Vector(Arrays.asList(assocToBTNodes_)); Vector nt_vec = new Vector(Arrays.asList(assocToNTNodes_)); Vector category_vec = new Vector(Arrays.asList(relationshipCategories_)); HashMap rel_hmap = new HashMap(); for (int k=0; k<category_vec.size(); k++) { String category = (String) category_vec.elementAt(k); Vector vec = new Vector(); rel_hmap.put(category, vec); } Vector w = new Vector(); long ms0 = System.currentTimeMillis(), delay=0; String action0 = "Retrieving all relationships from the server"; long ms; String action = null; Map<String,List<RelationshipTabResults>> map = null; Map<String,List<RelationshipTabResults>> map2 = null; LexBIGService lbs = RemoteServerUtil.createLexBIGService(); MetaBrowserService mbs = null; try { mbs = (MetaBrowserService)lbs.getGenericExtension("metabrowser-extension"); ms = System.currentTimeMillis(); action = "Retrieving " + SOURCE_OF; ms = System.currentTimeMillis(); map = mbs.getRelationshipsDisplay(CUI, null, Direction.SOURCEOF); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); ms = System.currentTimeMillis(); action = "Retrieving " + TARGET_OF; ms = System.currentTimeMillis(); map2 = mbs.getRelationshipsDisplay(CUI, null, Direction.TARGETOF); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); } catch (Exception ex) { ex.printStackTrace(); return null; } // Categorize relationships into six categories and find association source data ms = System.currentTimeMillis(); action = "Categorizing relationships into six categories; finding source data for each relationship"; for(String rel : map.keySet()){ List<RelationshipTabResults> relations = map.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { String category = "Other"; if (parent_asso_vec.contains(rel)) category = "Parent"; else if (child_asso_vec.contains(rel)) category = "Child"; else if (bt_vec.contains(rel)) category = "Broader"; else if (nt_vec.contains(rel)) category = "Narrower"; else if (sibling_asso_vec.contains(rel)) category = "Sibling"; for(RelationshipTabResults result : relations) { String code = result.getCui(); if (code.indexOf("@") == -1) { String rela = result.getRela(); String source = result.getSource(); String name = result.getName(); w = (Vector) rel_hmap.get(category); if (w == null) { w = new Vector(); } String str = rela + "|" + name + "|" + code + "|" + source; if (!w.contains(str)) { w.add(str); rel_hmap.put(category, w); } } } } } for(String rel : map2.keySet()){ List<RelationshipTabResults> relations = map2.get(rel); if (rel.compareTo(INCOMPLETE) != 0) { String category = "Other"; if (parent_asso_vec.contains(rel)) category = "Parent"; else if (child_asso_vec.contains(rel)) category = "Child"; else if (bt_vec.contains(rel)) category = "Broader"; else if (nt_vec.contains(rel)) category = "Narrower"; else if (sibling_asso_vec.contains(rel)) category = "Sibling"; for(RelationshipTabResults result : relations) { String code = result.getCui(); if (code.indexOf("@") == -1) { String rela = result.getRela(); String source = result.getSource(); String name = result.getName(); w = (Vector) rel_hmap.get(category); if (w == null) { w = new Vector(); } String str = rela + "|" + name + "|" + code + "|" + source; if (!w.contains(str)) { w.add(str); rel_hmap.put(category, w); } } } } } // Remove redundant RO relationships ms = System.currentTimeMillis(); action = "Removing redundant RO and CHD relationships"; HashSet other_hset = new HashSet(); Vector w2 = (Vector) rel_hmap.get("Other"); for (int k=0; k<w2.size(); k++) { String s = (String) w2.elementAt(k); Vector ret_vec = parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); String t = name + "|" + target_code + "|" + src; if (rel.compareTo("RO") != 0 && !other_hset.contains(t)) { other_hset.add(t); } } Vector w3 = new Vector(); for (int k=0; k<w2.size(); k++) { String s = (String) w2.elementAt(k); Vector ret_vec = parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); if (rel.compareTo("RO") != 0) { w3.add(s); } else { String t = name + "|" + target_code + "|" + src; if (!other_hset.contains(t)) { w3.add(s); } } } rel_hmap.put("Other", w3); other_hset = new HashSet(); w2 = (Vector) rel_hmap.get("Child"); for (int k=0; k<w2.size(); k++) { String s = (String) w2.elementAt(k); Vector ret_vec = parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); String t = name + "|" + target_code + "|" + src; if (rel.compareTo("CHD") != 0 && !other_hset.contains(t)) { other_hset.add(t); } } w3 = new Vector(); for (int k=0; k<w2.size(); k++) { String s = (String) w2.elementAt(k); Vector ret_vec = parseData(s, "|"); String rel = (String) ret_vec.elementAt(0); String name = (String) ret_vec.elementAt(1); String target_code = (String) ret_vec.elementAt(2); String src = (String) ret_vec.elementAt(3); if (rel.compareTo("CHD") != 0) { w3.add(s); } else { String t = name + "|" + target_code + "|" + src; if (!other_hset.contains(t)) { w3.add(s); } } } rel_hmap.put("Child", w3); delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); ms = System.currentTimeMillis(); action = "Sorting relationships by sort options (columns)"; // Sort relationships by sort options (columns) if (sort_option == null) { for (int k=0; k<category_vec.size(); k++) { String category = (String) category_vec.elementAt(k); w = (Vector) rel_hmap.get(category); SortUtils.quickSort(w); rel_hmap.put(category, w); } } else { for (int k=0; k<category_vec.size(); k++) { String category = (String) category_vec.elementAt(k); w = (Vector) rel_hmap.get(category); String sortOption = (String) sort_option.elementAt(k); w = sortRelationshipData(w, sortOption); rel_hmap.put(category, w); } } delay = System.currentTimeMillis() - ms; Debug.println("Run time (ms) for " + action + " " + delay); DBG.debugDetails(delay, action, "getAssociationTargetHashMap"); removeRedundantRecords(rel_hmap); String incomplete = (String) rel_hmap.get(INCOMPLETE); if (incomplete != null) rel_hmap.put(INCOMPLETE, incomplete); return rel_hmap; } }
package com.tactfactory.harmony.plateforme; import java.lang.reflect.Field; import com.tactfactory.harmony.annotation.Column; import com.tactfactory.harmony.annotation.Column.Type; import com.tactfactory.harmony.meta.FieldMetadata; import com.tactfactory.harmony.utils.ConsoleUtils; /** * SQliteAdapter. */ public abstract class SqliteAdapter { /** Prefix for column name generation. */ private static final String PREFIX = "COL_"; /** Suffix for column name generation. */ private static final String SUFFIX = "_ID"; /** * Generate field's structure for database creation schema. * @param fm The field * @return The field's structure */ public static String generateStructure(final FieldMetadata fm) { final StringBuilder builder = new StringBuilder(20); builder.append(' '); builder.append(generateColumnType(fm.getColumnDefinition())); if (fm.isId()) { builder.append(" PRIMARY KEY"); if (fm.getColumnDefinition().equalsIgnoreCase("INTEGER")) { builder.append(" AUTOINCREMENT"); } } else { // Set Length final Type fieldType = Type.fromName(fm.getType()); if (fieldType != null) { if (fm.getLength() != null && fm.getLength() != fieldType.getLength()) { builder.append('('); builder.append(fm.getLength()); builder.append(')'); } else if (fm.getPrecision() != null && fm.getPrecision() != fieldType.getPrecision()) { builder.append('('); builder.append(fm.getPrecision()); if (fm.getScale() != null && fm.getScale() != fieldType.getScale()) { builder.append(','); builder.append(fm.getScale()); } builder.append(')'); } } // Set Unique if (fm.isUnique() != null && fm.isUnique()) { builder.append(" UNIQUE"); } // Set Nullable if (fm.isNullable() == null || !fm.isNullable()) { builder.append(" NOT NULL"); } if (fm.getDefaultValue() != null) { builder.append(" DEFAULT '" + fm.getDefaultValue() + "'"); } } return builder.toString(); } /** * Generate the column type for a given harmony type. * @param fieldType The harmony type of a field. * @return The columnType for SQLite */ public static String generateColumnType(final String fieldType) { String type = fieldType; if (type.equalsIgnoreCase(Column.Type.STRING.getValue()) || type.equalsIgnoreCase(Column.Type.TEXT.getValue()) || type.equalsIgnoreCase(Column.Type.LOGIN.getValue()) || type.equalsIgnoreCase(Column.Type.PHONE.getValue()) || type.equalsIgnoreCase(Column.Type.PASSWORD.getValue()) || type.equalsIgnoreCase(Column.Type.EMAIL.getValue()) || type.equalsIgnoreCase(Column.Type.CITY.getValue()) || type.equalsIgnoreCase(Column.Type.ZIPCODE.getValue()) || type.equalsIgnoreCase(Column.Type.COUNTRY.getValue())) { type = "VARCHAR"; } else if (type.equalsIgnoreCase(Column.Type.DATETIME.getValue())) { type = "DATETIME"; } else if (type.equalsIgnoreCase(Column.Type.DATE.getValue())) { type = "DATE"; } else if (type.equalsIgnoreCase(Column.Type.TIME.getValue())) { type = "DATETIME"; } else if (type.equalsIgnoreCase(Column.Type.BOOLEAN.getValue())) { type = "BOOLEAN"; } else if (type.equalsIgnoreCase(Column.Type.INTEGER.getValue()) || type.equalsIgnoreCase(Column.Type.INT.getValue()) || type.equalsIgnoreCase(Column.Type.BC_EAN.getValue())) { type = "INTEGER"; } else if (type.equalsIgnoreCase(Column.Type.FLOAT.getValue())) { type = "FLOAT"; } else if (type.equalsIgnoreCase(Column.Type.DOUBLE.getValue())) { type = "DOUBLE"; } else if (type.equalsIgnoreCase(Column.Type.SHORT.getValue())) { type = "SHORT"; } else if (type.equalsIgnoreCase(Column.Type.LONG.getValue())) { type = "LONG"; } else if (type.equalsIgnoreCase(Column.Type.CHAR.getValue())) { type = "STRING"; } else if (type.equalsIgnoreCase(Column.Type.BYTE.getValue())) { type = "STRING"; } else if (type.equalsIgnoreCase(Column.Type.CHARACTER.getValue())) { type = "STRING"; } return type; } /** * Generate a column name. * @param fieldName The original field's name * @return the generated column name */ public static String generateColumnName(final String fieldName) { return PREFIX + fieldName.toUpperCase(); } /** * Generate a relation column name. * @param fieldName The original field's name * @return the generated column name */ public static String generateRelationColumnName(final String fieldName) { return PREFIX + fieldName.toUpperCase() + SUFFIX; } /** * Generate a column definition. * @param type The original field's type * @return the generated column definition */ public static String generateColumnDefinition(final String type) { String ret = type; if (type.equalsIgnoreCase("int")) { ret = "integer"; } return ret; } /** * SQLite Reserved keywords. */ public static enum Keywords { // CHECKSTYLE:OFF ABORT, ACTION, ADD, AFTER, ALL, ALTER, ANALYZE, AND, AS, ASC, ATTACH, AUTOINCREMENT, BEFORE, BEGIN, BETWEEN, BY, CASCADE, CASE, CAST, CHECK, COLLATE, COLUMN, COMMIT, CONFLICT, CONSTRAINT, CREATE, CROSS, CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP, DATABASE, DEFAULT, DEFERRABLE, DEFERRED, DELETE, DESC, DETACH, DISTINCT, DROP, EACH, ELSE, END, ESCAPE, EXCEPT, EXCLUSIVE, EXISTS, EXPLAIN, FAIL, FOR, FOREIGN, FROM, FULL, GLOB, GROUP, HAVING, IF, IGNORE, IMMEDIATE, IN, INDEX, INDEXED, INITIALLY, INNER, INSERT, INSTEAD, INTERSECT, INTO, IS, ISNULL, JOIN, KEY, LEFT, LIKE, LIMIT, MATCH, NATURAL, NO, NOT, NOTNULL, NULL, OF, OFFSET, ON, OR, ORDER, OUTER, PLAN, PRAGMA, PRIMARY, QUERY, RAISE, REFERENCES, REGEXP, REINDEX, RELEASE, RENAME, REPLACE, RESTRICT, RIGHT, ROLLBACK, ROW, SAVEPOINT, SELECT, SET, TABLE, TEMP, TEMPORARY, THEN, TO, TRANSACTION, TRIGGER, UNION, UNIQUE, UPDATE, USING, VACUUM, VALUES, VIEW, VIRTUAL, WHEN, WHERE; // CHECKSTYLE:ON /** * Tests if the given String is a reserverd SQLite keyword. * @param name The string * @return True if it is */ public static boolean exists(final String name) { boolean exists = false; try { final Field field = Keywords.class.getField(name.toUpperCase()); if (field.isEnumConstant()) { ConsoleUtils.displayWarning( name + " is a reserved SQLite keyword." + " You may have problems with" + " your database schema."); exists = true; } else { exists = false; } } catch (final NoSuchFieldException e) { exists = false; } return exists; } } }
package com.tactfactory.harmony.template; import java.util.HashMap; import com.google.common.base.CaseFormat; import com.tactfactory.harmony.plateforme.BaseAdapter; /** * Generator for bundles. */ public class BundleGenerator extends BaseGenerator { /** * Constructor. * @param adapt Adapter * @throws Exception Exception */ public BundleGenerator(BaseAdapter adapt) throws Exception { super(adapt); } /** * Generate the empty bundle basic files. * @param bundleOwnerName Owner name * @param bundleName Bundle name * @param bundleNameSpace Bundle namespace */ public void generateBundleFiles( String bundleOwnerName, String bundleName, String bundleNameSpace) { this.generateDataModel(bundleOwnerName, bundleName, bundleNameSpace); this.generateBuildXml(bundleOwnerName, bundleName); this.generateAnnotation(bundleOwnerName, bundleName, bundleNameSpace); this.generateParser(bundleOwnerName, bundleName, bundleNameSpace); this.generateCommand(bundleOwnerName, bundleName, bundleNameSpace); this.generateTemplate(bundleOwnerName, bundleName, bundleNameSpace); this.generateMeta(bundleOwnerName, bundleName, bundleNameSpace); } /** * Generate the datamodel associated with the bundle generation. * (different from the mobile project generation) * @param bundleOwnerName Owner name * @param bundleName Bundle name * @param bundleNameSpace Bundle namespace */ private void generateDataModel( String bundleOwnerName, String bundleName, String bundleNameSpace) { HashMap<String, Object> datamodel = new HashMap<String, Object>(); datamodel.put("bundle_namespace", bundleNameSpace); datamodel.put("bundle_name", bundleName); datamodel.put("bundle_owner", bundleOwnerName); this.setDatamodel(datamodel); } /** * Generate the empty annotation. * @param bundleOwnerName Owner name * @param bundleName Bundle name * @param bundleNameSpace Bundle namespace */ private void generateAnnotation( String bundleOwnerName, String bundleName, String bundleNameSpace) { String tplPath = this.getAdapter().getAnnotationBundleTemplatePath() + "/TemplateAnnotation.java"; String genPath = this.getAdapter().getAnnotationBundlePath( bundleOwnerName, bundleNameSpace, bundleName) + "/" + CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, bundleName) + ".java"; this.makeSource(tplPath, genPath, true); } /** * Generate the build.xml. * @param bundleOwnerName Owner name * @param bundleName Bundle name */ private void generateBuildXml( String bundleOwnerName, String bundleName) { String tplPath = this.getAdapter().getBundleTemplatePath() + "/build.xml"; String genPath = this.getAdapter().getBundlePath( bundleOwnerName, bundleName) + "/build.xml"; this.makeSource(tplPath, genPath, true); } /** * Generate bundle's parser. * @param bundleOwnerName Owner name * @param bundleName Bundle name * @param bundleNameSpace Bundle namespace */ private void generateParser( String bundleOwnerName, String bundleName, String bundleNameSpace) { String tplPath = this.getAdapter().getParserBundleTemplatePath() + "/TemplateParser.java"; String genPath = this.getAdapter().getParserBundlePath( bundleOwnerName, bundleNameSpace, bundleName) + "/" + CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, bundleName) + "Parser.java"; this.makeSource(tplPath, genPath, true); } /** * Generate command file for empty bundle. * @param bundleOwnerName Owner name * @param bundleName Bundle name * @param bundleNameSpace Bundle namespace */ private void generateCommand( String bundleOwnerName, String bundleName, String bundleNameSpace) { String tplPath = this.getAdapter().getCommandBundleTemplatePath() + "/TemplateCommand.java"; String genPath = this.getAdapter().getCommandBundlePath( bundleOwnerName, bundleNameSpace, bundleName) + "/" + CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, bundleName) + "Command.java"; this.makeSource(tplPath, genPath, true); } /** * Generate bundle's generator. * @param bundleOwnerName Owner name * @param bundleName Bundle name * @param bundleNameSpace Bundle namespace */ private void generateTemplate( String bundleOwnerName, String bundleName, String bundleNameSpace) { String tplPath = this.getAdapter().getTemplateBundleTemplatePath() + "/TemplateGenerator.java"; String genPath = this.getAdapter().getTemplateBundlePath( bundleOwnerName, bundleNameSpace, bundleName) + "/" + CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, bundleName) + "Generator.java"; this.makeSource(tplPath, genPath, true); } /** * Generate Bundle metadata. * @param bundleOwnerName Owner name * @param bundleName Bundle name * @param bundleNameSpace Bundle namespace */ private void generateMeta( String bundleOwnerName, String bundleName, String bundleNameSpace) { String tplPath = this.getAdapter().getMetaBundleTemplatePath() + "/TemplateMetadata.java"; String genPath = this.getAdapter().getMetaBundlePath( bundleOwnerName, bundleNameSpace, bundleName) + "/" + CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, bundleName) + "Metadata.java"; this.makeSource(tplPath, genPath, true); } }
package me.nallar.tickthreading.mappings; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import me.nallar.tickthreading.Log; public abstract class Mappings { @SuppressWarnings("unchecked") public List map(List things) { List mappedThings = new ArrayList(); for (Object thing : things) { if (thing instanceof MethodDescription) { mappedThings.add(map((MethodDescription) thing)); } else if (thing instanceof ClassDescription) { mappedThings.add(map((ClassDescription) thing)); } else { throw new IllegalArgumentException("Must be mappable: " + thing + "isn't!"); } } return mappedThings; } public MethodDescription map(Method method) { return map(new MethodDescription(method)); } public abstract MethodDescription map(MethodDescription methodDescription); public ClassDescription map(Class clazz) { return map(new ClassDescription(clazz)); } public abstract ClassDescription map(ClassDescription classDescription); }
package org.objectweb.proactive.extra.gcmdeployment; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.xml.XMLConstants; import javax.xml.namespace.NamespaceContext; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import org.objectweb.proactive.extra.gcmdeployment.GCMApplication.FileTransferBlock; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; public class GCMParserHelper implements GCMParserConstants { static public String getAttributeValue(Node node, String attributeName) { Node namedItem = node.getAttributes().getNamedItem(attributeName); return (namedItem != null) ? namedItem.getNodeValue() : null; } static public String getElementValue(Node node) { if ((node != null) && (node.getTextContent() != null)) { return node.getTextContent().trim(); } return null; } static public FileTransferBlock parseFileTransferNode(Node fileTransferNode) { FileTransferBlock fileTransferBlock = new FileTransferBlock(); String source = GCMParserHelper.getAttributeValue(fileTransferNode, "source"); fileTransferBlock.setSource(source); String destination = GCMParserHelper.getAttributeValue(fileTransferNode, "destination"); fileTransferBlock.setDestination(destination); return fileTransferBlock; } static public class MyDefaultHandler extends DefaultHandler { private String errMessage = ""; @Override public void warning(SAXParseException e) throws SAXParseException { // System.err.println("Warning Line " + e.getLineNumber() + ": " + // e.getMessage() + "\n"); throw e; } @Override public void error(SAXParseException e) throws SAXParseException { // errMessage = new String("Error Line " + e.getLineNumber() + ": " + // e.getMessage() + "\n"); // System.err.println(errMessage); throw e; } @Override public void fatalError(SAXParseException e) throws SAXParseException { // errMessage = new String("Error Line " + e.getLineNumber() + ": " + // e.getMessage() + "\n"); // System.err.println(errMessage); throw e; } } static public class ProActiveNamespaceContext implements NamespaceContext { protected String namespace; public ProActiveNamespaceContext(String namespace) { this.namespace = namespace; } public String getNamespaceURI(String prefix) { if (prefix == null) { throw new NullPointerException("Null prefix"); } else if ("pa".equals(prefix)) { return namespace; } else if ("xml".equals(prefix)) { return XMLConstants.XML_NS_URI; } return XMLConstants.NULL_NS_URI; } // This method isn't necessary for XPath processing. public String getPrefix(String uri) { throw new UnsupportedOperationException(); } // This method isn't necessary for XPath processing either. public Iterator getPrefixes(String uri) { throw new UnsupportedOperationException(); } } static public List<PathElement> parseClasspath(XPath xpath, Node classPathNode) throws XPathExpressionException { NodeList pathElementNodes = (NodeList) xpath.evaluate("pa:pathElement", classPathNode, XPathConstants.NODESET); ArrayList<PathElement> res = new ArrayList<PathElement>(); for (int i = 0; i < pathElementNodes.getLength(); ++i) { Node pathElementNode = pathElementNodes.item(i); PathElement pathElement = parsePathElementNode(pathElementNode); res.add(pathElement); } return res; } static public PathElement parsePathElementNode(Node pathElementNode) { PathElement pathElement = new PathElement(); String attr = GCMParserHelper.getAttributeValue(pathElementNode, "relpath"); pathElement.setRelPath(attr); attr = GCMParserHelper.getAttributeValue(pathElementNode, "base"); if (attr != null) { pathElement.setBase(attr); } return pathElement; } public static List<String> parseArgumentListNode(XPath xpath, Node argumentListNode) throws XPathExpressionException { ArrayList<String> args = new ArrayList<String>(); NodeList argNodes = (NodeList) xpath.evaluate("pa:arg", argumentListNode, XPathConstants.NODESET); for (int i = 0; i < argNodes.getLength(); ++i) { Node argNode = argNodes.item(i); args.add(getElementValue(argNode)); } return args; } public static List<String> parseEnviromentNode(XPath xpath, Node environmentNode) throws XPathExpressionException { ArrayList<String> environment = new ArrayList<String>(); NodeList argNodes = (NodeList) xpath.evaluate("pa:*Variable", environmentNode, XPathConstants.NODESET); for (int i = 0; i < argNodes.getLength(); ++i) { Node argNode = argNodes.item(i); environment.add(getElementValue(argNode)); } return environment; } }
package cgeo.geocaching; import cgeo.geocaching.DataStore.StorageLocation; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.activity.SimpleWebviewActivity; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.IConnector; import cgeo.geocaching.connector.ILoggingManager; import cgeo.geocaching.connector.capability.ISearchByCenter; import cgeo.geocaching.connector.capability.ISearchByGeocode; import cgeo.geocaching.connector.gc.GCConnector; import cgeo.geocaching.connector.gc.GCConstants; import cgeo.geocaching.connector.gc.Tile; import cgeo.geocaching.connector.gc.UncertainProperty; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag; import cgeo.geocaching.enumerations.LoadFlags.SaveFlag; import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.files.GPXParser; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.list.StoredList; import cgeo.geocaching.network.HtmlImage; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.utils.CancellableHandler; import cgeo.geocaching.utils.DateUtils; import cgeo.geocaching.utils.ImageUtils; import cgeo.geocaching.utils.LazyInitializedList; import cgeo.geocaching.utils.Log; import cgeo.geocaching.utils.LogTemplateProvider; import cgeo.geocaching.utils.LogTemplateProvider.LogContext; import cgeo.geocaching.utils.MatcherWrapper; import cgeo.geocaching.utils.RxUtils; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.ListUtils; import org.apache.commons.collections4.Predicate; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import rx.Scheduler; import rx.Subscription; import rx.functions.Action0; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.Parcelable; import android.text.Html; import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.EnumMap; import java.util.EnumSet; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; /** * Internal c:geo representation of a "cache" */ public class Geocache implements ICache, IWaypoint { private static final int OWN_WP_PREFIX_OFFSET = 17; private long updated = 0; private long detailedUpdate = 0; private long visitedDate = 0; private int listId = StoredList.TEMPORARY_LIST.id; private boolean detailed = false; private String geocode = ""; private String cacheId = ""; private String guid = ""; private UncertainProperty<CacheType> cacheType = new UncertainProperty<>(CacheType.UNKNOWN, Tile.ZOOMLEVEL_MIN - 1); private String name = ""; private String ownerDisplayName = ""; private String ownerUserId = ""; private Date hidden = null; /** * lazy initialized */ private String hint = null; private CacheSize size = CacheSize.UNKNOWN; private float difficulty = 0; private float terrain = 0; private Float direction = null; private Float distance = null; /** * lazy initialized */ private String location = null; private UncertainProperty<Geopoint> coords = new UncertainProperty<>(null); private boolean reliableLatLon = false; private String personalNote = null; /** * lazy initialized */ private String shortdesc = null; /** * lazy initialized */ private String description = null; private Boolean disabled = null; private Boolean archived = null; private Boolean premiumMembersOnly = null; private Boolean found = null; private Boolean favorite = null; private Boolean onWatchlist = null; private Boolean logOffline = null; private int favoritePoints = 0; private float rating = 0; // valid ratings are larger than zero private int votes = 0; private float myVote = 0; // valid ratings are larger than zero private int inventoryItems = 0; private final LazyInitializedList<String> attributes = new LazyInitializedList<String>() { @Override public List<String> call() { return DataStore.loadAttributes(geocode); } }; private final LazyInitializedList<Waypoint> waypoints = new LazyInitializedList<Waypoint>() { @Override public List<Waypoint> call() { return DataStore.loadWaypoints(geocode); } }; private List<Image> spoilers = null; private List<Trackable> inventory = null; private Map<LogType, Integer> logCounts = new EnumMap<>(LogType.class); private boolean userModifiedCoords = false; // temporary values private boolean statusChecked = false; private String directionImg = ""; private String nameForSorting; private final EnumSet<StorageLocation> storageLocation = EnumSet.of(StorageLocation.HEAP); private boolean finalDefined = false; private boolean logPasswordRequired = false; private static final Pattern NUMBER_PATTERN = Pattern.compile("\\d+"); private Handler changeNotificationHandler = null; /** * Create a new cache. To be used everywhere except for the GPX parser */ public Geocache() { // empty } /** * Cache constructor to be used by the GPX parser only. This constructor explicitly sets several members to empty * lists. * * @param gpxParser */ public Geocache(final GPXParser gpxParser) { setReliableLatLon(true); setAttributes(Collections.<String> emptyList()); setWaypoints(Collections.<Waypoint> emptyList(), false); } public void setChangeNotificationHandler(final Handler newNotificationHandler) { changeNotificationHandler = newNotificationHandler; } /** * Sends a change notification to interested parties */ private void notifyChange() { if (changeNotificationHandler != null) { changeNotificationHandler.sendEmptyMessage(0); } } /** * Gather missing information for new Geocache object from the stored Geocache object. * This is called in the new Geocache parsed from website to set information not yet * parsed. * * @param other * the other version, or null if non-existent * @return true if this cache is "equal" to the other version */ public boolean gatherMissingFrom(final Geocache other) { if (other == null) { return false; } if (other == this) { return true; } updated = System.currentTimeMillis(); // if parsed cache is not yet detailed and stored is, the information of // the parsed cache will be overwritten if (!detailed && other.detailed) { detailed = other.detailed; detailedUpdate = other.detailedUpdate; // boolean values must be enumerated here. Other types are assigned outside this if-statement reliableLatLon = other.reliableLatLon; finalDefined = other.finalDefined; } if (premiumMembersOnly == null) { premiumMembersOnly = other.premiumMembersOnly; } if (found == null) { found = other.found; } if (disabled == null) { disabled = other.disabled; } if (favorite == null) { favorite = other.favorite; } if (archived == null) { archived = other.archived; } if (onWatchlist == null) { onWatchlist = other.onWatchlist; } if (logOffline == null) { logOffline = other.logOffline; } if (visitedDate == 0) { visitedDate = other.visitedDate; } if (listId == StoredList.TEMPORARY_LIST.id) { listId = other.listId; } if (StringUtils.isBlank(geocode)) { geocode = other.geocode; } if (StringUtils.isBlank(cacheId)) { cacheId = other.cacheId; } if (StringUtils.isBlank(guid)) { guid = other.guid; } cacheType = UncertainProperty.getMergedProperty(cacheType, other.cacheType); if (StringUtils.isBlank(name)) { name = other.name; } if (StringUtils.isBlank(ownerDisplayName)) { ownerDisplayName = other.ownerDisplayName; } if (StringUtils.isBlank(ownerUserId)) { ownerUserId = other.ownerUserId; } if (hidden == null) { hidden = other.hidden; } if (!detailed && StringUtils.isBlank(getHint())) { hint = other.getHint(); } if (size == null || CacheSize.UNKNOWN == size) { size = other.size; } if (difficulty == 0) { difficulty = other.difficulty; } if (terrain == 0) { terrain = other.terrain; } if (direction == null) { direction = other.direction; } if (distance == null) { distance = other.distance; } if (StringUtils.isBlank(getLocation())) { location = other.getLocation(); } coords = UncertainProperty.getMergedProperty(coords, other.coords); // don't use StringUtils.isBlank here. Otherwise we cannot recognize a note which was deleted on GC if (personalNote == null) { personalNote = other.personalNote; } else if (other.personalNote != null && !personalNote.equals(other.personalNote)) { final PersonalNote myNote = new PersonalNote(this); final PersonalNote otherNote = new PersonalNote(other); final PersonalNote mergedNote = myNote.mergeWith(otherNote); personalNote = mergedNote.toString(); } if (!detailed && StringUtils.isBlank(getShortDescription())) { shortdesc = other.getShortDescription(); } if (StringUtils.isBlank(getDescription())) { description = other.getDescription(); } // FIXME: this makes no sense to favor this over the other. 0 should not be a special case here as it is // in the range of acceptable values. This is probably the case at other places (rating, votes, etc.) too. if (favoritePoints == 0) { favoritePoints = other.favoritePoints; } if (rating == 0) { rating = other.rating; } if (votes == 0) { votes = other.votes; } if (myVote == 0) { myVote = other.myVote; } if (!detailed && attributes.isEmpty()) { if (other.attributes != null) { attributes.addAll(other.attributes); } } if (waypoints.isEmpty()) { this.setWaypoints(other.waypoints, false); } else { final ArrayList<Waypoint> newPoints = new ArrayList<>(waypoints); Waypoint.mergeWayPoints(newPoints, other.waypoints, false); this.setWaypoints(newPoints, false); } if (spoilers == null) { spoilers = other.spoilers; } if (inventory == null) { // If inventoryItems is 0, it can mean both // "don't know" or "0 items". Since we cannot distinguish // them here, only populate inventoryItems from // old data when we have to do it for inventory. inventory = other.inventory; inventoryItems = other.inventoryItems; } if (logCounts.isEmpty()) { logCounts = other.logCounts; } // if cache has ORIGINAL type waypoint ... it is considered that it has modified coordinates, otherwise not userModifiedCoords = false; for (final Waypoint wpt : waypoints) { if (wpt.getWaypointType() == WaypointType.ORIGINAL) { userModifiedCoords = true; break; } } if (!reliableLatLon) { reliableLatLon = other.reliableLatLon; } return isEqualTo(other); } /** * Compare two caches quickly. For map and list fields only the references are compared ! * * @param other * the other cache to compare this one to * @return true if both caches have the same content */ @SuppressWarnings("deprecation") @SuppressFBWarnings("FE_FLOATING_POINT_EQUALITY") private boolean isEqualTo(final Geocache other) { return detailed == other.detailed && StringUtils.equalsIgnoreCase(geocode, other.geocode) && StringUtils.equalsIgnoreCase(name, other.name) && cacheType == other.cacheType && size == other.size && ObjectUtils.equals(found, other.found) && ObjectUtils.equals(premiumMembersOnly, other.premiumMembersOnly) && difficulty == other.difficulty && terrain == other.terrain && (coords != null ? coords.equals(other.coords) : null == other.coords) && reliableLatLon == other.reliableLatLon && ObjectUtils.equals(disabled, other.disabled) && ObjectUtils.equals(archived, other.archived) && listId == other.listId && StringUtils.equalsIgnoreCase(ownerDisplayName, other.ownerDisplayName) && StringUtils.equalsIgnoreCase(ownerUserId, other.ownerUserId) && StringUtils.equalsIgnoreCase(getDescription(), other.getDescription()) && StringUtils.equalsIgnoreCase(personalNote, other.personalNote) && StringUtils.equalsIgnoreCase(getShortDescription(), other.getShortDescription()) && StringUtils.equalsIgnoreCase(getLocation(), other.getLocation()) && ObjectUtils.equals(favorite, other.favorite) && favoritePoints == other.favoritePoints && ObjectUtils.equals(onWatchlist, other.onWatchlist) && (hidden != null ? hidden.equals(other.hidden) : null == other.hidden) && StringUtils.equalsIgnoreCase(guid, other.guid) && StringUtils.equalsIgnoreCase(getHint(), other.getHint()) && StringUtils.equalsIgnoreCase(cacheId, other.cacheId) && (direction != null ? direction.equals(other.direction) : null == other.direction) && (distance != null ? distance.equals(other.distance) : null == other.distance) && rating == other.rating && votes == other.votes && myVote == other.myVote && inventoryItems == other.inventoryItems && attributes == other.attributes && waypoints == other.waypoints && spoilers == other.spoilers && inventory == other.inventory && logCounts == other.logCounts && ObjectUtils.equals(logOffline, other.logOffline) && finalDefined == other.finalDefined; } public boolean hasTrackables() { return inventoryItems > 0; } public boolean canBeAddedToCalendar() { // is event type? if (!isEventCache()) { return false; } // has event date set? if (hidden == null) { return false; } // is not in the past? final Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return hidden.compareTo(cal.getTime()) >= 0; } public boolean isEventCache() { return cacheType.getValue().isEvent(); } public void logVisit(final Activity fromActivity) { if (!getConnector().canLog(this)) { ActivityMixin.showToast(fromActivity, fromActivity.getResources().getString(R.string.err_cannot_log_visit)); return; } fromActivity.startActivity(LogCacheActivity.getLogCacheIntent(fromActivity, cacheId, geocode)); } public void logOffline(final Activity fromActivity, final LogType logType) { final boolean mustIncludeSignature = StringUtils.isNotBlank(Settings.getSignature()) && Settings.isAutoInsertSignature(); final String initial = mustIncludeSignature ? LogTemplateProvider.applyTemplates(Settings.getSignature(), new LogContext(this, null, true)) : ""; logOffline(fromActivity, initial, Calendar.getInstance(), logType); } void logOffline(final Activity fromActivity, final String log, final Calendar date, final LogType logType) { if (logType == LogType.UNKNOWN) { return; } final boolean status = DataStore.saveLogOffline(geocode, date.getTime(), logType, log); final Resources res = fromActivity.getResources(); if (status) { ActivityMixin.showToast(fromActivity, res.getString(R.string.info_log_saved)); DataStore.saveVisitDate(geocode); logOffline = Boolean.TRUE; notifyChange(); } else { ActivityMixin.showToast(fromActivity, res.getString(R.string.err_log_post_failed)); } } public void clearOfflineLog() { DataStore.clearLogOffline(geocode); notifyChange(); } public List<LogType> getPossibleLogTypes() { return getConnector().getPossibleLogTypes(this); } public void openInBrowser(final Activity fromActivity) { final Intent viewIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getLongUrl())); // Check if cgeo is the default, show the chooser to let the user choose a browser if (viewIntent.resolveActivity(fromActivity.getPackageManager()).getPackageName().equals(fromActivity.getPackageName())) { final Intent chooser = Intent.createChooser(viewIntent, fromActivity.getString(R.string.cache_menu_browser)); final Intent internalBrowser = new Intent(fromActivity, SimpleWebviewActivity.class); internalBrowser.setData(Uri.parse(getUrl())); chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] {internalBrowser}); fromActivity.startActivity(chooser); } else { fromActivity.startActivity(viewIntent); } } private String getCacheUrl() { return getConnector().getCacheUrl(this); } private IConnector getConnector() { return ConnectorFactory.getConnector(this); } public boolean canOpenInBrowser() { return getCacheUrl() != null; } public boolean supportsRefresh() { return getConnector() instanceof ISearchByGeocode; } public boolean supportsWatchList() { return getConnector().supportsWatchList(); } public boolean supportsFavoritePoints() { return getConnector().supportsFavoritePoints(this); } public boolean supportsLogging() { return getConnector().supportsLogging(); } public boolean supportsLogImages() { return getConnector().supportsLogImages(); } public boolean supportsOwnCoordinates() { return getConnector().supportsOwnCoordinates(); } public ILoggingManager getLoggingManager(final LogCacheActivity activity) { return getConnector().getLoggingManager(activity, this); } @Override public float getDifficulty() { return difficulty; } @Override public String getGeocode() { return geocode; } @Override public String getOwnerDisplayName() { return ownerDisplayName; } @Override public CacheSize getSize() { if (size == null) { return CacheSize.UNKNOWN; } return size; } @Override public float getTerrain() { return terrain; } @Override public boolean isArchived() { return BooleanUtils.isTrue(archived); } @Override public boolean isDisabled() { return BooleanUtils.isTrue(disabled); } @Override public boolean isPremiumMembersOnly() { return BooleanUtils.isTrue(premiumMembersOnly); } public void setPremiumMembersOnly(final boolean members) { this.premiumMembersOnly = members; } @Override public boolean isOwner() { return getConnector().isOwner(this); } @Override public String getOwnerUserId() { return ownerUserId; } /** * Attention, calling this method may trigger a database access for the cache! */ @Override public String getHint() { initializeCacheTexts(); assertTextNotNull(hint, "Hint"); return hint; } /** * After lazy loading the lazily loaded field must be non {@code null}. * */ private static void assertTextNotNull(final String field, final String name) throws InternalError { if (field == null) { throw new InternalError(name + " field is not allowed to be null here"); } } /** * Attention, calling this method may trigger a database access for the cache! */ @Override public String getDescription() { initializeCacheTexts(); assertTextNotNull(description, "Description"); return description; } /** * loads long text parts of a cache on demand (but all fields together) */ private void initializeCacheTexts() { if (description == null || shortdesc == null || hint == null || location == null) { final Geocache partial = DataStore.loadCacheTexts(this.getGeocode()); if (description == null) { setDescription(partial.getDescription()); } if (shortdesc == null) { setShortDescription(partial.getShortDescription()); } if (hint == null) { setHint(partial.getHint()); } if (location == null) { setLocation(partial.getLocation()); } } } /** * Attention, calling this method may trigger a database access for the cache! */ @Override public String getShortDescription() { initializeCacheTexts(); assertTextNotNull(shortdesc, "Short description"); return shortdesc; } @Override public String getName() { return name; } @Override public String getCacheId() { if (StringUtils.isBlank(cacheId) && getConnector().equals(GCConnector.getInstance())) { return String.valueOf(GCConstants.gccodeToGCId(geocode)); } return cacheId; } @Override public String getGuid() { return guid; } /** * Attention, calling this method may trigger a database access for the cache! */ @Override public String getLocation() { initializeCacheTexts(); assertTextNotNull(location, "Location"); return location; } @Override public String getPersonalNote() { // non premium members have no personal notes, premium members have an empty string by default. // map both to null, so other code doesn't need to differentiate return StringUtils.defaultIfBlank(personalNote, null); } public boolean supportsCachesAround() { return getConnector() instanceof ISearchByCenter; } public void shareCache(final Activity fromActivity, final Resources res) { if (geocode == null) { return; } final Intent intent = getShareIntent(); fromActivity.startActivity(Intent.createChooser(intent, res.getText(R.string.cache_menu_share))); } public Intent getShareIntent() { final StringBuilder subject = new StringBuilder("Geocache "); subject.append(geocode); if (StringUtils.isNotBlank(name)) { subject.append(" - ").append(name); } final Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, subject.toString()); intent.putExtra(Intent.EXTRA_TEXT, getUrl()); return intent; } public String getUrl() { return getConnector().getCacheUrl(this); } public String getLongUrl() { return getConnector().getLongCacheUrl(this); } public String getCgeoUrl() { return getConnector().getCacheUrl(this); } public boolean supportsGCVote() { return StringUtils.startsWithIgnoreCase(geocode, "GC"); } public void setDescription(final String description) { this.description = description; } @Override public boolean isFound() { return BooleanUtils.isTrue(found); } @Override public boolean isFavorite() { return BooleanUtils.isTrue(favorite); } public void setFavorite(final boolean favorite) { this.favorite = favorite; } @Override @Nullable public Date getHiddenDate() { return hidden; } @Override public List<String> getAttributes() { return attributes.getUnderlyingList(); } @Override public List<Trackable> getInventory() { return inventory; } public void addSpoiler(final Image spoiler) { if (spoilers == null) { spoilers = new ArrayList<>(); } spoilers.add(spoiler); } @Override public List<Image> getSpoilers() { return ListUtils.unmodifiableList(ListUtils.emptyIfNull(spoilers)); } @Override public Map<LogType, Integer> getLogCounts() { return logCounts; } @Override public int getFavoritePoints() { return favoritePoints; } @Override public String getNameForSorting() { if (null == nameForSorting) { nameForSorting = name; // pad each number part to a fixed size of 6 digits, so that numerical sorting becomes equivalent to string sorting MatcherWrapper matcher = new MatcherWrapper(NUMBER_PATTERN, nameForSorting); int start = 0; while (matcher.find(start)) { final String number = matcher.group(); nameForSorting = StringUtils.substring(nameForSorting, 0, matcher.start()) + StringUtils.leftPad(number, 6, '0') + StringUtils.substring(nameForSorting, matcher.start() + number.length()); start = matcher.start() + Math.max(6, number.length()); matcher = new MatcherWrapper(NUMBER_PATTERN, nameForSorting); } } return nameForSorting; } public boolean isVirtual() { return cacheType.getValue().isVirtual(); } public boolean showSize() { return !(size == CacheSize.NOT_CHOSEN || isEventCache() || isVirtual()); } public long getUpdated() { return updated; } public void setUpdated(final long updated) { this.updated = updated; } public long getDetailedUpdate() { return detailedUpdate; } public void setDetailedUpdate(final long detailedUpdate) { this.detailedUpdate = detailedUpdate; } public long getVisitedDate() { return visitedDate; } public void setVisitedDate(final long visitedDate) { this.visitedDate = visitedDate; } public int getListId() { return listId; } public void setListId(final int listId) { this.listId = listId; } public boolean isDetailed() { return detailed; } public void setDetailed(final boolean detailed) { this.detailed = detailed; } public void setHidden(final Date hidden) { if (hidden == null) { this.hidden = null; } else { this.hidden = new Date(hidden.getTime()); // avoid storing the external reference in this object } } public Float getDirection() { return direction; } public void setDirection(final Float direction) { this.direction = direction; } public Float getDistance() { return distance; } public void setDistance(final Float distance) { this.distance = distance; } @Override public Geopoint getCoords() { return coords.getValue(); } public int getCoordZoomLevel() { return coords.getCertaintyLevel(); } /** * Set reliable coordinates * * @param coords */ public void setCoords(final Geopoint coords) { this.coords = new UncertainProperty<>(coords); } /** * Set unreliable coordinates from a certain map zoom level * * @param coords * @param zoomlevel */ public void setCoords(final Geopoint coords, final int zoomlevel) { this.coords = new UncertainProperty<>(coords, zoomlevel); } /** * @return true if the coords are from the cache details page and the user has been logged in */ public boolean isReliableLatLon() { return getConnector().isReliableLatLon(reliableLatLon); } public void setReliableLatLon(final boolean reliableLatLon) { this.reliableLatLon = reliableLatLon; } public void setShortDescription(final String shortdesc) { this.shortdesc = shortdesc; } public void setFavoritePoints(final int favoriteCnt) { this.favoritePoints = favoriteCnt; } public float getRating() { return rating; } public void setRating(final float rating) { this.rating = rating; } public int getVotes() { return votes; } public void setVotes(final int votes) { this.votes = votes; } public float getMyVote() { return myVote; } public void setMyVote(final float myVote) { this.myVote = myVote; } public int getInventoryItems() { return inventoryItems; } public void setInventoryItems(final int inventoryItems) { this.inventoryItems = inventoryItems; } @Override public boolean isOnWatchlist() { return BooleanUtils.isTrue(onWatchlist); } public void setOnWatchlist(final boolean onWatchlist) { this.onWatchlist = onWatchlist; } /** * return an immutable list of waypoints. * * @return always non <code>null</code> */ public List<Waypoint> getWaypoints() { return waypoints.getUnderlyingList(); } /** * @param waypoints * List of waypoints to set for cache * @param saveToDatabase * Indicates whether to add the waypoints to the database. Should be false if * called while loading or building a cache * @return <code>true</code> if waypoints successfully added to waypoint database */ public boolean setWaypoints(final List<Waypoint> waypoints, final boolean saveToDatabase) { this.waypoints.clear(); if (waypoints != null) { this.waypoints.addAll(waypoints); } finalDefined = false; if (waypoints != null) { for (final Waypoint waypoint : waypoints) { waypoint.setGeocode(geocode); if (waypoint.isFinalWithCoords()) { finalDefined = true; } } } return saveToDatabase && DataStore.saveWaypoints(this); } /** * The list of logs is immutable, because it is directly fetched from the database on demand, and not stored at this * object. If you want to modify logs, you have to load all logs of the cache, create a new list from the existing * list and store that new list in the database. * * @return immutable list of logs */ @NonNull public List<LogEntry> getLogs() { return DataStore.loadLogs(geocode); } /** * @return only the logs of friends */ @NonNull public List<LogEntry> getFriendsLogs() { final ArrayList<LogEntry> friendLogs = new ArrayList<>(); for (final LogEntry log : getLogs()) { if (log.friend) { friendLogs.add(log); } } return Collections.unmodifiableList(friendLogs); } public boolean isLogOffline() { return BooleanUtils.isTrue(logOffline); } public void setLogOffline(final boolean logOffline) { this.logOffline = logOffline; } public boolean isStatusChecked() { return statusChecked; } public void setStatusChecked(final boolean statusChecked) { this.statusChecked = statusChecked; } public String getDirectionImg() { return directionImg; } public void setDirectionImg(final String directionImg) { this.directionImg = directionImg; } public void setGeocode(final String geocode) { this.geocode = StringUtils.upperCase(geocode); } public void setCacheId(final String cacheId) { this.cacheId = cacheId; } public void setGuid(final String guid) { this.guid = guid; } public void setName(final String name) { this.name = name; } public void setOwnerDisplayName(final String ownerDisplayName) { this.ownerDisplayName = ownerDisplayName; } public void setOwnerUserId(final String ownerUserId) { this.ownerUserId = ownerUserId; } public void setHint(final String hint) { this.hint = hint; } public void setSize(final CacheSize size) { if (size == null) { this.size = CacheSize.UNKNOWN; } else { this.size = size; } } public void setDifficulty(final float difficulty) { this.difficulty = difficulty; } public void setTerrain(final float terrain) { this.terrain = terrain; } public void setLocation(final String location) { this.location = location; } public void setPersonalNote(final String personalNote) { this.personalNote = StringUtils.trimToNull(personalNote); } public void setDisabled(final boolean disabled) { this.disabled = disabled; } public void setArchived(final boolean archived) { this.archived = archived; } public void setFound(final boolean found) { this.found = found; } public void setAttributes(final List<String> attributes) { this.attributes.clear(); if (attributes != null) { this.attributes.addAll(attributes); } } public void setSpoilers(final List<Image> spoilers) { this.spoilers = spoilers; } public void setInventory(final List<Trackable> inventory) { this.inventory = inventory; } public void setLogCounts(final Map<LogType, Integer> logCounts) { this.logCounts = logCounts; } /* * (non-Javadoc) * * @see cgeo.geocaching.IBasicCache#getType() * * @returns Never null */ @Override public CacheType getType() { return cacheType.getValue(); } public void setType(final CacheType cacheType) { if (cacheType == null || CacheType.ALL == cacheType) { throw new IllegalArgumentException("Illegal cache type"); } this.cacheType = new UncertainProperty<>(cacheType); } public void setType(final CacheType cacheType, final int zoomlevel) { if (cacheType == null || CacheType.ALL == cacheType) { throw new IllegalArgumentException("Illegal cache type"); } this.cacheType = new UncertainProperty<>(cacheType, zoomlevel); } public boolean hasDifficulty() { return difficulty > 0f; } public boolean hasTerrain() { return terrain > 0f; } /** * @return the storageLocation */ public EnumSet<StorageLocation> getStorageLocation() { return storageLocation; } /** * @param storageLocation * the storageLocation to set */ public void addStorageLocation(final StorageLocation storageLocation) { this.storageLocation.add(storageLocation); } /** * @param waypoint * Waypoint to add to the cache * @param saveToDatabase * Indicates whether to add the waypoint to the database. Should be false if * called while loading or building a cache * @return <code>true</code> if waypoint successfully added to waypoint database */ public boolean addOrChangeWaypoint(final Waypoint waypoint, final boolean saveToDatabase) { waypoint.setGeocode(geocode); if (waypoint.getId() < 0) { // this is a new waypoint assignUniquePrefix(waypoint); waypoints.add(waypoint); if (waypoint.isFinalWithCoords()) { finalDefined = true; } } else { // this is a waypoint being edited final int index = getWaypointIndex(waypoint); if (index >= 0) { final Waypoint oldWaypoint = waypoints.remove(index); waypoint.setPrefix(oldWaypoint.getPrefix()); //migration if (StringUtils.isBlank(waypoint.getPrefix()) || StringUtils.equalsIgnoreCase(waypoint.getPrefix(), Waypoint.PREFIX_OWN)) { assignUniquePrefix(waypoint); } } waypoints.add(waypoint); // when waypoint was edited, finalDefined may have changed resetFinalDefined(); } return saveToDatabase && DataStore.saveWaypoint(waypoint.getId(), geocode, waypoint); } /* * Assigns a unique two-digit (compatibility with gc.com) * prefix within the scope of this cache. */ private void assignUniquePrefix(final Waypoint waypoint) { // gather existing prefixes final Set<String> assignedPrefixes = new HashSet<>(); for (final Waypoint wp : waypoints) { assignedPrefixes.add(wp.getPrefix()); } for (int i = OWN_WP_PREFIX_OFFSET; i < 100; i++) { final String prefixCandidate = StringUtils.leftPad(String.valueOf(i), 2, '0'); if (!assignedPrefixes.contains(prefixCandidate)) { waypoint.setPrefix(prefixCandidate); break; } } } public boolean hasWaypoints() { return !waypoints.isEmpty(); } public boolean hasFinalDefined() { return finalDefined; } // Only for loading public void setFinalDefined(final boolean finalDefined) { this.finalDefined = finalDefined; } /** * Reset <code>finalDefined</code> based on current list of stored waypoints */ private void resetFinalDefined() { finalDefined = false; for (final Waypoint wp : waypoints) { if (wp.isFinalWithCoords()) { finalDefined = true; break; } } } public boolean hasUserModifiedCoords() { return userModifiedCoords; } public void setUserModifiedCoords(final boolean coordsChanged) { userModifiedCoords = coordsChanged; } /** * Duplicate a waypoint. * * @param original * the waypoint to duplicate * @return <code>true</code> if the waypoint was duplicated, <code>false</code> otherwise (invalid index) */ public boolean duplicateWaypoint(final Waypoint original) { if (original == null) { return false; } final int index = getWaypointIndex(original); final Waypoint copy = new Waypoint(original); copy.setUserDefined(); copy.setName(CgeoApplication.getInstance().getString(R.string.waypoint_copy_of) + " " + copy.getName()); waypoints.add(index + 1, copy); return DataStore.saveWaypoint(-1, geocode, copy); } /** * delete a user defined waypoint * * @param waypoint * to be removed from cache * @return <code>true</code>, if the waypoint was deleted */ public boolean deleteWaypoint(final Waypoint waypoint) { if (waypoint == null) { return false; } if (waypoint.getId() < 0) { return false; } if (waypoint.isUserDefined()) { final int index = getWaypointIndex(waypoint); waypoints.remove(index); DataStore.deleteWaypoint(waypoint.getId()); DataStore.removeCache(geocode, EnumSet.of(RemoveFlag.CACHE)); // Check status if Final is defined if (waypoint.isFinalWithCoords()) { resetFinalDefined(); } return true; } return false; } /** * deletes any waypoint * * @param waypoint */ public void deleteWaypointForce(final Waypoint waypoint) { final int index = getWaypointIndex(waypoint); waypoints.remove(index); DataStore.deleteWaypoint(waypoint.getId()); DataStore.removeCache(geocode, EnumSet.of(RemoveFlag.CACHE)); resetFinalDefined(); } /** * Find index of given <code>waypoint</code> in cache's <code>waypoints</code> list * * @param waypoint * to find index for * @return index in <code>waypoints</code> if found, -1 otherwise */ private int getWaypointIndex(final Waypoint waypoint) { final int id = waypoint.getId(); for (int index = 0; index < waypoints.size(); index++) { if (waypoints.get(index).getId() == id) { return index; } } return -1; } /** * Lookup a waypoint by its id. * * @param id * the id of the waypoint to look for * @return waypoint or <code>null</code> */ public Waypoint getWaypointById(final int id) { for (final Waypoint waypoint : waypoints) { if (waypoint.getId() == id) { return waypoint; } } return null; } /** * Detect coordinates in the personal note and convert them to user defined waypoints. Works by rule of thumb. */ public void parseWaypointsFromNote() { for (final Waypoint waypoint : Waypoint.parseWaypointsFromNote(StringUtils.defaultString(getPersonalNote()))) { if (!hasIdenticalWaypoint(waypoint.getCoords())) { addOrChangeWaypoint(waypoint, false); } } } private boolean hasIdenticalWaypoint(final Geopoint point) { for (final Waypoint waypoint: waypoints) { // waypoint can have no coords such as a Final set by cache owner final Geopoint coords = waypoint.getCoords(); if (coords != null && coords.equals(point)) { return true; } } return false; } /* * For working in the debugger * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return this.geocode + " " + this.name; } @Override public int hashCode() { return StringUtils.defaultString(geocode).hashCode(); } @Override public boolean equals(final Object obj) { // TODO: explain the following line or remove this non-standard equality method // just compare the geocode even if that is not what "equals" normally does return this == obj || (obj instanceof Geocache && StringUtils.isNotEmpty(geocode) && geocode.equals(((Geocache) obj).geocode)); } public void store(final CancellableHandler handler) { store(StoredList.TEMPORARY_LIST.id, handler); } public void store(final int listId, final CancellableHandler handler) { final int newListId = listId < StoredList.STANDARD_LIST_ID ? Math.max(getListId(), StoredList.STANDARD_LIST_ID) : listId; storeCache(this, null, newListId, false, handler); } @Override public int getId() { return 0; } @Override public WaypointType getWaypointType() { return null; } @Override public String getCoordType() { return "cache"; } public Subscription drop(final Handler handler, final Scheduler scheduler) { return scheduler.createWorker().schedule(new Action0() { @Override public void call() { try { dropSynchronous(); handler.sendMessage(Message.obtain()); } catch (final Exception e) { Log.e("cache.drop: ", e); } } }); } public void dropSynchronous() { DataStore.markDropped(Collections.singletonList(this)); DataStore.removeCache(getGeocode(), EnumSet.of(RemoveFlag.CACHE)); } public void checkFields() { if (StringUtils.isBlank(getGeocode())) { Log.w("geo code not parsed correctly for " + geocode); } if (StringUtils.isBlank(getName())) { Log.w("name not parsed correctly for " + geocode); } if (StringUtils.isBlank(getGuid())) { Log.w("guid not parsed correctly for " + geocode); } if (getTerrain() == 0.0) { Log.w("terrain not parsed correctly for " + geocode); } if (getDifficulty() == 0.0) { Log.w("difficulty not parsed correctly for " + geocode); } if (StringUtils.isBlank(getOwnerDisplayName())) { Log.w("owner display name not parsed correctly for " + geocode); } if (StringUtils.isBlank(getOwnerUserId())) { Log.w("owner user id real not parsed correctly for " + geocode); } if (getHiddenDate() == null) { Log.w("hidden not parsed correctly for " + geocode); } if (getFavoritePoints() < 0) { Log.w("favoriteCount not parsed correctly for " + geocode); } if (getSize() == null) { Log.w("size not parsed correctly for " + geocode); } if (getType() == null || getType() == CacheType.UNKNOWN) { Log.w("type not parsed correctly for " + geocode); } if (getCoords() == null) { Log.w("coordinates not parsed correctly for " + geocode); } if (StringUtils.isBlank(getLocation())) { Log.w("location not parsed correctly for " + geocode); } } public Subscription refresh(final CancellableHandler handler, final Scheduler scheduler) { return scheduler.createWorker().schedule(new Action0() { @Override public void call() { refreshSynchronous(handler); } }); } public void refreshSynchronous(final CancellableHandler handler) { DataStore.removeCache(geocode, EnumSet.of(RemoveFlag.CACHE)); storeCache(null, geocode, listId, true, handler); } public static void storeCache(final Geocache origCache, final String geocode, final int listId, final boolean forceRedownload, final CancellableHandler handler) { try { Geocache cache = null; // get cache details, they may not yet be complete if (origCache != null) { SearchResult search = null; // only reload the cache if it was already stored or doesn't have full details (by checking the description) if (origCache.isOffline() || StringUtils.isBlank(origCache.getDescription())) { search = searchByGeocode(origCache.getGeocode(), null, listId, false, handler); } if (search != null) { cache = search.getFirstCacheFromResult(LoadFlags.LOAD_CACHE_OR_DB); } else { cache = origCache; } } else if (StringUtils.isNotBlank(geocode)) { final SearchResult search = searchByGeocode(geocode, null, listId, forceRedownload, handler); if (search != null) { cache = search.getFirstCacheFromResult(LoadFlags.LOAD_CACHE_OR_DB); } } if (cache == null) { if (handler != null) { handler.sendMessage(Message.obtain()); } return; } if (CancellableHandler.isCancelled(handler)) { return; } final HtmlImage imgGetter = new HtmlImage(cache.getGeocode(), false, listId, true); // store images from description if (StringUtils.isNotBlank(cache.getDescription())) { Html.fromHtml(cache.getDescription(), imgGetter, null); } if (CancellableHandler.isCancelled(handler)) { return; } // store spoilers if (CollectionUtils.isNotEmpty(cache.getSpoilers())) { for (final Image oneSpoiler : cache.getSpoilers()) { imgGetter.getDrawable(oneSpoiler.getUrl()); } } if (CancellableHandler.isCancelled(handler)) { return; } // store images from logs if (Settings.isStoreLogImages()) { for (final LogEntry log : cache.getLogs()) { if (log.hasLogImages()) { for (final Image oneLogImg : log.getLogImages()) { imgGetter.getDrawable(oneLogImg.getUrl()); } } } } if (CancellableHandler.isCancelled(handler)) { return; } cache.setListId(listId); DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB)); if (CancellableHandler.isCancelled(handler)) { return; } RxUtils.waitForCompletion(StaticMapsProvider.downloadMaps(cache), imgGetter.waitForEndObservable(handler)); if (handler != null) { handler.sendEmptyMessage(CancellableHandler.DONE); } } catch (final Exception e) { Log.e("Geocache.storeCache", e); } } public static SearchResult searchByGeocode(final String geocode, final String guid, final int listId, final boolean forceReload, final CancellableHandler handler) { if (StringUtils.isBlank(geocode) && StringUtils.isBlank(guid)) { Log.e("Geocache.searchByGeocode: No geocode nor guid given"); return null; } if (!forceReload && listId == StoredList.TEMPORARY_LIST.id && (DataStore.isOffline(geocode, guid) || DataStore.isThere(geocode, guid, true, true))) { final SearchResult search = new SearchResult(); final String realGeocode = StringUtils.isNotBlank(geocode) ? geocode : DataStore.getGeocodeForGuid(guid); search.addGeocode(realGeocode); return search; } // if we have no geocode, we can't dynamically select the handler, but must explicitly use GC if (geocode == null && guid != null) { return GCConnector.getInstance().searchByGeocode(null, guid, handler); } final IConnector connector = ConnectorFactory.getConnector(geocode); if (connector instanceof ISearchByGeocode) { return ((ISearchByGeocode) connector).searchByGeocode(geocode, guid, handler); } return null; } public boolean isOffline() { return listId >= StoredList.STANDARD_LIST_ID; } /** * guess an event start time from the description * * @return start time in minutes after midnight */ public String guessEventTimeMinutes() { if (!isEventCache()) { return null; } final String hourLocalized = CgeoApplication.getInstance().getString(R.string.cache_time_full_hours); final ArrayList<Pattern> patterns = new ArrayList<>(); // 12:34 patterns.add(Pattern.compile("\\b(\\d{1,2})\\:(\\d\\d)\\b")); if (StringUtils.isNotBlank(hourLocalized)) { // 17 - 20 o'clock patterns.add(Pattern.compile("\\b(\\d{1,2})(?:\\.00)?" + "\\s*(?:-|[a-z]+)\\s*" + "(?:\\d{1,2})(?:\\.00)?" + "\\s+" + Pattern.quote(hourLocalized), Pattern.CASE_INSENSITIVE)); // 12 o'clock, 12.00 o'clock patterns.add(Pattern.compile("\\b(\\d{1,2})(?:\\.00)?\\s+" + Pattern.quote(hourLocalized), Pattern.CASE_INSENSITIVE)); } final String searchText = getShortDescription() + ' ' + getDescription(); for (final Pattern pattern : patterns) { final MatcherWrapper matcher = new MatcherWrapper(pattern, searchText); while (matcher.find()) { try { final int hours = Integer.parseInt(matcher.group(1)); int minutes = 0; if (matcher.groupCount() >= 2) { minutes = Integer.parseInt(matcher.group(2)); } if (hours >= 0 && hours < 24 && minutes >= 0 && minutes < 60) { return String.valueOf(hours * 60 + minutes); } } catch (final NumberFormatException ignored) { // cannot happen, but static code analysis doesn't know } } } return null; } public boolean hasStaticMap() { return StaticMapsProvider.hasStaticMap(this); } public static final Predicate<Geocache> hasStaticMap = new Predicate<Geocache>() { @Override public boolean evaluate(final Geocache cache) { return cache.hasStaticMap(); } }; public Collection<Image> getImages() { final LinkedList<Image> result = new LinkedList<>(); result.addAll(getSpoilers()); addLocalSpoilersTo(result); for (final LogEntry log : getLogs()) { result.addAll(log.getLogImages()); } ImageUtils.addImagesFromHtml(result, getDescription(), geocode); return result; } /** * Add spoilers stored locally in <tt>/sdcard/GeocachePhotos</tt>. If a cache is named GC123ABC, the * directory will be <tt>/sdcard/GeocachePhotos/C/B/GC123ABC/</tt>. * * @param spoilers the list to add to */ private void addLocalSpoilersTo(final List<Image> spoilers) { if (StringUtils.length(geocode) >= 2) { final String suffix = StringUtils.right(geocode, 2); final File baseDir = new File(Environment.getExternalStorageDirectory(), "GeocachePhotos"); final File lastCharDir = new File(baseDir, suffix.substring(1)); final File secondToLastCharDir = new File(lastCharDir, suffix.substring(0, 1)); final File finalDir = new File(secondToLastCharDir, geocode); final File[] files = finalDir.listFiles(); if (files != null) { for (final File image : files) { spoilers.add(new Image("file://" + image.getAbsolutePath(), image.getName())); } } } } public void setDetailedUpdatedNow() { final long now = System.currentTimeMillis(); setUpdated(now); setDetailedUpdate(now); setDetailed(true); } /** * Gets whether the user has logged the specific log type for this cache. Only checks the currently stored logs of * the cache, so the result might be wrong. */ public boolean hasOwnLog(final LogType logType) { for (final LogEntry logEntry : getLogs()) { if (logEntry.type == logType && logEntry.isOwn()) { return true; } } return false; } public int getMapMarkerId() { return getConnector().getCacheMapMarkerId(isDisabled() || isArchived()); } public boolean isLogPasswordRequired() { return logPasswordRequired; } public void setLogPasswordRequired(final boolean required) { logPasswordRequired = required; } public String getWaypointGpxId(final String prefix) { return getConnector().getWaypointGpxId(prefix, geocode); } public String getWaypointPrefix(final String name) { return getConnector().getWaypointPrefix(name); } /** * Get number of overall finds for a cache, or 0 if the number of finds is not known. * * @return */ public int getFindsCount() { if (getLogCounts().isEmpty()) { setLogCounts(DataStore.loadLogCounts(getGeocode())); } final Integer logged = getLogCounts().get(LogType.FOUND_IT); if (logged != null) { return logged; } return 0; } public boolean applyDistanceRule() { return (getType().applyDistanceRule() || hasUserModifiedCoords()) && getConnector() == GCConnector.getInstance(); } public LogType getDefaultLogType() { if (isEventCache()) { final Date eventDate = getHiddenDate(); final boolean expired = DateUtils.isPastEvent(this); if (hasOwnLog(LogType.WILL_ATTEND) || expired || (eventDate != null && DateUtils.daysSince(eventDate.getTime()) == 0)) { return hasOwnLog(LogType.ATTENDED) ? LogType.NOTE : LogType.ATTENDED; } return LogType.WILL_ATTEND; } if (isFound()) { return LogType.NOTE; } if (getType() == CacheType.WEBCAM) { return LogType.WEBCAM_PHOTO_TAKEN; } return LogType.FOUND_IT; } }
package groovy.util; import groovy.lang.Closure; import groovy.lang.GroovyShell; import java.util.logging.Logger; import junit.framework.TestCase; import org.codehaus.groovy.runtime.InvokerHelper; /** * A default JUnit TestCase in Groovy. This provides a number of helper methods * plus avoids the JUnit restriction of requiring all test* methods to be void * return type. * * @author <a href="mailto:bob@werken.com">bob mcwhirter</a> * @author <a href="mailto:james@coredevelopers.net">James Strachan</a> * @version $Revision$ */ public class GroovyTestCase extends TestCase { protected Logger log = Logger.getLogger(getClass().getName()); private static int counter; private boolean useAgileDoxNaming = false; public GroovyTestCase() { } /** * Overload the getName() method to make the test cases look more like AgileDox * (thanks to Joe Walnes for this tip!) */ public String getName() { if (useAgileDoxNaming) { return super.getName().substring(4).replaceAll("([A-Z])", " $1").toLowerCase(); } else { return super.getName(); } } public String getMethodName() { return super.getName(); } /** * Asserts that the arrays are equivalent and contain the same values * * @param expected * @param value */ protected void assertArrayEquals(Object[] expected, Object[] value) { String message = "expected array: " + InvokerHelper.toString(expected) + " value array: " + InvokerHelper.toString(value); assertNotNull(message + ": expected should not be null", expected); assertNotNull(message + ": value should not be null", value); assertEquals(message, expected.length, value.length); for (int i = 0, size = expected.length; i < size; i++) { assertEquals("value[" + i + "] when " + message, expected[i], value[i]); } } /** * Asserts that the array of characters has a given length * * @param length expected length * @param array the array */ protected void assertLength(int length, char[] array) { assertEquals(length, array.length); } /** * Asserts that the array of ints has a given length * * @param length expected length * @param array the array */ protected void assertLength(int length, int[] array) { assertEquals(length, array.length); } /** * Asserts that the array of objects has a given length * * @param length expected length * @param array the array */ protected void assertLength(int length, Object[] array) { assertEquals(length, array.length); } /** * Asserts that the array of characters contains a given char * * @param expected expected character to be found * @param array the array */ protected void assertContains(char expected, char[] array) { for (int i = 0; i < array.length; ++i) { if (array[i] == expected) { return; } } StringBuffer message = new StringBuffer(); message.append(expected + " not in {"); for (int i = 0; i < array.length; ++i) { message.append("'" + array[i] + "'"); if (i < (array.length - 1)) { message.append(", "); } } message.append(" }"); fail(message.toString()); } /** * Asserts that the array of ints contains a given int * * @param expected expected int * @param array the array */ protected void assertContains(int expected, int[] array) { for (int i = 0; i < array.length; ++i) { if (array[i] == expected) { return; } } StringBuffer message = new StringBuffer(); message.append(expected + " not in {"); for (int i = 0; i < array.length; ++i) { message.append("'" + array[i] + "'"); if (i < (array.length - 1)) { message.append(", "); } } message.append(" }"); fail(message.toString()); } /** * Asserts that the value of toString() on the given object matches the * given text string * * @param value the object to be output to the console * @param expected the expected String representation */ protected void assertToString(Object value, String expected) { Object console = InvokerHelper.invokeMethod(value, "toString", null); assertEquals("toString() on value: " + value, expected, console); } /** * Asserts that the value of inspect() on the given object matches the * given text string * * @param value the object to be output to the console * @param expected the expected String representation */ protected void assertInspect(Object value, String expected) { Object console = InvokerHelper.invokeMethod(value, "inspect", null); assertEquals("inspect() on value: " + value, expected, console); } /** * Asserts that the script runs without any exceptions * * @param script the script that should pass without any exception thrown */ protected void assertScript(final String script) throws Exception { GroovyShell shell = new GroovyShell(); shell.evaluate(script, getTestClassName()); } protected String getTestClassName() { return "TestScript" + getMethodName() + (counter++) + ".groovy"; } /** * Asserts that the given code closure fails when it is evaluated * * @param code */ protected void shouldFail(Closure code) { boolean failed = false; try { code.call(); } catch (Exception e) { failed = true; } assertTrue("Closure " + code + " should have failed", failed); } /** * Asserts that the given code closure fails when it is evaluated * and that a particular exception is thrown. * * @param clazz the class of the expected exception * @param code the closure that should fail */ protected void shouldFail(Class clazz, Closure code) { boolean failed = false; try { code.call(); } catch (Exception e) { if (clazz.isInstance(e)) { failed = true; } assertTrue("Closure " + code + " should have failed with an exception of type " + clazz.getName() + ", instead got Exception " + e, failed); return; } assertTrue("Closure " + code + " should have failed with an exception of type " + clazz.getName(), failed); } /** * Returns a copy of a string in which all EOLs are \n. */ protected String fixEOLs( String value ) { return value.replaceAll( "(\\r\\n?)|\n", "\n" ); } }
public class P0912 { public static int editDist(String s1, String s2) { int n = s1.length(); int m = s2.length(); // by default, r[0][] = 0, r[][0] = 0 int[][] r = new int[n + 1][m + 1]; int[][] s = new int[n + 1][m + 1]; editDistHelper(s1, s2, r, s); return r[n][m]; } private static void editDistHelper(String s1, String s2, int[][] r, int[][] s) { } public static void main(String[] args) {} }
package cgeo.geocaching; import cgeo.geocaching.DataStore.StorageLocation; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.activity.SimpleWebviewActivity; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.IConnector; import cgeo.geocaching.connector.ILoggingManager; import cgeo.geocaching.connector.capability.ISearchByCenter; import cgeo.geocaching.connector.capability.ISearchByGeocode; import cgeo.geocaching.connector.gc.GCConnector; import cgeo.geocaching.connector.gc.GCConstants; import cgeo.geocaching.connector.gc.Tile; import cgeo.geocaching.connector.gc.UncertainProperty; import cgeo.geocaching.connector.trackable.TrackableBrand; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag; import cgeo.geocaching.enumerations.LoadFlags.SaveFlag; import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.files.GPXParser; import cgeo.geocaching.list.StoredList; import cgeo.geocaching.location.Geopoint; import cgeo.geocaching.network.HtmlImage; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.utils.CalendarUtils; import cgeo.geocaching.utils.CancellableHandler; import cgeo.geocaching.utils.ImageUtils; import cgeo.geocaching.utils.LazyInitializedList; import cgeo.geocaching.utils.Log; import cgeo.geocaching.utils.LogTemplateProvider; import cgeo.geocaching.utils.LogTemplateProvider.LogContext; import cgeo.geocaching.utils.MatcherWrapper; import cgeo.geocaching.utils.RxUtils; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.ListUtils; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.Parcelable; import android.text.Html; import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.EnumMap; import java.util.EnumSet; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import rx.Scheduler; import rx.Subscription; import rx.functions.Action0; import rx.schedulers.Schedulers; /** * Internal representation of a "cache" */ public class Geocache implements IWaypoint { private static final int OWN_WP_PREFIX_OFFSET = 17; private long updated = 0; private long detailedUpdate = 0; private long visitedDate = 0; private int listId = StoredList.TEMPORARY_LIST.id; private boolean detailed = false; @NonNull private String geocode = ""; private String cacheId = ""; private String guid = ""; private UncertainProperty<CacheType> cacheType = new UncertainProperty<>(CacheType.UNKNOWN, Tile.ZOOMLEVEL_MIN - 1); private String name = ""; private String ownerDisplayName = ""; private String ownerUserId = ""; @Nullable private Date hidden = null; /** * lazy initialized */ private String hint = null; @NonNull private CacheSize size = CacheSize.UNKNOWN; private float difficulty = 0; private float terrain = 0; private Float direction = null; private Float distance = null; /** * lazy initialized */ private String location = null; private UncertainProperty<Geopoint> coords = new UncertainProperty<>(null); private boolean reliableLatLon = false; private String personalNote = null; /** * lazy initialized */ private String shortdesc = null; /** * lazy initialized */ private String description = null; private Boolean disabled = null; private Boolean archived = null; private Boolean premiumMembersOnly = null; private Boolean found = null; private Boolean favorite = null; private Boolean onWatchlist = null; private Boolean logOffline = null; private int favoritePoints = 0; private float rating = 0; // valid ratings are larger than zero private int votes = 0; private float myVote = 0; // valid ratings are larger than zero private int inventoryItems = 0; private final LazyInitializedList<String> attributes = new LazyInitializedList<String>() { @Override public List<String> call() { return inDatabase() ? DataStore.loadAttributes(geocode) : new LinkedList<String>(); } }; private final LazyInitializedList<Waypoint> waypoints = new LazyInitializedList<Waypoint>() { @Override public List<Waypoint> call() { return inDatabase() ? DataStore.loadWaypoints(geocode) : new LinkedList<Waypoint>(); } }; private List<Image> spoilers = null; private List<Trackable> inventory = null; private Map<LogType, Integer> logCounts = new EnumMap<>(LogType.class); private boolean userModifiedCoords = false; // temporary values private boolean statusChecked = false; private String directionImg = ""; private String nameForSorting; private final EnumSet<StorageLocation> storageLocation = EnumSet.of(StorageLocation.HEAP); private boolean finalDefined = false; private boolean logPasswordRequired = false; private LogEntry offlineLogs = null; private static final Pattern NUMBER_PATTERN = Pattern.compile("\\d+"); private Handler changeNotificationHandler = null; /** * Create a new cache. To be used everywhere except for the GPX parser */ public Geocache() { // empty } /** * Cache constructor to be used by the GPX parser only. This constructor explicitly sets several members to empty * lists. * * @param gpxParser ignored parameter allowing to select this constructor */ public Geocache(final GPXParser gpxParser) { setReliableLatLon(true); setAttributes(Collections.<String> emptyList()); setWaypoints(Collections.<Waypoint> emptyList(), false); } public void setChangeNotificationHandler(final Handler newNotificationHandler) { changeNotificationHandler = newNotificationHandler; } /** * Sends a change notification to interested parties */ private void notifyChange() { if (changeNotificationHandler != null) { changeNotificationHandler.sendEmptyMessage(0); } } /** * Gather missing information for new Geocache object from the stored Geocache object. * This is called in the new Geocache parsed from website to set information not yet * parsed. * * @param other * the other version, or null if non-existent * @return true if this cache is "equal" to the other version */ public boolean gatherMissingFrom(final Geocache other) { if (other == null) { return false; } if (other == this) { return true; } updated = System.currentTimeMillis(); // if parsed cache is not yet detailed and stored is, the information of // the parsed cache will be overwritten if (!detailed && other.detailed) { detailed = true; detailedUpdate = other.detailedUpdate; // boolean values must be enumerated here. Other types are assigned outside this if-statement reliableLatLon = other.reliableLatLon; finalDefined = other.finalDefined; } if (premiumMembersOnly == null) { premiumMembersOnly = other.premiumMembersOnly; } if (found == null) { found = other.found; } if (disabled == null) { disabled = other.disabled; } if (favorite == null) { favorite = other.favorite; } if (archived == null) { archived = other.archived; } if (onWatchlist == null) { onWatchlist = other.onWatchlist; } if (logOffline == null) { logOffline = other.logOffline; } if (visitedDate == 0) { visitedDate = other.visitedDate; } if (listId == StoredList.TEMPORARY_LIST.id) { listId = other.listId; } if (StringUtils.isBlank(geocode)) { geocode = other.geocode; } if (StringUtils.isBlank(cacheId)) { cacheId = other.cacheId; } if (StringUtils.isBlank(guid)) { guid = other.guid; } cacheType = UncertainProperty.getMergedProperty(cacheType, other.cacheType); if (StringUtils.isBlank(name)) { name = other.name; } if (StringUtils.isBlank(ownerDisplayName)) { ownerDisplayName = other.ownerDisplayName; } if (StringUtils.isBlank(ownerUserId)) { ownerUserId = other.ownerUserId; } if (hidden == null) { hidden = other.hidden; } if (!detailed && StringUtils.isBlank(getHint())) { hint = other.getHint(); } if (size == CacheSize.UNKNOWN) { size = other.size; } if (difficulty == 0) { difficulty = other.difficulty; } if (terrain == 0) { terrain = other.terrain; } if (direction == null) { direction = other.direction; } if (distance == null) { distance = other.distance; } if (StringUtils.isBlank(getLocation())) { location = other.getLocation(); } coords = UncertainProperty.getMergedProperty(coords, other.coords); // don't use StringUtils.isBlank here. Otherwise we cannot recognize a note which was deleted on GC if (personalNote == null) { personalNote = other.personalNote; } else if (other.personalNote != null && !personalNote.equals(other.personalNote)) { final PersonalNote myNote = new PersonalNote(this); final PersonalNote otherNote = new PersonalNote(other); final PersonalNote mergedNote = myNote.mergeWith(otherNote); personalNote = mergedNote.toString(); } if (!detailed && StringUtils.isBlank(getShortDescription())) { shortdesc = other.getShortDescription(); } if (StringUtils.isBlank(getDescription())) { description = other.getDescription(); } // FIXME: this makes no sense to favor this over the other. 0 should not be a special case here as it is // in the range of acceptable values. This is probably the case at other places (rating, votes, etc.) too. if (favoritePoints == 0) { favoritePoints = other.favoritePoints; } if (rating == 0) { rating = other.rating; } if (votes == 0) { votes = other.votes; } if (myVote == 0) { myVote = other.myVote; } if (!detailed && attributes.isEmpty()) { if (other.attributes != null) { attributes.addAll(other.attributes); } } if (waypoints.isEmpty()) { this.setWaypoints(other.waypoints, false); } else { final List<Waypoint> newPoints = new ArrayList<>(waypoints); Waypoint.mergeWayPoints(newPoints, other.waypoints, false); this.setWaypoints(newPoints, false); } if (spoilers == null) { spoilers = other.spoilers; } if (inventory == null) { // If inventoryItems is 0, it can mean both // "don't know" or "0 items". Since we cannot distinguish // them here, only populate inventoryItems from // old data when we have to do it for inventory. setInventory(other.inventory); } if (logCounts.isEmpty()) { logCounts = other.logCounts; } // if cache has ORIGINAL type waypoint ... it is considered that it has modified coordinates, otherwise not userModifiedCoords = false; for (final Waypoint wpt : waypoints) { if (wpt.getWaypointType() == WaypointType.ORIGINAL) { userModifiedCoords = true; break; } } if (!reliableLatLon) { reliableLatLon = other.reliableLatLon; } return isEqualTo(other); } /** * Compare two caches quickly. For map and list fields only the references are compared ! * * @param other * the other cache to compare this one to * @return true if both caches have the same content */ @SuppressWarnings("deprecation") @SuppressFBWarnings("FE_FLOATING_POINT_EQUALITY") private boolean isEqualTo(final Geocache other) { return detailed == other.detailed && StringUtils.equalsIgnoreCase(geocode, other.geocode) && StringUtils.equalsIgnoreCase(name, other.name) && cacheType == other.cacheType && size == other.size && ObjectUtils.equals(found, other.found) && ObjectUtils.equals(premiumMembersOnly, other.premiumMembersOnly) && difficulty == other.difficulty && terrain == other.terrain && (coords != null ? coords.equals(other.coords) : null == other.coords) && reliableLatLon == other.reliableLatLon && ObjectUtils.equals(disabled, other.disabled) && ObjectUtils.equals(archived, other.archived) && listId == other.listId && StringUtils.equalsIgnoreCase(ownerDisplayName, other.ownerDisplayName) && StringUtils.equalsIgnoreCase(ownerUserId, other.ownerUserId) && StringUtils.equalsIgnoreCase(getDescription(), other.getDescription()) && StringUtils.equalsIgnoreCase(personalNote, other.personalNote) && StringUtils.equalsIgnoreCase(getShortDescription(), other.getShortDescription()) && StringUtils.equalsIgnoreCase(getLocation(), other.getLocation()) && ObjectUtils.equals(favorite, other.favorite) && favoritePoints == other.favoritePoints && ObjectUtils.equals(onWatchlist, other.onWatchlist) && (hidden != null ? hidden.equals(other.hidden) : null == other.hidden) && StringUtils.equalsIgnoreCase(guid, other.guid) && StringUtils.equalsIgnoreCase(getHint(), other.getHint()) && StringUtils.equalsIgnoreCase(cacheId, other.cacheId) && (direction != null ? direction.equals(other.direction) : null == other.direction) && (distance != null ? distance.equals(other.distance) : null == other.distance) && rating == other.rating && votes == other.votes && myVote == other.myVote && inventoryItems == other.inventoryItems && attributes == other.attributes && waypoints == other.waypoints && spoilers == other.spoilers && inventory == other.inventory && logCounts == other.logCounts && ObjectUtils.equals(logOffline, other.logOffline) && finalDefined == other.finalDefined; } public boolean hasTrackables() { return inventoryItems > 0; } public boolean canBeAddedToCalendar() { // is event type? if (!isEventCache()) { return false; } // has event date set? if (hidden == null) { return false; } // is not in the past? final Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); assert hidden != null; // Eclipse compiler issue return hidden.compareTo(cal.getTime()) >= 0; } public boolean isEventCache() { return cacheType.getValue().isEvent(); } public void logVisit(final Activity fromActivity) { if (!getConnector().canLog(this)) { ActivityMixin.showToast(fromActivity, fromActivity.getResources().getString(R.string.err_cannot_log_visit)); return; } fromActivity.startActivity(LogCacheActivity.getLogCacheIntent(fromActivity, cacheId, geocode)); } public void logOffline(final Activity fromActivity, final LogType logType) { final boolean mustIncludeSignature = StringUtils.isNotBlank(Settings.getSignature()) && Settings.isAutoInsertSignature(); final String initial = mustIncludeSignature ? LogTemplateProvider.applyTemplates(Settings.getSignature(), new LogContext(this, null, true)) : ""; logOffline(fromActivity, initial, Calendar.getInstance(), logType); } void logOffline(final Activity fromActivity, final String log, final Calendar date, final LogType logType) { if (logType == LogType.UNKNOWN) { return; } final boolean status = DataStore.saveLogOffline(geocode, date.getTime(), logType, log); final Resources res = fromActivity.getResources(); if (status) { ActivityMixin.showToast(fromActivity, res.getString(R.string.info_log_saved)); DataStore.saveVisitDate(geocode); logOffline = Boolean.TRUE; notifyChange(); } else { ActivityMixin.showToast(fromActivity, res.getString(R.string.err_log_post_failed)); } } /** * Get the Offline Log entry if any. * * @return * The Offline LogEntry */ @Nullable public LogEntry getOfflineLog() { if (isLogOffline() && offlineLogs == null) { offlineLogs = DataStore.loadLogOffline(geocode); } return offlineLogs; } /** * Get the Offline Log entry if any. * * @return * The Offline LogEntry else Null */ @Nullable public LogType getOfflineLogType() { final LogEntry offlineLog = getOfflineLog(); if (offlineLog == null) { return null; } return offlineLog.type; } /** * Drop offline log for a given geocode. */ public void clearOfflineLog() { DataStore.clearLogOffline(geocode); notifyChange(); } @NonNull public List<LogType> getPossibleLogTypes() { return getConnector().getPossibleLogTypes(this); } public void openInBrowser(final Activity fromActivity) { if (getUrl() == null) { return; } final Intent viewIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getLongUrl())); // Check if cgeo is the default, show the chooser to let the user choose a browser if (viewIntent.resolveActivity(fromActivity.getPackageManager()).getPackageName().equals(fromActivity.getPackageName())) { final Intent chooser = Intent.createChooser(viewIntent, fromActivity.getString(R.string.cache_menu_browser)); final Intent internalBrowser = new Intent(fromActivity, SimpleWebviewActivity.class); internalBrowser.setData(Uri.parse(getUrl())); chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] {internalBrowser}); fromActivity.startActivity(chooser); } else { fromActivity.startActivity(viewIntent); } } @NonNull private IConnector getConnector() { return ConnectorFactory.getConnector(this); } public boolean supportsRefresh() { return getConnector() instanceof ISearchByGeocode; } public boolean supportsWatchList() { return getConnector().supportsWatchList(); } public boolean supportsFavoritePoints() { return getConnector().supportsFavoritePoints(this); } public boolean supportsLogging() { return getConnector().supportsLogging(); } public boolean supportsLogImages() { return getConnector().supportsLogImages(); } public boolean supportsOwnCoordinates() { return getConnector().supportsOwnCoordinates(); } @NonNull public ILoggingManager getLoggingManager(final LogCacheActivity activity) { return getConnector().getLoggingManager(activity, this); } public float getDifficulty() { return difficulty; } @Override @NonNull public String getGeocode() { return geocode; } /** * @return displayed owner, might differ from the real owner */ public String getOwnerDisplayName() { return ownerDisplayName; } @NonNull public CacheSize getSize() { return size; } public float getTerrain() { return terrain; } public boolean isArchived() { return BooleanUtils.isTrue(archived); } public boolean isDisabled() { return BooleanUtils.isTrue(disabled); } public boolean isPremiumMembersOnly() { return BooleanUtils.isTrue(premiumMembersOnly); } public void setPremiumMembersOnly(final boolean members) { this.premiumMembersOnly = members; } /** * * @return {@code true} if the user is the owner of the cache, {@code false} otherwise */ public boolean isOwner() { return getConnector().isOwner(this); } /** * @return GC username of the (actual) owner, might differ from the owner. Never empty. */ @NonNull public String getOwnerUserId() { return ownerUserId; } /** * Attention, calling this method may trigger a database access for the cache! * * @return the decrypted hint */ public String getHint() { initializeCacheTexts(); assertTextNotNull(hint, "Hint"); return hint; } /** * After lazy loading the lazily loaded field must be non {@code null}. * */ private static void assertTextNotNull(final String field, final String name) throws InternalError { if (field == null) { throw new InternalError(name + " field is not allowed to be null here"); } } /** * Attention, calling this method may trigger a database access for the cache! */ public String getDescription() { initializeCacheTexts(); assertTextNotNull(description, "Description"); return description; } /** * loads long text parts of a cache on demand (but all fields together) */ private void initializeCacheTexts() { if (description == null || shortdesc == null || hint == null || location == null) { if (inDatabase()) { final Geocache partial = DataStore.loadCacheTexts(this.getGeocode()); if (description == null) { setDescription(partial.getDescription()); } if (shortdesc == null) { setShortDescription(partial.getShortDescription()); } if (hint == null) { setHint(partial.getHint()); } if (location == null) { setLocation(partial.getLocation()); } } else { description = StringUtils.defaultString(description); shortdesc = StringUtils.defaultString(shortdesc); hint = StringUtils.defaultString(hint); location = StringUtils.defaultString(location); } } } /** * Attention, calling this method may trigger a database access for the cache! */ public String getShortDescription() { initializeCacheTexts(); assertTextNotNull(shortdesc, "Short description"); return shortdesc; } @Override public String getName() { return name; } public String getCacheId() { if (StringUtils.isBlank(cacheId) && getConnector().equals(GCConnector.getInstance())) { return String.valueOf(GCConstants.gccodeToGCId(geocode)); } return cacheId; } public String getGuid() { return guid; } /** * Attention, calling this method may trigger a database access for the cache! */ public String getLocation() { initializeCacheTexts(); assertTextNotNull(location, "Location"); return location; } public String getPersonalNote() { // non premium members have no personal notes, premium members have an empty string by default. // map both to null, so other code doesn't need to differentiate return StringUtils.defaultIfBlank(personalNote, null); } public boolean supportsCachesAround() { return getConnector() instanceof ISearchByCenter; } public void shareCache(@NonNull final Activity fromActivity, final Resources res) { final Intent intent = getShareIntent(); fromActivity.startActivity(Intent.createChooser(intent, res.getText(R.string.cache_menu_share))); } @NonNull public Intent getShareIntent() { final StringBuilder subject = new StringBuilder("Geocache "); subject.append(geocode); if (StringUtils.isNotBlank(name)) { subject.append(" - ").append(name); } final Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, subject.toString()); intent.putExtra(Intent.EXTRA_TEXT, StringUtils.defaultString(getUrl())); return intent; } @Nullable public String getUrl() { return getConnector().getCacheUrl(this); } @Nullable public String getLongUrl() { return getConnector().getLongCacheUrl(this); } @Nullable public String getCgeoUrl() { return getConnector().getCacheUrl(this); } public boolean supportsGCVote() { return StringUtils.startsWithIgnoreCase(geocode, "GC"); } public void setDescription(final String description) { this.description = description; } public boolean isFound() { return BooleanUtils.isTrue(found); } /** * * @return {@code true} if the user has put a favorite point onto this cache */ public boolean isFavorite() { return BooleanUtils.isTrue(favorite); } public void setFavorite(final boolean favorite) { this.favorite = favorite; } @Nullable public Date getHiddenDate() { if (hidden != null) { return new Date(hidden.getTime()); } return null; } @NonNull public List<String> getAttributes() { return attributes.getUnderlyingList(); } public void addSpoiler(final Image spoiler) { if (spoilers == null) { spoilers = new ArrayList<>(); } spoilers.add(spoiler); } @NonNull public List<Image> getSpoilers() { return ListUtils.unmodifiableList(ListUtils.emptyIfNull(spoilers)); } /** * @return a statistic how often the caches has been found, disabled, archived etc. */ public Map<LogType, Integer> getLogCounts() { return logCounts; } public int getFavoritePoints() { return favoritePoints; } /** * @return the normalized cached name to be used for sorting, taking into account the numerical parts in the name */ public String getNameForSorting() { if (null == nameForSorting) { nameForSorting = name; // pad each number part to a fixed size of 6 digits, so that numerical sorting becomes equivalent to string sorting MatcherWrapper matcher = new MatcherWrapper(NUMBER_PATTERN, nameForSorting); int start = 0; while (matcher.find(start)) { final String number = matcher.group(); nameForSorting = StringUtils.substring(nameForSorting, 0, matcher.start()) + StringUtils.leftPad(number, 6, '0') + StringUtils.substring(nameForSorting, matcher.start() + number.length()); start = matcher.start() + Math.max(6, number.length()); matcher = new MatcherWrapper(NUMBER_PATTERN, nameForSorting); } } return nameForSorting; } public boolean isVirtual() { return cacheType.getValue().isVirtual(); } public boolean showSize() { return !(size == CacheSize.NOT_CHOSEN || isEventCache() || isVirtual()); } public long getUpdated() { return updated; } public void setUpdated(final long updated) { this.updated = updated; } public long getDetailedUpdate() { return detailedUpdate; } public void setDetailedUpdate(final long detailedUpdate) { this.detailedUpdate = detailedUpdate; } public long getVisitedDate() { return visitedDate; } public void setVisitedDate(final long visitedDate) { this.visitedDate = visitedDate; } public int getListId() { return listId; } public void setListId(final int listId) { this.listId = listId; } public boolean isDetailed() { return detailed; } public void setDetailed(final boolean detailed) { this.detailed = detailed; } public void setHidden(@Nullable final Date hidden) { this.hidden = hidden != null ? new Date(hidden.getTime()) : null; } public Float getDirection() { return direction; } public void setDirection(final Float direction) { this.direction = direction; } public Float getDistance() { return distance; } public void setDistance(final Float distance) { this.distance = distance; } @Override public Geopoint getCoords() { return coords.getValue(); } public int getCoordZoomLevel() { return coords.getCertaintyLevel(); } /** * Set reliable coordinates */ public void setCoords(final Geopoint coords) { this.coords = new UncertainProperty<>(coords); } /** * Set unreliable coordinates from a certain map zoom level */ public void setCoords(final Geopoint coords, final int zoomlevel) { this.coords = new UncertainProperty<>(coords, zoomlevel); } /** * @return true if the coords are from the cache details page and the user has been logged in */ public boolean isReliableLatLon() { return getConnector().isReliableLatLon(reliableLatLon); } public void setReliableLatLon(final boolean reliableLatLon) { this.reliableLatLon = reliableLatLon; } public void setShortDescription(final String shortdesc) { this.shortdesc = shortdesc; } public void setFavoritePoints(final int favoriteCnt) { this.favoritePoints = favoriteCnt; } public float getRating() { return rating; } public void setRating(final float rating) { this.rating = rating; } public int getVotes() { return votes; } public void setVotes(final int votes) { this.votes = votes; } public float getMyVote() { return myVote; } public void setMyVote(final float myVote) { this.myVote = myVote; } /** * Get the current inventory count * * @return the inventory size */ public int getInventoryItems() { return inventoryItems; } /** * Set the current inventory count * * @param inventoryItems the new inventory size */ public void setInventoryItems(final int inventoryItems) { this.inventoryItems = inventoryItems; } /** * Get the current inventory * * @return the Geocache inventory */ public List<Trackable> getInventory() { return inventory; } /** * Replace the inventory with new content. * No check are performed. * * @param newInventory to set on Geocache */ public void setInventory(final List<Trackable> newInventory) { inventory = newInventory; inventoryItems = CollectionUtils.size(inventory); } /** * Add new Trackables to inventory safely. * This take care of removing old items if they are from the same brand. * If items are present, data are merged, not duplicated. * * @param newTrackables to be added to the Geocache */ public void mergeInventory(final List<Trackable> newTrackables, final EnumSet<TrackableBrand> processedBrands) { final List<Trackable> mergedTrackables = new ArrayList<>(newTrackables); for (final Trackable trackable : ListUtils.emptyIfNull(inventory)) { if (processedBrands.contains(trackable.getBrand())) { final ListIterator<Trackable> iterator = mergedTrackables.listIterator(); while (iterator.hasNext()) { final Trackable newTrackable = iterator.next(); if (trackable.getUniqueID().equals(newTrackable.getUniqueID())) { // Respect the merge order. New Values replace existing values. trackable.mergeTrackable(newTrackable); iterator.set(trackable); break; } } } else { mergedTrackables.add(trackable); } } setInventory(mergedTrackables); } /** * Add new Trackable to inventory safely. * If items are present, data are merged, not duplicated. * * @param newTrackable to be added to the Geocache */ public void addInventoryItem(final Trackable newTrackable) { if (inventory == null) { inventory = new ArrayList<>(); } boolean foundTrackable = false; for (final Trackable trackable: inventory) { if (trackable.getUniqueID().equals(newTrackable.getUniqueID())) { // Trackable already present, merge data foundTrackable = true; trackable.mergeTrackable(newTrackable); break; } } if (!foundTrackable) { inventory.add(newTrackable); } inventoryItems = inventory.size(); } /** * @return {@code true} if the cache is on the user's watchlist, {@code false} otherwise */ public boolean isOnWatchlist() { return BooleanUtils.isTrue(onWatchlist); } public void setOnWatchlist(final boolean onWatchlist) { this.onWatchlist = onWatchlist; } /** * return an immutable list of waypoints. * * @return always non <code>null</code> */ @NonNull public List<Waypoint> getWaypoints() { return waypoints.getUnderlyingList(); } /** * @param waypoints * List of waypoints to set for cache * @param saveToDatabase * Indicates whether to add the waypoints to the database. Should be false if * called while loading or building a cache * @return <code>true</code> if waypoints successfully added to waypoint database */ public boolean setWaypoints(final List<Waypoint> waypoints, final boolean saveToDatabase) { this.waypoints.clear(); if (waypoints != null) { this.waypoints.addAll(waypoints); } finalDefined = false; if (waypoints != null) { for (final Waypoint waypoint : waypoints) { waypoint.setGeocode(geocode); if (waypoint.isFinalWithCoords()) { finalDefined = true; } } } return saveToDatabase && DataStore.saveWaypoints(this); } /** * The list of logs is immutable, because it is directly fetched from the database on demand, and not stored at this * object. If you want to modify logs, you have to load all logs of the cache, create a new list from the existing * list and store that new list in the database. * * @return immutable list of logs */ @NonNull public List<LogEntry> getLogs() { return inDatabase() ? DataStore.loadLogs(geocode) : Collections.<LogEntry>emptyList(); } /** * @return only the logs of friends */ @NonNull public List<LogEntry> getFriendsLogs() { final List<LogEntry> friendLogs = new ArrayList<>(); for (final LogEntry log : getLogs()) { if (log.friend) { friendLogs.add(log); } } return Collections.unmodifiableList(friendLogs); } public boolean isLogOffline() { return BooleanUtils.isTrue(logOffline); } public void setLogOffline(final boolean logOffline) { this.logOffline = logOffline; } public boolean isStatusChecked() { return statusChecked; } public void setStatusChecked(final boolean statusChecked) { this.statusChecked = statusChecked; } public String getDirectionImg() { return directionImg; } public void setDirectionImg(final String directionImg) { this.directionImg = directionImg; } public void setGeocode(@NonNull final String geocode) { this.geocode = StringUtils.upperCase(geocode); } public void setCacheId(final String cacheId) { this.cacheId = cacheId; } public void setGuid(final String guid) { this.guid = guid; } public void setName(final String name) { this.name = name; } public void setOwnerDisplayName(final String ownerDisplayName) { this.ownerDisplayName = ownerDisplayName; } public void setOwnerUserId(final String ownerUserId) { this.ownerUserId = ownerUserId; } public void setHint(final String hint) { this.hint = hint; } public void setSize(@NonNull final CacheSize size) { this.size = size; } public void setDifficulty(final float difficulty) { this.difficulty = difficulty; } public void setTerrain(final float terrain) { this.terrain = terrain; } public void setLocation(final String location) { this.location = location; } public void setPersonalNote(final String personalNote) { this.personalNote = StringUtils.trimToNull(personalNote); } public void setDisabled(final boolean disabled) { this.disabled = disabled; } public void setArchived(final boolean archived) { this.archived = archived; } public void setFound(final boolean found) { this.found = found; } public void setAttributes(final List<String> attributes) { this.attributes.clear(); if (attributes != null) { this.attributes.addAll(attributes); } } public void setSpoilers(final List<Image> spoilers) { this.spoilers = spoilers; } public void setLogCounts(final Map<LogType, Integer> logCounts) { this.logCounts = logCounts; } /* * (non-Javadoc) * * @see cgeo.geocaching.IBasicCache#getType() * * @returns Never null */ public CacheType getType() { return cacheType.getValue(); } public void setType(final CacheType cacheType) { if (cacheType == null || CacheType.ALL == cacheType) { throw new IllegalArgumentException("Illegal cache type"); } this.cacheType = new UncertainProperty<>(cacheType); } public void setType(final CacheType cacheType, final int zoomlevel) { if (cacheType == null || CacheType.ALL == cacheType) { throw new IllegalArgumentException("Illegal cache type"); } this.cacheType = new UncertainProperty<>(cacheType, zoomlevel); } public boolean hasDifficulty() { return difficulty > 0f; } public boolean hasTerrain() { return terrain > 0f; } /** * @return the storageLocation */ public EnumSet<StorageLocation> getStorageLocation() { return storageLocation; } /** * @param storageLocation * the storageLocation to set */ public void addStorageLocation(final StorageLocation storageLocation) { this.storageLocation.add(storageLocation); } /** * Check if this cache instance comes from or has been stored into the database. */ public boolean inDatabase() { return storageLocation.contains(StorageLocation.DATABASE); } /** * @param waypoint * Waypoint to add to the cache * @param saveToDatabase * Indicates whether to add the waypoint to the database. Should be false if * called while loading or building a cache * @return <code>true</code> if waypoint successfully added to waypoint database */ public boolean addOrChangeWaypoint(final Waypoint waypoint, final boolean saveToDatabase) { waypoint.setGeocode(geocode); if (waypoint.getId() < 0) { // this is a new waypoint if (StringUtils.isBlank(waypoint.getPrefix())) { assignUniquePrefix(waypoint); } waypoints.add(waypoint); if (waypoint.isFinalWithCoords()) { finalDefined = true; } } else { // this is a waypoint being edited final int index = getWaypointIndex(waypoint); if (index >= 0) { final Waypoint oldWaypoint = waypoints.remove(index); waypoint.setPrefix(oldWaypoint.getPrefix()); //migration if (StringUtils.isBlank(waypoint.getPrefix()) || StringUtils.equalsIgnoreCase(waypoint.getPrefix(), Waypoint.PREFIX_OWN)) { assignUniquePrefix(waypoint); } } waypoints.add(waypoint); // when waypoint was edited, finalDefined may have changed resetFinalDefined(); } return saveToDatabase && DataStore.saveWaypoint(waypoint.getId(), geocode, waypoint); } /* * Assigns a unique two-digit (compatibility with gc.com) * prefix within the scope of this cache. */ private void assignUniquePrefix(final Waypoint waypoint) { // gather existing prefixes final Set<String> assignedPrefixes = new HashSet<>(); for (final Waypoint wp : waypoints) { assignedPrefixes.add(wp.getPrefix()); } for (int i = OWN_WP_PREFIX_OFFSET; i < 100; i++) { final String prefixCandidate = String.valueOf(i); if (!assignedPrefixes.contains(prefixCandidate)) { waypoint.setPrefix(prefixCandidate); return; } } throw new IllegalStateException("too many waypoints, unable to assign unique prefix"); } public boolean hasWaypoints() { return !waypoints.isEmpty(); } public boolean hasFinalDefined() { return finalDefined; } // Only for loading public void setFinalDefined(final boolean finalDefined) { this.finalDefined = finalDefined; } /** * Reset <code>finalDefined</code> based on current list of stored waypoints */ private void resetFinalDefined() { finalDefined = false; for (final Waypoint wp : waypoints) { if (wp.isFinalWithCoords()) { finalDefined = true; break; } } } public boolean hasUserModifiedCoords() { return userModifiedCoords; } public void setUserModifiedCoords(final boolean coordsChanged) { userModifiedCoords = coordsChanged; } /** * Duplicate a waypoint. * * @param original * the waypoint to duplicate * @return <code>true</code> if the waypoint was duplicated, <code>false</code> otherwise (invalid index) */ public boolean duplicateWaypoint(final Waypoint original) { if (original == null) { return false; } final int index = getWaypointIndex(original); final Waypoint copy = new Waypoint(original); copy.setUserDefined(); copy.setName(CgeoApplication.getInstance().getString(R.string.waypoint_copy_of) + " " + copy.getName()); waypoints.add(index + 1, copy); return DataStore.saveWaypoint(-1, geocode, copy); } /** * delete a user defined waypoint * * @param waypoint * to be removed from cache * @return <code>true</code>, if the waypoint was deleted */ public boolean deleteWaypoint(final Waypoint waypoint) { if (waypoint == null) { return false; } if (waypoint.getId() < 0) { return false; } if (waypoint.isUserDefined()) { final int index = getWaypointIndex(waypoint); waypoints.remove(index); DataStore.deleteWaypoint(waypoint.getId()); DataStore.removeCache(geocode, EnumSet.of(RemoveFlag.CACHE)); // Check status if Final is defined if (waypoint.isFinalWithCoords()) { resetFinalDefined(); } return true; } return false; } /** * deletes any waypoint */ public void deleteWaypointForce(final Waypoint waypoint) { final int index = getWaypointIndex(waypoint); waypoints.remove(index); DataStore.deleteWaypoint(waypoint.getId()); DataStore.removeCache(geocode, EnumSet.of(RemoveFlag.CACHE)); resetFinalDefined(); } /** * Find index of given <code>waypoint</code> in cache's <code>waypoints</code> list * * @param waypoint * to find index for * @return index in <code>waypoints</code> if found, -1 otherwise */ private int getWaypointIndex(final Waypoint waypoint) { final int id = waypoint.getId(); for (int index = 0; index < waypoints.size(); index++) { if (waypoints.get(index).getId() == id) { return index; } } return -1; } /** * Lookup a waypoint by its id. * * @param id * the id of the waypoint to look for * @return waypoint or <code>null</code> */ public Waypoint getWaypointById(final int id) { for (final Waypoint waypoint : waypoints) { if (waypoint.getId() == id) { return waypoint; } } return null; } /** * Detect coordinates in the personal note and convert them to user defined waypoints. Works by rule of thumb. */ public boolean parseWaypointsFromNote() { boolean changed = false; for (final Waypoint waypoint : Waypoint.parseWaypointsFromNote(StringUtils.defaultString(getPersonalNote()))) { if (!hasIdenticalWaypoint(waypoint.getCoords())) { addOrChangeWaypoint(waypoint, false); changed = true; } } return changed; } private boolean hasIdenticalWaypoint(final Geopoint point) { for (final Waypoint waypoint: waypoints) { // waypoint can have no coords such as a Final set by cache owner final Geopoint coords = waypoint.getCoords(); if (coords != null && coords.equals(point)) { return true; } } return false; } /* * For working in the debugger * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return this.geocode + " " + this.name; } @Override public int hashCode() { return StringUtils.defaultString(geocode).hashCode(); } @Override public boolean equals(final Object obj) { // TODO: explain the following line or remove this non-standard equality method // just compare the geocode even if that is not what "equals" normally does return this == obj || (obj instanceof Geocache && StringUtils.isNotEmpty(geocode) && geocode.equals(((Geocache) obj).geocode)); } public void store() { store(StoredList.TEMPORARY_LIST.id, null); } public void store(final int listId, final CancellableHandler handler) { final int newListId = listId < StoredList.STANDARD_LIST_ID ? Math.max(getListId(), StoredList.STANDARD_LIST_ID) : listId; storeCache(this, null, newListId, false, handler); } @Override public int getId() { return 0; } @Override public WaypointType getWaypointType() { return null; } @Override public String getCoordType() { return "cache"; } public Subscription drop(final Handler handler) { return Schedulers.io().createWorker().schedule(new Action0() { @Override public void call() { try { dropSynchronous(); handler.sendMessage(Message.obtain()); } catch (final Exception e) { Log.e("cache.drop: ", e); } } }); } public void dropSynchronous() { DataStore.markDropped(Collections.singletonList(this)); DataStore.removeCache(getGeocode(), EnumSet.of(RemoveFlag.CACHE)); } private void warnIncorrectParsingIf(final boolean incorrect, final String field) { if (incorrect) { Log.w(field + " not parsed correctly for " + geocode); } } private void warnIncorrectParsingIfBlank(final String str, final String field) { warnIncorrectParsingIf(StringUtils.isBlank(str), field); } public void checkFields() { warnIncorrectParsingIfBlank(getGeocode(), "geo"); warnIncorrectParsingIfBlank(getName(), "name"); warnIncorrectParsingIfBlank(getGuid(), "guid"); warnIncorrectParsingIf(getTerrain() == 0.0, "terrain"); warnIncorrectParsingIf(getDifficulty() == 0.0, "difficulty"); warnIncorrectParsingIfBlank(getOwnerDisplayName(), "owner"); warnIncorrectParsingIfBlank(getOwnerUserId(), "owner"); warnIncorrectParsingIf(getHiddenDate() == null, "hidden"); warnIncorrectParsingIf(getFavoritePoints() < 0, "favoriteCount"); warnIncorrectParsingIf(getSize() == CacheSize.UNKNOWN, "size"); warnIncorrectParsingIf(getType() == null || getType() == CacheType.UNKNOWN, "type"); warnIncorrectParsingIf(getCoords() == null, "coordinates"); warnIncorrectParsingIfBlank(getLocation(), "location"); } public Subscription refresh(final CancellableHandler handler, final Scheduler scheduler) { return scheduler.createWorker().schedule(new Action0() { @Override public void call() { refreshSynchronous(handler); } }); } public void refreshSynchronous(final CancellableHandler handler) { DataStore.removeCache(geocode, EnumSet.of(RemoveFlag.CACHE)); storeCache(null, geocode, listId, true, handler); } public static void storeCache(final Geocache origCache, final String geocode, final int listId, final boolean forceRedownload, final CancellableHandler handler) { try { Geocache cache = null; // get cache details, they may not yet be complete if (origCache != null) { SearchResult search = null; // only reload the cache if it was already stored or doesn't have full details (by checking the description) if (origCache.isOffline() || StringUtils.isBlank(origCache.getDescription())) { search = searchByGeocode(origCache.getGeocode(), null, listId, false, handler); } if (search != null) { cache = search.getFirstCacheFromResult(LoadFlags.LOAD_CACHE_OR_DB); } else { cache = origCache; } } else if (StringUtils.isNotBlank(geocode)) { final SearchResult search = searchByGeocode(geocode, null, listId, forceRedownload, handler); if (search != null) { cache = search.getFirstCacheFromResult(LoadFlags.LOAD_CACHE_OR_DB); } } if (cache == null) { if (handler != null) { handler.sendMessage(Message.obtain()); } return; } if (CancellableHandler.isCancelled(handler)) { return; } final HtmlImage imgGetter = new HtmlImage(cache.getGeocode(), false, listId, true); // store images from description if (StringUtils.isNotBlank(cache.getDescription())) { Html.fromHtml(cache.getDescription(), imgGetter, null); } if (CancellableHandler.isCancelled(handler)) { return; } // store spoilers if (CollectionUtils.isNotEmpty(cache.getSpoilers())) { for (final Image oneSpoiler : cache.getSpoilers()) { imgGetter.getDrawable(oneSpoiler.getUrl()); } } if (CancellableHandler.isCancelled(handler)) { return; } // store images from logs if (Settings.isStoreLogImages()) { for (final LogEntry log : cache.getLogs()) { if (log.hasLogImages()) { for (final Image oneLogImg : log.getLogImages()) { imgGetter.getDrawable(oneLogImg.getUrl()); } } } } if (CancellableHandler.isCancelled(handler)) { return; } cache.setListId(listId); DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB)); if (CancellableHandler.isCancelled(handler)) { return; } RxUtils.waitForCompletion(StaticMapsProvider.downloadMaps(cache), imgGetter.waitForEndObservable(handler)); if (handler != null) { handler.sendEmptyMessage(CancellableHandler.DONE); } } catch (final Exception e) { Log.e("Geocache.storeCache", e); } } public static SearchResult searchByGeocode(final String geocode, final String guid, final int listId, final boolean forceReload, final CancellableHandler handler) { if (StringUtils.isBlank(geocode) && StringUtils.isBlank(guid)) { Log.e("Geocache.searchByGeocode: No geocode nor guid given"); return null; } if (!forceReload && listId == StoredList.TEMPORARY_LIST.id && (DataStore.isOffline(geocode, guid) || DataStore.isThere(geocode, guid, true))) { final SearchResult search = new SearchResult(); final String realGeocode = StringUtils.isNotBlank(geocode) ? geocode : DataStore.getGeocodeForGuid(guid); search.addGeocode(realGeocode); return search; } // if we have no geocode, we can't dynamically select the handler, but must explicitly use GC if (geocode == null) { return GCConnector.getInstance().searchByGeocode(null, guid, handler); } final IConnector connector = ConnectorFactory.getConnector(geocode); if (connector instanceof ISearchByGeocode) { return ((ISearchByGeocode) connector).searchByGeocode(geocode, guid, handler); } return null; } public boolean isOffline() { return listId >= StoredList.STANDARD_LIST_ID; } /** * guess an event start time from the description * * @return start time in minutes after midnight */ public int guessEventTimeMinutes() { if (!isEventCache()) { return -1; } final String hourLocalized = CgeoApplication.getInstance().getString(R.string.cache_time_full_hours); final List<Pattern> patterns = new ArrayList<>(); // 12:34 patterns.add(Pattern.compile("\\b(\\d{1,2})\\:(\\d\\d)\\b")); if (StringUtils.isNotBlank(hourLocalized)) { // 12:34o'clock patterns.add(Pattern.compile("\\b(\\d{1,2})\\:(\\d\\d)" + Pattern.quote(hourLocalized), Pattern.CASE_INSENSITIVE)); // 17 - 20 o'clock patterns.add(Pattern.compile("\\b(\\d{1,2})(?:\\.00)?" + "\\s*(?:-|[a-z]+)\\s?" + "(?:\\d{1,2})(?:\\.00)?" + "\\s?" + Pattern.quote(hourLocalized), Pattern.CASE_INSENSITIVE)); // 12 o'clock, 12.00 o'clock patterns.add(Pattern.compile("\\b(\\d{1,2})(?:\\.(00|15|30|45))?\\s?" + Pattern.quote(hourLocalized), Pattern.CASE_INSENSITIVE)); } final String searchText = getShortDescription() + ' ' + getDescription(); for (final Pattern pattern : patterns) { final MatcherWrapper matcher = new MatcherWrapper(pattern, searchText); while (matcher.find()) { try { final int hours = Integer.parseInt(matcher.group(1)); int minutes = 0; if (matcher.groupCount() >= 2 && !StringUtils.isEmpty(matcher.group(2))) { minutes = Integer.parseInt(matcher.group(2)); } if (hours >= 0 && hours < 24 && minutes >= 0 && minutes < 60) { return hours * 60 + minutes; } } catch (final NumberFormatException ignored) { // cannot happen, but static code analysis doesn't know } } } return -1; } public boolean hasStaticMap() { return StaticMapsProvider.hasStaticMap(this); } @NonNull public Collection<Image> getImages() { final List<Image> result = new LinkedList<>(); result.addAll(getSpoilers()); addLocalSpoilersTo(result); for (final LogEntry log : getLogs()) { result.addAll(log.getLogImages()); } ImageUtils.addImagesFromHtml(result, geocode, getShortDescription(), getDescription()); return result; } /** * Add spoilers stored locally in <tt>/sdcard/GeocachePhotos</tt>. If a cache is named GC123ABC, the * directory will be <tt>/sdcard/GeocachePhotos/C/B/GC123ABC/</tt>. * * @param spoilers the list to add to */ private void addLocalSpoilersTo(final List<Image> spoilers) { if (StringUtils.length(geocode) >= 2) { final String suffix = StringUtils.right(geocode, 2); final File baseDir = new File(Environment.getExternalStorageDirectory(), "GeocachePhotos"); final File lastCharDir = new File(baseDir, suffix.substring(1)); final File secondToLastCharDir = new File(lastCharDir, suffix.substring(0, 1)); final File finalDir = new File(secondToLastCharDir, geocode); final File[] files = finalDir.listFiles(); if (files != null) { for (final File image : files) { spoilers.add(new Image("file://" + image.getAbsolutePath(), image.getName())); } } } } public void setDetailedUpdatedNow() { final long now = System.currentTimeMillis(); setUpdated(now); setDetailedUpdate(now); setDetailed(true); } /** * Gets whether the user has logged the specific log type for this cache. Only checks the currently stored logs of * the cache, so the result might be wrong. */ public boolean hasOwnLog(final LogType logType) { for (final LogEntry logEntry : getLogs()) { if (logEntry.type == logType && logEntry.isOwn()) { return true; } } return false; } public int getMapMarkerId() { return getConnector().getCacheMapMarkerId(isDisabled() || isArchived()); } public boolean isLogPasswordRequired() { return logPasswordRequired; } public void setLogPasswordRequired(final boolean required) { logPasswordRequired = required; } public String getWaypointGpxId(final String prefix) { return getConnector().getWaypointGpxId(prefix, geocode); } @NonNull public String getWaypointPrefix(final String name) { return getConnector().getWaypointPrefix(name); } /** * Get number of overall finds for a cache, or 0 if the number of finds is not known. */ public int getFindsCount() { if (getLogCounts().isEmpty()) { setLogCounts(inDatabase() ? DataStore.loadLogCounts(getGeocode()) : Collections.<LogType, Integer>emptyMap()); } final Integer logged = getLogCounts().get(LogType.FOUND_IT); if (logged != null) { return logged; } return 0; } public boolean applyDistanceRule() { return (getType().applyDistanceRule() || hasUserModifiedCoords()) && getConnector() == GCConnector.getInstance(); } @NonNull public LogType getDefaultLogType() { if (isEventCache()) { final Date eventDate = getHiddenDate(); final boolean expired = CalendarUtils.isPastEvent(this); if (hasOwnLog(LogType.WILL_ATTEND) || expired || (eventDate != null && CalendarUtils.daysSince(eventDate.getTime()) == 0)) { return hasOwnLog(LogType.ATTENDED) ? LogType.NOTE : LogType.ATTENDED; } return LogType.WILL_ATTEND; } if (isFound()) { return LogType.NOTE; } if (getType() == CacheType.WEBCAM) { return LogType.WEBCAM_PHOTO_TAKEN; } return LogType.FOUND_IT; } /** * Get the geocodes of a collection of caches. * * @param caches a collection of caches * @return the non-blank geocodes of the caches */ @NonNull public static Set<String> getGeocodes(@NonNull final Collection<Geocache> caches) { final Set<String> geocodes = new HashSet<>(caches.size()); for (final Geocache cache : caches) { final String geocode = cache.getGeocode(); if (StringUtils.isNotBlank(geocode)) { geocodes.add(geocode); } } return geocodes; } /** * Show the hint as toast message. If no hint is available, a default "no hint available" will be shown instead. */ public void showHintToast(final Activity activity) { final String hint = getHint(); ActivityMixin.showToast(activity, StringUtils.defaultIfBlank(hint, activity.getString(R.string.cache_hint_not_available))); } }
import java.awt.Point; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class StarUML { public static void main(String[] args) throws XPathExpressionException { File f = new File(args[0]); XML xml = new StarUML.XML(f); } public static class XML { public XML(File file) throws XPathExpressionException { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); doc = db.parse(file); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } xPath = XPathFactory.newInstance().newXPath(); sized = xPathEval(sizedXPath); positioned = xPathEval(positionedXPath); classViews = xPathEval(classViewsXPath); dependencyViews = xPathEval(dependencyViewsXPath); deeseViews = xPathEval(deeseViewsXPath); // TODO: Means of integrating non-View nodes as well into guidTable and typeTable. //List<Node> allOperations = xPathEval(allNodesXPath); // UMLView Factory-based construction Map<String,UMLView> guidTable = new HashMap<String,UMLView>(); Map<String,List<UMLView>> typeTable = new HashMap<String,List<UMLView>>(); UMLView.Factory vf = new XML.UMLViewFactory(guidTable,typeTable); List<UMLView> deeseViewsReally = new ArrayList<UMLView>(); for (Node n : deeseViews) deeseViewsReally.add(vf.newUMLView(n)); for (String type : typeTable.keySet()) { System.out.println(Global.leftPad(type+": ",60,"=")); for (UMLView v : typeTable.get(type)) System.out.println(v); } // UMLView Renderer construction float minx = 0x7fffffff; float miny = 0x7fffffff; float maxx = -1; float maxy = -1; for (UMLView v : deeseViewsReally) { if (v.hasPosition() && v.hasDimensions()) { if (v.left >= 0 && v.left < minx) minx = v.left; if (v.top >= 0 && v.top < miny) miny = v.top; if (v.left+v.width > maxx) maxx = v.left+v.width; if (v.top+v.height > maxy) maxy = v.top+v.height; } } final int marginx = 24; final int marginy = 20; SVG.BaseNode svgNode = new SVG.BaseNode((int)(maxx-minx)+2+2*marginx, (int)(maxy-miny)+1+2*marginy); SVG.BaseNode svgOffsetNode = new SVG.BaseNode((int)maxx+1+2, (int)maxy+1); svgOffsetNode.attributes.put("x", ""+(int)(-minx+1+marginx)); svgOffsetNode.attributes.put("y", ""+(int)(-miny+1+marginy)); svgNode.addChild(svgOffsetNode); UMLView.Renderer vr = new XML.UMLViewSVGRenderer(svgOffsetNode); //*/ //*/
package hivemall.utils.math; import java.util.Arrays; public final class Primes { private static final int[] PRIMES = { 3, 5, 7, 13, 19, 31, 43, 61, 73, 89, 103, 109, 139, 151, 181, 193, 199, 229, 241, 271, 283, 313, 349, 421, 433, 463, 523, 571, 601, 619, 661, 823, 859, 883, 1021, 1063, 1093, 1153, 1231, 1321, 1429, 1489, 1621, 1699, 1789, 1873, 1951, 2029, 2131, 2143, 2311, 2383, 2593, 2731, 2803, 3001, 3121, 3259, 3391, 3583, 3673, 3919, 4093, 4273, 4423, 4651, 4801, 5023, 5281, 5521, 5743, 5881, 6301, 6571, 6871, 7129, 7489, 7759, 8089, 8539, 8863, 9283, 9721, 10141, 10531, 11071, 11551, 12073, 12613, 13009, 13759, 14323, 14869, 15649, 16363, 17029, 17839, 18541, 19471, 20233, 21193, 22159, 23059, 24181, 25171, 26263, 27541, 28753, 30013, 31321, 32719, 34213, 35731, 37309, 38923, 40639, 42463, 44281, 46309, 48313, 50461, 52711, 55051, 57529, 60091, 62299, 65521, 68281, 71413, 74611, 77713, 81373, 84979, 88663, 92671, 96739, 100801, 105529, 109849, 115021, 120079, 125509, 131011, 136861, 142873, 149251, 155863, 162751, 169891, 177433, 185071, 193381, 202129, 211063, 220021, 229981, 240349, 250969, 262111, 273643, 285841, 298411, 311713, 325543, 339841, 355009, 370663, 386989, 404269, 422113, 440809, 460081, 480463, 501829, 524221, 547399, 571603, 596929, 623353, 651019, 679909, 709741, 741343, 774133, 808441, 844201, 881539, 920743, 961531, 1004119, 1048573, 1094923, 1143283, 1193911, 1246963, 1302181, 1359733, 1420039, 1482853, 1548541, 1616899, 1688413, 1763431, 1841293, 1922773, 2008081, 2097133, 2189989, 2286883, 2388163, 2493853, 2604013, 2719669, 2840041, 2965603, 3097123, 3234241, 3377191, 3526933, 3682363, 3845983, 4016041, 4193803, 4379719, 4573873, 4776223, 4987891, 5208523, 5439223, 5680153, 5931313, 6194191, 6468463, 6754879, 7053331, 7366069, 7692343, 8032639, 8388451, 8759953, 9147661, 9552733, 9975193, 10417291, 10878619, 11360203, 11863153, 12387841, 12936529, 13509343, 14107801, 14732413, 15384673, 16065559, 16777141, 17519893, 18295633, 19105483, 19951231, 20834689, 21757291, 22720591, 23726449, 24776953, 25873963, 27018853, 28215619, 29464579, 30769093, 32131711, 33554011, 35039911, 36591211, 38211163, 39903121, 41669479, 43514521, 45441199, 47452879, 49553941, 51747991, 54039079, 56431513, 58930021, 61539091, 64263571, 67108669, 70079959, 73182409, 76422793, 79806229, 83339383, 87029053, 90881083, 94906249, 99108043, 103495879, 108077731, 112863013, 117860053, 123078019, 128526943, 134217439, 140159911, 146365159, 152845393, 159612601, 166679173, 174058849, 181765093, 189812341, 198216103, 206991601, 216156043, 225726379, 235720159, 246156271, 257054491, 268435009, 280319203, 292730833, 305691181, 319225021, 333358513, 348117151, 363529759, 379624279, 396432481, 413983771, 432312511, 451452613, 471440161, 492312523, 514109251, 536870839, 560640001, 585461743, 611382451, 638450569, 666717199, 696235363, 727060069, 759249643, 792864871, 827967631, 864625033, 902905501, 942880663, 984625531, 1028218189, 1073741719, 1121280091, 1170923713, 1222764841, 1276901371, 1333434301, 1392470281, 1454120779, 1518500173, 1585729993, 1655935399, 1729249999, 1805811253, 1885761133, 1969251079, 2056437379, 2147482951, Integer.MAX_VALUE }; /** * Returns from a static prime table the least prime that is greater * than or equal to a specified value. */ public static int findLeastPrimeNumber(final int n) { assert (n >= 0) : n; int idx = Arrays.binarySearch(PRIMES, n); if(idx < 0) { idx = -idx - 1; if(idx >= PRIMES.length) { idx = PRIMES.length - 1; } return PRIMES[idx]; // if not found, use max prime (in this case 9973). } return PRIMES[idx]; } }
package com.skelril.aurora.shards.CursedMine; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.blocks.ItemID; import com.sk89q.worldedit.bukkit.BukkitPlayer; import com.sk89q.worldedit.bukkit.BukkitUtil; import com.sk89q.worldedit.bukkit.BukkitWorld; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.world.World; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import com.skelril.aurora.admin.AdminComponent; import com.skelril.aurora.exceptions.UnsupportedPrayerException; import com.skelril.aurora.prayer.PrayerComponent; import com.skelril.aurora.prayer.PrayerFX.InventoryFX; import com.skelril.aurora.prayer.PrayerType; import com.skelril.aurora.shards.BukkitShardInstance; import com.skelril.aurora.util.ChanceUtil; import com.skelril.aurora.util.ChatUtil; import com.skelril.aurora.util.LocationUtil; import com.skelril.aurora.util.item.ItemUtil; import com.skelril.aurora.util.restoration.BlockRecord; import com.skelril.aurora.util.restoration.PlayerMappedBlockRecordIndex; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.entity.*; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; import static com.sk89q.commandbook.CommandBook.inst; import static com.zachsthings.libcomponents.bukkit.BasePlugin.server; public class CursedMineInstance extends BukkitShardInstance<CursedMineShard> implements Runnable { private static final int[] items = new int[]{ BlockID.IRON_BLOCK, BlockID.IRON_ORE, ItemID.IRON_BAR, BlockID.GOLD_BLOCK, BlockID.GOLD_ORE, ItemID.GOLD_BAR, ItemID.GOLD_NUGGET, BlockID.REDSTONE_ORE, BlockID.GLOWING_REDSTONE_ORE, ItemID.REDSTONE_DUST, BlockID.LAPIS_LAZULI_BLOCK, BlockID.LAPIS_LAZULI_ORE, ItemID.INK_SACK, BlockID.DIAMOND_BLOCK, BlockID.DIAMOND_ORE, ItemID.DIAMOND, BlockID.EMERALD_BLOCK, BlockID.EMERALD_ORE, ItemID.EMERALD }; private CuboidRegion floodGate; private Location entryPoint; private final long lastActivationTime = 18000; private long lastActivation = 0; private PlayerMappedBlockRecordIndex recordSystem = new PlayerMappedBlockRecordIndex(); private int idleTicks = 0; private int ticks = 0; public CursedMineInstance(CursedMineShard shard, World world, ProtectedRegion region) { super(shard, world, region); remove(); setUp(); } private void setUp() { com.sk89q.worldedit.Vector offset = getRegion().getMinimumPoint(); entryPoint = new Location(getBukkitWorld(), offset.getX() + 71.5, offset.getY() + 59, offset.getZ() + 86.5); floodGate = new CuboidRegion(offset.add(66, 40, 131), offset.add(78, 40, 139)); } public void revertAll() { recordSystem.revertAll(); } public void randomRestore() { recordSystem.revertByTime(ChanceUtil.getRangedRandom(9000, 60000)); } public void revertPlayer(Player player) { recordSystem.revertByPlayer(player.getName()); } public void recordBlockBreak(Player player, BlockRecord record) { recordSystem.addItem(player.getName(), record); } public boolean hasRecordForPlayer(Player player) { return recordSystem.hasRecordForPlayer(player.getName()); } public void activatePumps() { long temp = lastActivation; lastActivation = System.currentTimeMillis(); if (System.currentTimeMillis() - temp <= lastActivationTime * 5) { lastActivation -= lastActivationTime * .4; } } @Override public void cleanUp() { revertAll(); super.cleanUp(); } @Override public void run() { ++ticks; ++idleTicks; if (!isEmpty()) { idleTicks = 0; equalize(); changeWater(); } else if (idleTicks > 60 * 5) { expire(); return; } if (ticks % 4 == 0) { drain(); sweepFloor(); randomRestore(); } } @Override public void teleportTo(com.sk89q.worldedit.entity.Player... players) { for (com.sk89q.worldedit.entity.Player player : players) { if (player instanceof BukkitPlayer) { Player bPlayer = ((BukkitPlayer) player).getPlayer(); bPlayer.teleport(entryPoint); } } } public void equalize() { getContained(Player.class).stream().forEach(getMaster().getAdmin()::deadmin); } public void eatFood(Player player) { if (player.getSaturation() - 1 >= 0) { player.setSaturation(player.getSaturation() - 1); } else if (player.getFoodLevel() - 1 >= 0) { player.setFoodLevel(player.getFoodLevel() - 1); } else if (player.getHealth() - 1 >= 0) { player.setHealth(player.getHealth() - 1); } } public void poison(Player player, int duration) { if (ChanceUtil.getChance(player.getLocation().getBlockY() / 2)) { player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 20 * duration, 2)); ChatUtil.sendWarning(player, "The ore releases a toxic gas poisoning you!"); } } public void ghost(final Player player, int blockID) { try { AdminComponent adminComponent = getMaster().getAdmin(); PrayerComponent prayerComponent = getMaster().getPrayer(); if (ChanceUtil.getChance(player.getLocation().getBlockY())) { if (ChanceUtil.getChance(2)) { switch (ChanceUtil.getRandom(6)) { case 1: ChatUtil.sendNotice(player, "Caspher the friendly ghost drops some bread."); player.getWorld().dropItemNaturally(player.getLocation(), new ItemStack(ItemID.BREAD, ChanceUtil.getRandom(16))); break; case 2: ChatUtil.sendNotice(player, "COOKIE gives you a cookie."); player.getWorld().dropItemNaturally(player.getLocation(), new ItemStack(ItemID.COOKIE)); break; case 3: ChatUtil.sendNotice(player, "Caspher the friendly ghost appears."); for (int i = 0; i < 8; i++) { player.getWorld().dropItemNaturally(player.getLocation(), new ItemStack(ItemID.IRON_BAR, ChanceUtil.getRandom(64))); player.getWorld().dropItemNaturally(player.getLocation(), new ItemStack(ItemID.GOLD_BAR, ChanceUtil.getRandom(64))); player.getWorld().dropItemNaturally(player.getLocation(), new ItemStack(ItemID.DIAMOND, ChanceUtil.getRandom(64))); } break; case 4: ChatUtil.sendNotice(player, "John gives you a new jacket."); player.getWorld().dropItemNaturally(player.getLocation(), new ItemStack(ItemID.LEATHER_CHEST)); break; case 5: ChatUtil.sendNotice(player, "Tim teleports items to you."); getContained(Item.class).forEach(i -> i.teleport(player)); // Add in some extra drops just in case the loot wasn't very juicy player.getWorld().dropItem(player.getLocation(), new ItemStack(ItemID.IRON_BAR, ChanceUtil.getRandom(64))); player.getWorld().dropItem(player.getLocation(), new ItemStack(ItemID.GOLD_BAR, ChanceUtil.getRandom(64))); player.getWorld().dropItem(player.getLocation(), new ItemStack(ItemID.DIAMOND, ChanceUtil.getRandom(64))); break; case 6: ChatUtil.sendNotice(player, "Dan gives you a sparkling touch."); int id; switch (ChanceUtil.getRandom(3)) { case 1: id = ItemID.IRON_BAR; break; case 2: id = ItemID.GOLD_BAR; break; case 3: id = ItemID.DIAMOND; break; default: id = ItemID.REDSTONE_DUST; break; } prayerComponent.influencePlayer(player, PrayerComponent.constructPrayer(player, new InventoryFX(id, 64), 5000)); break; default: break; } } else { if (ItemUtil.hasAncientArmor(player) && ChanceUtil.getChance(2)) { ChatUtil.sendNotice(player, ChatColor.AQUA, "Your armor blocks an incoming ghost attack."); return; } adminComponent.depowerPlayer(player); switch (ChanceUtil.getRandom(11)) { case 1: if (ChanceUtil.getChance(4)) { if (blockID == BlockID.DIAMOND_ORE) { getMaster().getHitList().addPlayer(player, this); ChatUtil.sendWarning(player, "You ignite fumes in the air!"); EditSession ess = WorldEdit.getInstance() .getEditSessionFactory() .getEditSession(new BukkitWorld(player.getWorld()), -1); try { ess.fillXZ(BukkitUtil.toVector(player.getLocation()), new BaseBlock(BlockID.FIRE), 20, 20, true); } catch (MaxChangedBlocksException ignored) { } for (int i = ChanceUtil.getRandom(24) + 20; i > 0; --i) { final boolean untele = i == 11; server().getScheduler().runTaskLater(inst(), () -> { if (untele) { recordSystem.revertByPlayer(player.getName()); getMaster().getHitList().remPlayer(player); } if (!contains(player)) return; Location l = LocationUtil.findRandomLoc(player.getLocation().getBlock(), 3, true, false); l.getWorld().createExplosion(l.getX(), l.getY(), l.getZ(), 3F, true, false); }, 12 * i); } } else { getMaster().getHitList().addPlayer(player, this); player.chat("Who's a good ghost?!?!"); server().getScheduler().runTaskLater(inst(), () -> { player.chat("Don't hurt me!!!"); server().getScheduler().runTaskLater(inst(), () -> { player.chat("Nooooooooooo!!!"); try { prayerComponent.influencePlayer(player, PrayerComponent.constructPrayer(player, PrayerType.CANNON, TimeUnit.MINUTES.toMillis(2))); } catch (UnsupportedPrayerException ex) { ex.printStackTrace(); } }, 20); }, 20); } break; } case 2: ChatUtil.sendWarning(player, "Dave attaches to your soul..."); for (int i = 20; i > 0; --i) { server().getScheduler().runTaskLater(inst(), () -> { if (!contains(player)) return; player.setHealth(ChanceUtil.getRandom(ChanceUtil.getRandom(player.getMaxHealth())) - 1); }, 12 * i); } break; case 3: ChatUtil.sendWarning(player, "George plays with fire, sadly too close to you."); prayerComponent.influencePlayer(player, PrayerComponent.constructPrayer(player, PrayerType.FIRE, TimeUnit.SECONDS.toMillis(45))); break; case 4: ChatUtil.sendWarning(player, "Simon says pick up sticks."); for (int i = 0; i < player.getInventory().getContents().length * 1.5; i++) { player.getWorld().dropItem(player.getLocation(), new ItemStack(ItemID.STICK, 64)); } break; case 5: ChatUtil.sendWarning(player, "Ben dumps out your backpack."); prayerComponent.influencePlayer(player, PrayerComponent.constructPrayer(player, PrayerType.BUTTERFINGERS, TimeUnit.SECONDS.toMillis(10))); break; case 6: ChatUtil.sendWarning(player, "Merlin attacks with a mighty rage!"); prayerComponent.influencePlayer(player, PrayerComponent.constructPrayer(player, PrayerType.MERLIN, TimeUnit.SECONDS.toMillis(20))); break; case 7: ChatUtil.sendWarning(player, "Dave tells everyone that your mining!"); Bukkit.broadcastMessage(ChatColor.GOLD + "The player: " + player.getDisplayName() + " is mining in the cursed mine!!!"); break; case 8: ChatUtil.sendWarning(player, "Dave likes your food."); getMaster().getHitList().addPlayer(player, this); prayerComponent.influencePlayer(player, PrayerComponent.constructPrayer(player, PrayerType.STARVATION, TimeUnit.MINUTES.toMillis(15))); break; case 9: ChatUtil.sendWarning(player, "Hallow declares war on YOU!"); for (int i = 0; i < ChanceUtil.getRangedRandom(10, 30); i++) { Blaze blaze = getBukkitWorld().spawn(player.getLocation(), Blaze.class); blaze.setTarget(player); blaze.setRemoveWhenFarAway(true); } break; case 10: ChatUtil.sendWarning(player, "A legion of hell hounds appears!"); for (int i = 0; i < ChanceUtil.getRangedRandom(10, 30); i++) { Wolf wolf = getBukkitWorld().spawn(player.getLocation(), Wolf.class); wolf.setTarget(player); wolf.setRemoveWhenFarAway(true); } break; case 11: if (blockID == BlockID.EMERALD_ORE) { ChatUtil.sendNotice(player, "Dave got a chemistry set!"); getMaster().getHitList().addPlayer(player, this); prayerComponent.influencePlayer(player, PrayerComponent.constructPrayer(player, PrayerType.DEADLYPOTION, TimeUnit.MINUTES.toMillis(30))); } else { ChatUtil.sendWarning(player, "Dave says hi, that's not good."); getMaster().getHitList().addPlayer(player, this); prayerComponent.influencePlayer(player, PrayerComponent.constructPrayer(player, PrayerType.SLAP, TimeUnit.MINUTES.toMillis(30))); prayerComponent.influencePlayer(player, PrayerComponent.constructPrayer(player, PrayerType.BUTTERFINGERS, TimeUnit.MINUTES.toMillis(30))); prayerComponent.influencePlayer(player, PrayerComponent.constructPrayer(player, PrayerType.FIRE, TimeUnit.MINUTES.toMillis(30))); } break; default: break; } } } } catch (UnsupportedPrayerException ex) { ex.printStackTrace(); } } private static Set<Integer> replaceableTypes = new HashSet<>(); static { replaceableTypes.add(BlockID.WATER); replaceableTypes.add(BlockID.STATIONARY_WATER); replaceableTypes.add(BlockID.WOOD); replaceableTypes.add(BlockID.AIR); } private void changeWater() { int id = 0; if (lastActivation == 0 || System.currentTimeMillis() - lastActivation >= lastActivationTime) { id = BlockID.WOOD; } com.sk89q.worldedit.Vector min = floodGate.getMinimumPoint(); com.sk89q.worldedit.Vector max = floodGate.getMaximumPoint(); int minX = min.getBlockX(); int minZ = min.getBlockZ(); int blockY = min.getBlockY(); int maxX = max.getBlockX(); int maxZ = max.getBlockZ(); for (int x = minX; x <= maxX; x++) { for (int z = minZ; z <= maxZ; z++) { Block block = getBukkitWorld().getBlockAt(x, blockY, z); if (!block.getChunk().isLoaded()) continue; if (replaceableTypes.contains(block.getTypeId())) { block.setTypeId(id); } } } } private boolean checkInventory(Player player) { if (!inst().hasPermission(player, "aurora.prayer.intervention")) return false; for (int aItem : items) { if (player.getInventory().containsAtLeast(new ItemStack(aItem), 1)) return true; } return false; } public void drain() { Location modifiable = new Location(getBukkitWorld(), 0, 0, 0); Location previousLoc; for (Entity e : getContained(InventoryHolder.class)) { Inventory eInventory = ((InventoryHolder) e).getInventory(); if (e instanceof Player) { if (getMaster().getAdmin().isAdmin((Player) e)) continue; modifiable = e.getLocation(modifiable); // Emerald long diff = System.currentTimeMillis() - lastActivation; if (modifiable.getY() < 30 && (lastActivation == 0 || diff <= lastActivationTime * .35 || diff >= lastActivationTime * 5)) { for (int i = 0; i < ChanceUtil.getRangedRandom(2, 5); i++) { previousLoc = modifiable.clone(); modifiable = LocationUtil.findRandomLoc(previousLoc, 5, true, false); if (modifiable.getBlock().getTypeId() != BlockID.AIR) { modifiable = previousLoc; } getBukkitWorld().spawn(modifiable, Blaze.class); } } } for (int i = 0; i < (ItemUtil.countFilledSlots(eInventory.getContents()) / 2) - 2 || i < 1; i++) { if (e instanceof Player) { if (ChanceUtil.getChance(15) && checkInventory((Player) e)) { ChatUtil.sendNotice((Player) e, "Divine intervention protects some of your items."); continue; } } // Iron ItemUtil.removeItemOfType((InventoryHolder) e, BlockID.IRON_BLOCK, ChanceUtil.getRandom(2), true); ItemUtil.removeItemOfType((InventoryHolder) e, BlockID.IRON_ORE, ChanceUtil.getRandom(4), true); ItemUtil.removeItemOfType((InventoryHolder) e, ItemID.IRON_BAR, ChanceUtil.getRandom(8), true); // Gold ItemUtil.removeItemOfType((InventoryHolder) e, BlockID.GOLD_BLOCK, ChanceUtil.getRandom(2), true); ItemUtil.removeItemOfType((InventoryHolder) e, BlockID.GOLD_ORE, ChanceUtil.getRandom(4), true); ItemUtil.removeItemOfType((InventoryHolder) e, ItemID.GOLD_BAR, ChanceUtil.getRandom(10), true); ItemUtil.removeItemOfType((InventoryHolder) e, ItemID.GOLD_NUGGET, ChanceUtil.getRandom(80), true); // Redstone ItemUtil.removeItemOfType((InventoryHolder) e, BlockID.REDSTONE_ORE, ChanceUtil.getRandom(2), true); ItemUtil.removeItemOfType((InventoryHolder) e, BlockID.GLOWING_REDSTONE_ORE, ChanceUtil.getRandom(2), true); ItemUtil.removeItemOfType((InventoryHolder) e, ItemID.REDSTONE_DUST, ChanceUtil.getRandom(34), true); // Lap ItemUtil.removeItemOfType((InventoryHolder) e, BlockID.LAPIS_LAZULI_BLOCK, ChanceUtil.getRandom(2), true); ItemUtil.removeItemOfType((InventoryHolder) e, BlockID.LAPIS_LAZULI_ORE, ChanceUtil.getRandom(4), true); eInventory.removeItem(new ItemStack(ItemID.INK_SACK, ChanceUtil.getRandom(34), (short) 4)); // Diamond ItemUtil.removeItemOfType((InventoryHolder) e, BlockID.DIAMOND_BLOCK, ChanceUtil.getRandom(2), true); ItemUtil.removeItemOfType((InventoryHolder) e, BlockID.DIAMOND_ORE, ChanceUtil.getRandom(4), true); ItemUtil.removeItemOfType((InventoryHolder) e, ItemID.DIAMOND, ChanceUtil.getRandom(16), true); } } } public void sweepFloor() { for (Item item : getContained(Item.class)) { if (!contains(item)) continue; int id = item.getItemStack().getTypeId(); for (int aItem : items) { if (aItem == id) { double newAmt = item.getItemStack().getAmount() * .8; if (newAmt < 1) { item.remove(); } else { item.getItemStack().setAmount((int) newAmt); } break; } } } } }
package mockit; import java.io.*; import mockit.integration.junit4.*; import static org.junit.Assert.*; import org.junit.*; import org.junit.runner.*; @RunWith(JMockit.class) public final class ExpectationsTest { static class Collaborator { private int value; Collaborator() {} Collaborator(int value) { this.value = value; } private static String doInternal() { return "123"; } void provideSomeService() {} int getValue() { return value; } void setValue(int value) { this.value = value; } } @Test public void expectNothingWithExplicitEndRecording() { new Expectations() { }.endRecording(); } @Test public void restoreFieldTypeRedefinitions(final Collaborator mock) { new Expectations() { { mock.getValue(); returns(2); } }; assertEquals(2, mock.getValue()); Mockit.restoreAllOriginalDefinitions(); assertEquals(0, mock.getValue()); } @Test public void mockInterface(final Runnable mock) { new Expectations() {{ mock.run(); }}; mock.run(); } public abstract static class AbstractCollaborator { String doSomethingConcrete() { return "test"; } protected abstract void doSomethingAbstract(); } @Test public void mockAbstractClass(final AbstractCollaborator mock) { new Expectations() { { mock.doSomethingConcrete(); mock.doSomethingAbstract(); } }; mock.doSomethingConcrete(); mock.doSomethingAbstract(); } @Test public void mockFinalField() { new Expectations() { final Collaborator mock = new Collaborator(); { mock.getValue(); } }; new Collaborator().getValue(); } @Test public void mockClassWithoutDefaultConstructor() { new Expectations() { Dummy mock; }; } static class Dummy { @SuppressWarnings({"UnusedDeclaration"}) Dummy(int i) {} } @Test public void mockSubclass() { new Expectations() { SubCollaborator mock = new SubCollaborator(); }; new SubCollaborator(); } static final class SubCollaborator extends Collaborator { } @Test(expected = IllegalStateException.class) public void attemptToRecordExpectedReturnValueForNoCurrentInvocation() { new Expectations() { Collaborator mock; { returns(42); } }; } @Test(expected = IllegalStateException.class) public void attemptToAddArgumentMatcherWhenNotRecording() { new Expectations() { Collaborator mock; { endRecording(); mock.setValue(withAny(5)); } }; } @Test public void mockClassWithMethodsOfAllReturnTypesReturningDefaultValues() { ClassWithMethodsOfEveryReturnType realObject = new ClassWithMethodsOfEveryReturnType(); new Expectations() { ClassWithMethodsOfEveryReturnType mock; { mock.getBoolean(); mock.getChar(); mock.getByte(); mock.getShort(); mock.getInt(); mock.getLong(); mock.getFloat(); mock.getDouble(); mock.getObject(); } }; assertFalse(realObject.getBoolean()); assertEquals('\0', realObject.getChar()); assertEquals(0, realObject.getByte()); assertEquals(0, realObject.getShort()); assertEquals(0, realObject.getInt()); assertEquals(0L, realObject.getLong()); assertEquals(0.0, realObject.getFloat(), 0.0); assertEquals(0.0, realObject.getDouble(), 0.0); assertNull(realObject.getObject()); } static class ClassWithMethodsOfEveryReturnType { boolean getBoolean() { return true; } char getChar() { return 'A' ; } byte getByte() { return 1; } short getShort() { return 1; } int getInt() { return 1; } long getLong() { return 1; } float getFloat() { return 1.0F; } double getDouble() { return 1.0; } Object getObject() { return new Object(); } } @Test(expected = AssertionError.class) public void replayWithUnexpectedMethodInvocation(final Collaborator mock) { new Expectations() { { mock.getValue(); } }; mock.provideSomeService(); } @Test(expected = AssertionError.class) public void replayWithUnexpectedStaticMethodInvocation() { new Expectations() { Collaborator mock; { mock.getValue(); } }; Collaborator.doInternal(); } @Test(expected = AssertionError.class) public void replayWithMissingExpectedMethodInvocation() { new Expectations() { Collaborator mock; { mock.setValue(123); } }; } @Test(expected = AssertionError.class) public void assertSatisfiedWithMissingExpectedMethodInvocation() { new Expectations() { Collaborator mock; { mock.setValue(123); } }; Expectations.assertSatisfied(); } @Test public void defineTwoConsecutiveReturnValues(final Collaborator mock) { new Expectations() { { mock.getValue(); returns(1); returns(2); } }; assertEquals(1, mock.getValue()); assertEquals(2, mock.getValue()); } @Test // Note: this test only works under JDK 1.6+; JDK 1.5 does not support redefining natives. public void mockNativeMethod() { new Expectations() { final System system = null; { System.nanoTime(); returns(0L); } }; assertEquals(0, System.nanoTime()); } @Test public void mockSystemGetenvMethod() { new Expectations() { System mockedSystem; { System.getenv("envVar"); returns("."); } }; assertEquals(".", System.getenv("envVar")); } @Test public void mockConstructorsInJREClassHierarchies() throws Exception { new Expectations() { final FileWriter fileWriter; PrintWriter printWriter; { fileWriter = new FileWriter("no.file"); } }; new FileWriter("no.file"); } }
package io.fabric8.che.starter.exception; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.UnknownHostException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import io.fabric8.kubernetes.client.KubernetesClientException; @RestControllerAdvice public class GlobalExceptionHandler { @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "URL is not valid") @ExceptionHandler({ URISyntaxException.class, MalformedURLException.class }) public String handleURLException(Exception e) { return e.getMessage(); } @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "MasterUrl is not valid") @ExceptionHandler(UnknownHostException.class) public String handleHostException(UnknownHostException e) { return e.getMessage(); } @ResponseStatus(value = HttpStatus.UNAUTHORIZED, reason = "Access is denied due to invalid credentials") @ExceptionHandler(KubernetesClientException.class) public String handleKubernetesClientException(KubernetesClientException e) { return e.getMessage(); } @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Route not found") @ExceptionHandler(RouteNotFoundException.class) public String handleRouteNotFoundException(RouteNotFoundException e) { return e.getMessage(); } @SuppressWarnings("restriction") @ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "Unable to find valid certification path to requested target") @ExceptionHandler(sun.security.provider.certpath.SunCertPathBuilderException.class) public String handleSunCertPathBuilderException(RouteNotFoundException e) { return e.getMessage(); } }
package org.codeforamerica.open311.internals.parsing; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.codeforamerica.open311.facade.data.AttributeInfo; import org.codeforamerica.open311.facade.data.AttributeInfo.Datatype; import org.codeforamerica.open311.facade.data.POSTServiceRequestResponse; import org.codeforamerica.open311.facade.data.Service; import org.codeforamerica.open311.facade.data.ServiceDefinition; import org.codeforamerica.open311.facade.data.ServiceDiscoveryInfo; import org.codeforamerica.open311.facade.data.ServiceRequest; import org.codeforamerica.open311.facade.data.ServiceRequest.Status; import org.codeforamerica.open311.facade.data.ServiceRequestIdResponse; import org.codeforamerica.open311.facade.exceptions.DataParsingException; import org.codeforamerica.open311.facade.exceptions.GeoReportV2Error; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class JSONParser extends AbstractParser { private static final String NULL_STRING_JSON = "null"; private DateParser dateParser = new DateParser(); @Override public List<Service> parseServiceList(String rawData) throws DataParsingException { List<Service> result = new LinkedList<Service>(); try { JSONArray serviceList = new JSONArray(rawData); for (int i = 0; i < serviceList.length(); i++) { JSONObject service = serviceList.getJSONObject(i); result.add(getService(service)); } } catch (Exception e) { throw new DataParsingException(e.getMessage()); } return result; } /** * Builds a {@link Service} object from a {@link JSONObject}. * * @param service * JSONObject which represents a service. * @return An object with its state given by the JSONObject * @throws JSONException * If the given service isn't correct. * @throws DataParsingException * If the received parameters are not valid. */ private Service getService(JSONObject service) throws JSONException, DataParsingException { String code = getString(service, SERVICE_CODE_TAG); String name = getString(service, SERVICE_NAME_TAG); String description = getString(service, DESCRIPTION_TAG); Boolean metadata = getBoolean(service, METADATA_TAG); String group = getString(service, SERVICE_GROUP_TAG); String[] keywords = getKeywords(getString(service, KEYWORDS_TAG)); Service.Type type = Service.Type.getFromString(getString(service, TYPE_TAG)); checkParameters(code); return new Service(code, name, description, metadata, type, keywords, group); } @Override public ServiceDefinition parseServiceDefinition(String rawData) throws DataParsingException { try { JSONObject serviceDefinition = new JSONObject(rawData); if (serviceDefinition.has(SERVICE_DEFINITION_TAG)) { serviceDefinition = serviceDefinition .getJSONObject(SERVICE_DEFINITION_TAG); } String serviceCode = getString(serviceDefinition, SERVICE_CODE_TAG); JSONArray attributesArray = serviceDefinition .getJSONArray(ATTRIBUTES_TAG); checkParameters(serviceCode); return new ServiceDefinition(serviceCode, parseAttributeList(attributesArray)); } catch (JSONException e) { throw new DataParsingException(e.getMessage()); } } /** * Parses the list of attributes attached to a service definition. * * @param attributesArray * The JSONArray object. * @return List of attributes. * @throws JSONException * If the given object is not correct. * @throws DataParsingException * If the code parameter is missing. */ private List<AttributeInfo> parseAttributeList(JSONArray attributesArray) throws JSONException, DataParsingException { List<AttributeInfo> attributes = new LinkedList<AttributeInfo>(); for (int i = 0; i < attributesArray.length(); i++) { JSONObject attribute = attributesArray.getJSONObject(i); Boolean variable = getBoolean(attribute, VARIABLE_TAG); String code = getString(attribute, CODE_TAG); Datatype datatype = Datatype.getFromString(getString(attribute, DATATYPE_TAG)); Boolean required = getBoolean(attribute, REQUIRED_TAG); String datatypeDescription = getString(attribute, DATATYPE_DESCRIPTION_TAG); Integer order = getInteger(attribute, ORDER_TAG); String description = getString(attribute, DESCRIPTION_TAG); Map<String, String> values = null; if (attribute.has(VALUES_TAG)) { JSONArray valuesArray = attribute.getJSONArray(VALUES_TAG); values = new HashMap<String, String>(); for (int j = 0; j < valuesArray.length(); j++) { JSONObject valueObject = valuesArray.getJSONObject(j); String key = getString(valueObject, KEY_TAG); String name = getString(valueObject, NAME_TAG); values.put(key, name); } } checkParameters(code); attributes.add(new AttributeInfo(variable, code, datatype, required, datatypeDescription, order, description, values)); } return attributes; } @Override public ServiceRequestIdResponse parseServiceRequestIdFromAToken( String rawData) throws DataParsingException { try { JSONArray responsesArray = new JSONArray(rawData); if (responsesArray.length() == 0) { return null; } JSONObject response = responsesArray.getJSONObject(0); String token = getString(response, TOKEN_TAG); String serviceRequestId = getString(response, SERVICE_REQUEST_ID_TAG); checkParameters(token, serviceRequestId); return new ServiceRequestIdResponse(serviceRequestId, token); } catch (Exception e) { throw new DataParsingException(e.getMessage()); } } @Override public List<ServiceRequest> parseServiceRequests(String rawData) throws DataParsingException { List<ServiceRequest> result = new LinkedList<ServiceRequest>(); try { JSONArray serviceRequestsArray; if (rawData.contains("{\"service_requests\"")) { serviceRequestsArray = new JSONObject(rawData) .getJSONArray(SERVICE_REQUESTS_TAG); } else { serviceRequestsArray = new JSONArray(rawData); } for (int i = 0; i < serviceRequestsArray.length(); i++) { JSONObject serviceRequest = serviceRequestsArray .getJSONObject(i); result.add(parseServiceRequest(serviceRequest)); } return result; } catch (Exception e) { throw new DataParsingException(e.getMessage()); } } /** * Builds a service request object from a JSONObject. * * @param serviceRequest * JSONObject representing the service definition data. * @return A service request object. * @throws MalformedURLException * If the media URL isn't correct. * @throws DataParsingException * If the received parameters are not valid. * @throws JSONException * If there was any problem parsing any parameter. */ private ServiceRequest parseServiceRequest(JSONObject serviceRequest) throws MalformedURLException, DataParsingException, JSONException { String serviceRequestId = getString(serviceRequest, SERVICE_REQUEST_ID_TAG); Status status = Status.getFromString(getString(serviceRequest, STATUS_TAG)); String statusNotes = getString(serviceRequest, STATUS_NOTES_TAG); String serviceName = getString(serviceRequest, SERVICE_NAME_TAG); String serviceCode = getString(serviceRequest, SERVICE_CODE_TAG); String description = getString(serviceRequest, DESCRIPTION_TAG); String agencyResponsible = getString(serviceRequest, AGENCY_RESPONSIBLE_TAG); String serviceNotice = getString(serviceRequest, SERVICE_NOTICE_TAG); Date requestedDatetime = dateParser.parseDate(getString(serviceRequest, REQUESTED_DATETIME_TAG)); Date updatedDatetime = dateParser.parseDate(getString(serviceRequest, UPDATED_DATETIME_TAG)); Date expectedDatetime = dateParser.parseDate(getString(serviceRequest, EXPECTED_DATETIME_TAG)); String address = getString(serviceRequest, ADDRESS_TAG); Long addressId = getLong(serviceRequest, ADDRESS_ID_TAG); Integer zipCode = getInteger(serviceRequest, ZIPCODE_TAG); Float latitude = getFloat(serviceRequest, LATITUDE_TAG); Float longitude = getFloat(serviceRequest, LONGITUDE_TAG); String rawMediaUrl = getString(serviceRequest, MEDIA_URL_TAG).trim(); URL mediaUrl = buildUrl(rawMediaUrl); checkParameters(serviceCode); return new ServiceRequest(serviceRequestId, status, statusNotes, serviceName, serviceCode, description, agencyResponsible, serviceNotice, requestedDatetime, updatedDatetime, expectedDatetime, address, addressId, zipCode, latitude, longitude, mediaUrl); } @Override public POSTServiceRequestResponse parsePostServiceRequestResponse( String rawData) throws DataParsingException { JSONArray postServiceRequestResponseArray; try { postServiceRequestResponseArray = new JSONArray(rawData); if (postServiceRequestResponseArray.length() > 0) { JSONObject postServiceRequestResponse = postServiceRequestResponseArray .getJSONObject(0); String token = getString(postServiceRequestResponse, TOKEN_TAG); String serviceRequestId = getString(postServiceRequestResponse, SERVICE_REQUEST_ID_TAG); String serviceNotice = getString(postServiceRequestResponse, SERVICE_NOTICE_TAG); String accountId = getString(postServiceRequestResponse, ACCOUNT_ID_TAG); checkParameters(serviceRequestId, token); return new POSTServiceRequestResponse(serviceRequestId, token, serviceNotice, accountId); } throw new DataParsingException( "The obtained response couldn't be parsed, it may be an error."); } catch (JSONException e) { throw new DataParsingException(e.getMessage()); } } @Override public GeoReportV2Error parseGeoReportV2Errors(String rawData) throws DataParsingException { try { JSONArray errorsArray = new JSONArray(rawData); if (errorsArray.length() > 0) { JSONObject errorObject = errorsArray.getJSONObject(0); String code = getString(errorObject, CODE_TAG); String description = getString(errorObject, DESCRIPTION_TAG); checkParameters(code, description); return new GeoReportV2Error(code, description); } else { throw new DataParsingException( "The obtained response is not an error object"); } } catch (JSONException e) { throw new DataParsingException(e.getMessage()); } } @Override public ServiceDiscoveryInfo parseServiceDiscovery(String rawData) throws DataParsingException { throw new UnsupportedOperationException( "This operation is expected to be done by an XML parser."); } /** * Searches the value of a given tag in a {@link JSONObject}. * * @param object * Object to inspect. * @param tag * Tag to search. * @return The string value of the tag, <code>null</code> if it wasn't * found. */ private String getString(JSONObject object, String tag) { String result; try { result = object.getString(tag); return result.equals(NULL_STRING_JSON) ? "" : result; } catch (JSONException e) { return ""; } } /** * Searches the value of a given tag in a {@link JSONObject}. * * @param object * Object to inspect. * @param tag * Tag to search. * @return The integer value of the tag, <code>null</code> if it wasn't * found. * @throws JSONException * If there was any problem with the parsing. */ private Integer getInteger(JSONObject object, String tag) throws JSONException { Long result = getLong(object, tag); return result != null ? result.intValue() : null; } /** * Searches the value of a given tag in a {@link JSONObject}. * * @param object * Object to inspect. * @param tag * Tag to search. * @return The long value of the tag, <code>null</code> if it wasn't found. * @throws JSONException * If there was any problem with the parsing. */ private Long getLong(JSONObject object, String tag) throws JSONException { if (object.has(tag)) { return object.getLong(tag); } return null; } /** * Searches the value of a given tag in a {@link JSONObject}. * * @param object * Object to inspect. * @param tag * Tag to search. * @return The float value of the tag, <code>null</code> if it wasn't found. * @throws JSONException * If there was any problem with the parsing. */ private Float getFloat(JSONObject object, String tag) throws JSONException { Double result = getDouble(object, tag); return result != null ? result.floatValue() : null; } /** * Searches the value of a given tag in a {@link JSONObject}. * * @param object * Object to inspect. * @param tag * Tag to search. * @return The double value of the tag, <code>null</code> if it wasn't * found. * @throws JSONException * If there was any problem with the parsing. */ private Double getDouble(JSONObject object, String tag) throws JSONException { if (object.has(tag)) { return object.getDouble(tag); } return null; } /** * Parses a boolean. * * @param object * Object to inspect. * @param tag * Tag to search. * @return <code>null</code> if it wasn't found. * @throws JSONException * If there was any problem. */ private Boolean getBoolean(JSONObject object, String tag) throws JSONException { if (object.has(tag)) { return new Boolean(object.getBoolean(tag)); } return null; } }
package com.rcv; import static java.util.Map.entry; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.nio.file.Files; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.logging.Level; import javafx.util.Pair; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; class ResultsWriter { private static final String CDF_CONTEST_ID = "contest-001"; private static final String CDF_ELECTION_ID = "election-001"; private static final String CDF_GPU_ID = "gpu-election"; private static final String CDF_GPU_ID_FORMAT = "gpu-%d"; private static final String CDF_REPORTING_DEVICE_ID = "rd-001"; private static final Map<String, String> candidateCodeToCdfId = new HashMap<>(); // number of rounds needed to elect winner(s) private int numRounds; // all precinct Ids which may appear in the output cvrs private Set<String> precinctIds; // cache precinct to GpUnitId map private Map<String, String> GpUnitIds; // threshold to win private BigDecimal winningThreshold; // map from round number to list of candidates eliminated in that round private Map<Integer, List<String>> roundToEliminatedCandidates; // map from round number to list of candidates winning in that round private Map<Integer, List<String>> roundToWinningCandidates; // configuration file in use for this contest private ContestConfig config; // timestampString string to use when generating output file names private String timestampString; // TallyTransfer object contains totals votes transferred each round private TallyTransfers tallyTransfers; private Map<Integer, BigDecimal> roundToResidualSurplus; private int numBallots; static String sequentialSuffixForOutputPath(Integer sequentialTabulationNumber) { return sequentialTabulationNumber != null ? "_" + sequentialTabulationNumber : ""; } static String getOutputFilePath( String outputDirectory, String outputType, String timestampString, Integer sequentialTabulationNumber) { String fileName = String.format( "%s_%s%s", timestampString, outputType, sequentialSuffixForOutputPath(sequentialTabulationNumber)); return Paths.get(outputDirectory, fileName).toAbsolutePath().toString(); } static String sanitizeStringForOutput(String s) { return s.replaceAll("[^a-zA-Z0-9_\\-.]", "_"); } private static void generateJsonFile(String path, Map<String, Object> json) throws IOException { // mapper converts java objects to json ObjectMapper mapper = new ObjectMapper(); // set mapper to order keys alphabetically for more legible output mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); // create a module to contain a serializer for BigDecimal serialization SimpleModule module = new SimpleModule(); module.addSerializer(BigDecimal.class, new ToStringSerializer()); // attach serializer to mapper mapper.registerModule(module); // jsonWriter writes those object to disk ObjectWriter jsonWriter = mapper.writer(new DefaultPrettyPrinter()); File outFile = new File(path); try { jsonWriter.writeValue(outFile, json); } catch (IOException exception) { Logger.log(Level.SEVERE, "Error writing to JSON file: %s\n%s", path, exception.toString()); throw exception; } } private static String generateCvrSnapshotID(String cvrID, Integer round) { return round != null && round > 0 ? String.format("ballot-%s-round-%d", cvrID, round) : String.format("ballot-%s", cvrID); } private static String getCdfIdForCandidateCode(String code) { String id = candidateCodeToCdfId.get(code); if (id == null) { id = code.startsWith("cs-") ? code : String.format("cs-%s", sanitizeStringForOutput(code).toLowerCase()); candidateCodeToCdfId.put(code, id); } return id; } // purpose: Instead of a map from rank to list of candidates, we need a sorted list of candidates // with the ranks they were given. (Ordinarily a candidate will have only a single rank, but they // could have multiple ranks if the ballot duplicates the candidate, i.e. assigns them multiple // ranks. // We sort by the lowest (best) rank, then alphabetically by name. private static List<Map.Entry<String, List<Integer>>> getCandidatesWithRanksList( Map<Integer, Set<String>> rankToCandidateIDs) { Map<String, List<Integer>> candidateIdToRanks = new HashMap<>(); // first group the ranks by candidate for (int rank : rankToCandidateIDs.keySet()) { for (String candidateId : rankToCandidateIDs.get(rank)) { candidateIdToRanks.computeIfAbsent(candidateId, k -> new LinkedList<>()); candidateIdToRanks.get(candidateId).add(rank); } } // we want the ranks for a given candidate in ascending order for (List<Integer> list : candidateIdToRanks.values()) { Collections.sort(list); } List<Map.Entry<String, List<Integer>>> sortedCandidatesWithRanks = new LinkedList<>(candidateIdToRanks.entrySet()); // and now we sort the list of candidates with ranks sortedCandidatesWithRanks.sort( (firstObject, secondObject) -> { int ret; Integer firstRank = firstObject.getValue().get(0); Integer secondRank = secondObject.getValue().get(0); if (!firstRank.equals(secondRank)) { ret = firstRank.compareTo(secondRank); } else { ret = firstObject.getKey().compareTo(secondObject.getKey()); } return ret; }); return sortedCandidatesWithRanks; } ResultsWriter setRoundToResidualSurplus(Map<Integer, BigDecimal> roundToResidualSurplus) { this.roundToResidualSurplus = roundToResidualSurplus; return this; } // function: setTallyTransfers // purpose: setter for tally transfer object used when generating json summary output // param: TallyTransfer object ResultsWriter setTallyTransfers(TallyTransfers tallyTransfers) { this.tallyTransfers = tallyTransfers; return this; } ResultsWriter setNumBallots(int numBallots) { this.numBallots = numBallots; return this; } // function: setNumRounds // purpose: setter for total number of rounds // param: numRounds total number of rounds ResultsWriter setNumRounds(int numRounds) { this.numRounds = numRounds; return this; } // function: setWinningThreshold // purpose: setter for winning threshold // param: threshold to win ResultsWriter setWinningThreshold(BigDecimal threshold) { this.winningThreshold = threshold; return this; } // function: setPrecinctIds // purpose: setter for precinctIds ResultsWriter setPrecinctIds(Set<String> precinctIds) { this.precinctIds = precinctIds; return this; } // function: setCandidatesToRoundEliminated // purpose: setter for candidatesToRoundEliminated object // param: candidatesToRoundEliminated map of candidateID to round in which they were eliminated ResultsWriter setCandidatesToRoundEliminated(Map<String, Integer> candidatesToRoundEliminated) { // roundToEliminatedCandidates is the inverse of candidatesToRoundEliminated map // so we can look up who got eliminated for each round roundToEliminatedCandidates = new HashMap<>(); // candidate is used for indexing over all candidates in candidatesToRoundEliminated for (String candidate : candidatesToRoundEliminated.keySet()) { // round is the current candidate's round of elimination int round = candidatesToRoundEliminated.get(candidate); roundToEliminatedCandidates.computeIfAbsent(round, k -> new LinkedList<>()); roundToEliminatedCandidates.get(round).add(candidate); } return this; } // function: setWinnerToRound // purpose: setter for the winning candidates // param: map from winning candidate name to the round in which they won ResultsWriter setWinnerToRound(Map<String, Integer> winnerToRound) { // very similar to the logic in setCandidatesToRoundEliminated above roundToWinningCandidates = new HashMap<>(); for (String candidate : winnerToRound.keySet()) { int round = winnerToRound.get(candidate); roundToWinningCandidates.computeIfAbsent(round, k -> new LinkedList<>()); roundToWinningCandidates.get(round).add(candidate); } return this; } // function: setContestConfig // purpose: setter for ContestConfig object // param: config the ContestConfig object to use when writing results ResultsWriter setContestConfig(ContestConfig config) { this.config = config; return this; } // function: setTimestampString // purpose: setter for timestampString string used for creating output file names // param: timestampString string to use for creating output file names ResultsWriter setTimestampString(String timestampString) { this.timestampString = timestampString; return this; } // function: generatePrecinctSummarySpreadsheet // purpose: creates a summary spreadsheet for the votes in a particular precinct // param: roundTallies is map from precinct to the round-by-round vote count in the precinct void generatePrecinctSummarySpreadsheets( Map<String, Map<Integer, Map<String, BigDecimal>>> precinctRoundTallies) throws IOException { Set<String> filenames = new HashSet<>(); for (String precinct : precinctRoundTallies.keySet()) { // precinctFileString is a unique filesystem-safe string which can be used for creating // the precinct output filename String precinctFileString = getPrecinctFileString(precinct, filenames); // filename for output String outputFileName = String.format("%s_%s_precinct_summary", this.timestampString, precinctFileString); // full path for output String outputPath = Paths.get(config.getOutputDirectory(), outputFileName).toAbsolutePath().toString(); generateSummarySpreadsheet(precinctRoundTallies.get(precinct), precinct, outputPath); // generate json output generateSummaryJson(precinctRoundTallies.get(precinct), precinct, outputPath); } } // function: generateSummarySpreadsheet // purpose: creates a summary spreadsheet .csv file // param: roundTallies is the round-by-count count of votes per candidate // param: precinct indicates which precinct we're reporting results for (null means all) // param: outputPath is the full path of the file to save // file access: write / create private void generateSummarySpreadsheet( Map<Integer, Map<String, BigDecimal>> roundTallies, String precinct, String outputPath) throws IOException { String csvPath = outputPath + ".csv"; Logger.log(Level.INFO, "Generating summary spreadsheets: %s...", csvPath); // Get all candidates sorted by their first round tally. This determines the display order. // container for firstRoundTally Map<String, BigDecimal> firstRoundTally = roundTallies.get(1); // candidates sorted by first round tally List<String> sortedCandidates = sortCandidatesByTally(firstRoundTally); // totalActiveVotesPerRound is a map of round to active votes in each round Map<Integer, BigDecimal> totalActiveVotesPerRound = new HashMap<>(); // round indexes over all rounds plus final results round for (int round = 1; round <= numRounds; round++) { // tally is map of candidate to tally for the current round Map<String, BigDecimal> tallies = roundTallies.get(round); // total will contain total votes for all candidates in this round // this is used for calculating other derived data BigDecimal total = BigDecimal.ZERO; // tally indexes over all tallies for the current round for (BigDecimal tally : tallies.values()) { total = total.add(tally); } totalActiveVotesPerRound.put(round, total); } // csvPrinter will be used to write output to csv file CSVPrinter csvPrinter; try { BufferedWriter writer = Files.newBufferedWriter(Paths.get(csvPath)); csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT); } catch (IOException exception) { Logger.log(Level.SEVERE, "Error creating CSV file: %s\n%s", csvPath, exception.toString()); throw exception; } // print contest info addHeaderRows(csvPrinter, precinct); // add a row header for the round column labels csvPrinter.print("Rounds"); // round indexes over all rounds for (int round = 1; round <= numRounds; round++) { // label string will have the actual text which goes in the cell String label = String.format("Round %d", round); // cell for round label csvPrinter.print(label); } csvPrinter.println(); // actions don't make sense in individual precinct results if (precinct == null || precinct.isEmpty()) { addActionRows(csvPrinter); } // candidate indexes over all candidates for (String candidate : sortedCandidates) { // show each candidate row with their totals for each round // text for the candidate name String candidateDisplayName = config.getNameForCandidateCode(candidate); csvPrinter.print(candidateDisplayName); // round indexes over all rounds for (int round = 1; round <= numRounds; round++) { // vote tally this round BigDecimal thisRoundTally = roundTallies.get(round).get(candidate); // not all candidates may have a tally in every round if (thisRoundTally == null) { thisRoundTally = BigDecimal.ZERO; } // total votes cell csvPrinter.print(thisRoundTally.toString()); } // advance to next line csvPrinter.println(); } // row for the inactive CVR counts // inactive CVR header cell csvPrinter.print("Inactive ballots"); // round indexes through all rounds for (int round = 1; round <= numRounds; round++) { // Exhausted/inactive count is the difference between the total ballots and the total votes // still active or counting as residual surplus votes in the current round. BigDecimal thisRoundInactive = new BigDecimal(numBallots) .subtract(totalActiveVotesPerRound.get(round)) .subtract(roundToResidualSurplus.get(round)); // total votes cell csvPrinter.print(thisRoundInactive.toString()); } csvPrinter.println(); // row for residual surplus (if needed) // We check if we accumulated any residual surplus over the course of the tabulation by testing // whether the value in the final round is positive. if (roundToResidualSurplus.get(numRounds).signum() == 1) { csvPrinter.print("Residual surplus"); for (int round = 1; round <= numRounds; round++) { csvPrinter.print(roundToResidualSurplus.get(round).toString()); } csvPrinter.println(); } // write xls to disk try { // output stream is used to write data to disk csvPrinter.flush(); csvPrinter.close(); } catch (IOException exception) { Logger.log(Level.SEVERE, "Error saving file: %s\n%s", outputPath, exception.toString()); throw exception; } } // function: addActionRows // "action" rows describe which candidates were eliminated or elected // purpose: output rows to csv file describing which actions were taken in each round // param: csvPrinter object for writing csv file private void addActionRows(CSVPrinter csvPrinter) throws IOException { // print eliminated candidates in first action row csvPrinter.print("Eliminated"); // for each round print any candidates who were eliminated for (int round = 1; round <= numRounds; round++) { // list of all candidates eliminated in this round List<String> eliminated = roundToEliminatedCandidates.get(round); if (eliminated != null && eliminated.size() > 0) { addActionRowCandidates(eliminated, csvPrinter); } else { csvPrinter.print(""); } } csvPrinter.println(); // print elected candidates in second action row csvPrinter.print("Elected"); // for each round print any candidates who were elected for (int round = 1; round <= numRounds; round++) { // list of all candidates eliminated in this round List<String> winners = roundToWinningCandidates.get(round); if (winners != null && winners.size() > 0) { addActionRowCandidates(winners, csvPrinter); } else { csvPrinter.print(""); } } csvPrinter.println(); } // function: addActionRowCandidates // purpose: add the given candidate(s) names to the csv file next cell // param: candidates list of candidate names to add to the next cell // param: csvPrinter object for output to csv file private void addActionRowCandidates(List<String> candidates, CSVPrinter csvPrinter) throws IOException { List<String> candidateDisplayNames = new ArrayList<>(); // build list of display names for (String candidate : candidates) { candidateDisplayNames.add(config.getNameForCandidateCode(candidate)); } // concatenate them using semi-colon for display in a single cell String candidateCellText = String.join("; ", candidateDisplayNames); // print the candidate name list csvPrinter.print(candidateCellText); } // function: addHeaderRows // purpose: add arbitrary header rows and cell to the top of the visualizer spreadsheet private void addHeaderRows(CSVPrinter csvPrinter, String precinct) throws IOException { csvPrinter.printRecord("Contest", config.getContestName()); csvPrinter.printRecord("Jurisdiction", config.getContestJurisdiction()); csvPrinter.printRecord("Office", config.getContestOffice()); csvPrinter.printRecord("Date", config.getContestDate()); csvPrinter.printRecord("Threshold", winningThreshold.toString()); if (precinct != null && !precinct.isEmpty()) { csvPrinter.printRecord("Precinct", precinct); } csvPrinter.println(); } // function: sortCandidatesByTally // purpose: given a map of candidates to tally return a list of all input candidates // sorted from highest tally to lowest // param: tally map of candidateID to tally // return: list of all input candidates sorted from highest tally to lowest private List<String> sortCandidatesByTally(Map<String, BigDecimal> tally) { // entries will contain all the input tally entries in sorted order List<Map.Entry<String, BigDecimal>> entries = new ArrayList<>(tally.entrySet()); // anonymous custom comparator will sort undeclared write in candidates to last place entries.sort( (firstObject, secondObject) -> { // result of the comparison int ret; if (firstObject.getKey().equals(config.getUndeclaredWriteInLabel())) { ret = 1; } else if (secondObject.getKey().equals(config.getUndeclaredWriteInLabel())) { ret = -1; } else { ret = (secondObject.getValue()).compareTo(firstObject.getValue()); } return ret; }); // container list for the final results List<String> sortedCandidates = new LinkedList<>(); // index over all entries for (Map.Entry<String, BigDecimal> entry : entries) { sortedCandidates.add(entry.getKey()); } return sortedCandidates; } // function: getPrecinctFileString // purpose: return a unique, valid string for this precinct's output spreadsheet filename // param: precinct is the name of the precinct // param: filenames is the set of filenames we've already generated // return: the new filename private String getPrecinctFileString(String precinct, Set<String> filenames) { // sanitized is the precinct name with all special characters converted to underscores String sanitized = sanitizeStringForOutput(precinct); // filename is the string that we'll eventually return String filename = sanitized; // appendNumber is used to find a unique filename (in practice this really shouldn't be // necessary because different precinct names shouldn't have the same sanitized name, but we're // doing it here to be safe) int appendNumber = 2; while (filenames.contains(filename)) { filename = sanitized + "_" + appendNumber++; } filenames.add(filename); return filename; } // function: generateOverallSummaryFiles // purpose: creates a summary spreadsheet and JSON for the full contest // param: roundTallies is the round-by-round count of votes per candidate void generateOverallSummaryFiles(Map<Integer, Map<String, BigDecimal>> roundTallies) throws IOException { String outputPath = getOutputFilePath( config.getOutputDirectory(), "summary", timestampString, config.isSequentialMultiSeatEnabled() ? config.getSequentialWinners().size() + 1 : null); // generate the spreadsheet generateSummarySpreadsheet(roundTallies, null, outputPath); // generate json output generateSummaryJson(roundTallies, null, outputPath); } // create NIST Common Data Format CVR json void generateCdfJson(List<CastVoteRecord> castVoteRecords) throws IOException, RoundSnapshotDataMissingException { // generate GpUnitIds for precincts (identify election jurisdiction and precincts) GpUnitIds = generateGpUnitIds(); HashMap<String, Object> outputJson = new HashMap<>(); String outputPath = getOutputFilePath( config.getOutputDirectory(), "cvr_cdf", timestampString, config.isSequentialMultiSeatEnabled() ? config.getSequentialWinners().size() + 1 : null) + ".json"; Logger.log(Level.INFO, "Generating CVR CDF JSON file: %s...", outputPath); outputJson.put("CVR", generateCdfMapForCvrs(castVoteRecords)); outputJson.put("Election", new Map[]{generateCdfMapForElection()}); outputJson.put( "GeneratedDate", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").format(new Date())); outputJson.put("GpUnit", generateCdfMapForGpUnits()); outputJson.put("ReportGeneratingDeviceIds", new String[]{CDF_REPORTING_DEVICE_ID}); outputJson.put( "ReportingDevice", new Map[]{ Map.ofEntries( entry("@id", CDF_REPORTING_DEVICE_ID), entry("@type", "CVR.ReportingDevice"), entry("Application", "RCV Universal Tabulator"), entry("Manufacturer", "Bright Spots")) }); outputJson.put("Version", "1.0.0"); outputJson.put("@type", "CVR.CastVoteRecordReport"); generateJsonFile(outputPath, outputJson); } // generate map of GpUnitIds // we map from precinctId => GpUnitId // as lookups will be done from precinctId during cvr creation private Map<String, String> generateGpUnitIds() { Map<String, String> GpUnitIdToPrecinctId = new HashMap<>(); int GpUnitIdIndex = 0; // for every precinctId add an entry for (String precinctId : precinctIds) { GpUnitIdToPrecinctId.put(precinctId, String.format(CDF_GPU_ID_FORMAT, ++GpUnitIdIndex)); } return GpUnitIdToPrecinctId; } // generates json containing precinct IDs private List<Map<String, Object>> generateCdfMapForGpUnits() { // create the GpUnit map List<Map<String, Object>> GpUnitMaps = new LinkedList<>(); // and add the election-scope entry for the election jurisdiction GpUnitMaps.add( Map.ofEntries( entry("@id", CDF_GPU_ID), entry("Type", "other"), entry("OtherType", "Election Scope Jurisdiction"), entry("Name", config.getContestJurisdiction()), entry("@type", "CVR.GpUnit"))); // generate GpUnit entries for (Entry<String, String> entry : GpUnitIds.entrySet()) { GpUnitMaps.add( Map.ofEntries( entry("@id", entry.getValue()), entry("Type", "precinct"), entry("Name", entry.getKey()), entry("@type", "CVR.GpUnit"))); } return GpUnitMaps; } // purpose: helper method for generateCdfJson to compile the data for all the CVR snapshots private List<Map<String, Object>> generateCdfMapForCvrs(List<CastVoteRecord> castVoteRecords) throws RoundSnapshotDataMissingException { List<Map<String, Object>> cvrMaps = new LinkedList<>(); for (CastVoteRecord cvr : castVoteRecords) { List<Map<String, Object>> cvrSnapshots = new LinkedList<>(); cvrSnapshots.add(generateCvrSnapshotMap(cvr, null, null)); // copy most recent round snapshot data to subsequent rounds // until more snapshot data is available List<Pair<String, BigDecimal>> previousRoundSnapshotData = null; for (int round = 1; round <= numRounds; round++) { List<Pair<String, BigDecimal>> currentRoundSnapshotData = cvr.getCdfSnapshotData().get(round); if (currentRoundSnapshotData == null) { if (previousRoundSnapshotData == null) { throw new RoundSnapshotDataMissingException(cvr.getID()); } currentRoundSnapshotData = previousRoundSnapshotData; } cvrSnapshots.add(generateCvrSnapshotMap(cvr, round, currentRoundSnapshotData)); previousRoundSnapshotData = currentRoundSnapshotData; } // create new cvr map entry Map<String, Object> cvrMap = new HashMap<>(); cvrMap.put("BallotPrePrintedId", cvr.getID()); cvrMap.put("CurrentSnapshotId", generateCvrSnapshotID(cvr.getID(), numRounds)); cvrMap.put("CVRSnapshot", cvrSnapshots); cvrMap.put("ElectionId", CDF_ELECTION_ID); cvrMap.put("@type", "CVR.CVR"); // if using precincts add GpUnitId for cvr precinct if (config.isTabulateByPrecinctEnabled()) { String GpUnitId = GpUnitIds.get(cvr.getPrecinct()); cvrMap.put("BallotStyleUnitId", GpUnitId); } cvrMaps.add(cvrMap); } return cvrMaps; } // purpose: helper for generateCdfMapForCvrs to handle a single CVR in a single round private Map<String, Object> generateCvrSnapshotMap( CastVoteRecord cvr, Integer round, List<Pair<String, BigDecimal>> currentRoundSnapshotData) { List<Map<String, Object>> selectionMapList = new LinkedList<>(); List<Map.Entry<String, List<Integer>>> candidatesWithRanksList = getCandidatesWithRanksList(cvr.rankToCandidateIDs); for (Map.Entry<String, List<Integer>> candidateWithRanks : candidatesWithRanksList) { String candidateCode = candidateWithRanks.getKey(); String isAllocable = "unknown"; BigDecimal numberVotes = BigDecimal.ONE; if (currentRoundSnapshotData != null) { // scanning the list isn't actually expensive because it will almost always be very short for (Pair<String, BigDecimal> allocation : currentRoundSnapshotData) { if (allocation.getKey().equals(candidateCode)) { isAllocable = "yes"; numberVotes = allocation.getValue(); break; } } // didn't find an allocation, i.e. this ballot didn't contribute all or part of a vote to // this candidate in this round if (isAllocable.equals("unknown")) { isAllocable = "no"; // not sure what numberVotes should be in this situation } } List<Map<String, Object>> selectionPositionMaps = new LinkedList<>(); for (int rank : candidateWithRanks.getValue()) { selectionPositionMaps.add( Map.ofEntries( entry("HasIndication", "yes"), entry("IsAllocable", isAllocable), entry("NumberVotes", numberVotes), entry("Rank", rank), entry("@type", "CVR.SelectionPosition"))); if (isAllocable.equals("yes")) { // If there are duplicate rankings for the candidate on this ballot, only the first one // can be allocable. isAllocable = "no"; } } selectionMapList.add( Map.ofEntries( entry("ContestSelectionId", getCdfIdForCandidateCode(candidateCode)), entry("SelectionPosition", selectionPositionMaps), entry("@type", "CVR.CVRContestSelection"))); } Map<String, Object> contestMap = Map.ofEntries( entry("ContestId", CDF_CONTEST_ID), entry("ContestSelection", selectionMapList), entry("@type", "CVR.CVRContest")); return Map.ofEntries( entry("@id", generateCvrSnapshotID(cvr.getID(), round)), entry("CVRContest", new Map[]{contestMap}), entry("Type", round != null ? "interpreted" : "original"), entry("@type", "CVR.CVRSnapshot")); } private Map<String, Object> generateCdfMapForElection() { HashMap<String, Object> electionMap = new HashMap<>(); List<Map<String, Object>> contestSelections = new LinkedList<>(); for (String candidateCode : config.getCandidateCodeList()) { Map<String, String> codeMap = Map.ofEntries( entry("@type", "CVR.Code"), entry("Type", "other"), entry("OtherType", "vendor-label"), entry("Value", config.getNameForCandidateCode(candidateCode))); contestSelections.add( Map.ofEntries( entry("@id", getCdfIdForCandidateCode(candidateCode)), entry("@type", "CVR.ContestSelection"), entry("Code", new Map[]{codeMap}))); } Map<String, Object> contestJson = Map.ofEntries( entry("@id", CDF_CONTEST_ID), entry("ContestSelection", contestSelections), entry("@type", "CVR.CandidateContest")); electionMap.put("@id", CDF_ELECTION_ID); electionMap.put("Contest", new Map[]{contestJson}); electionMap.put("ElectionScopeId", CDF_GPU_ID); electionMap.put("@type", "CVR.Election"); return electionMap; } // function: generateSummaryJson // purpose: create summary json data for use in visualizer, unit tests and other tools // param: outputPath where to write json file // param: roundTallies all tally information // file access: write to outputPath private void generateSummaryJson( Map<Integer, Map<String, BigDecimal>> roundTallies, String precinct, String outputPath) throws IOException { String jsonPath = outputPath + ".json"; Logger.log(Level.INFO, "Generating summary JSON file: %s...", jsonPath); // root outputJson dict will have two entries: // results - vote totals, transfers, and candidates elected / eliminated // config - global config into HashMap<String, Object> outputJson = new HashMap<>(); // config will contain contest configuration info HashMap<String, Object> configData = new HashMap<>(); // add config header info configData.put("contest", config.getContestName()); configData.put("jurisdiction", config.getContestJurisdiction()); configData.put("office", config.getContestOffice()); configData.put("date", config.getContestDate()); configData.put("threshold", winningThreshold); if (precinct != null && !precinct.isEmpty()) { configData.put("precinct", precinct); } // results will be a list of round data objects ArrayList<Object> results = new ArrayList<>(); // for each round create objects for json serialization for (int round = 1; round <= numRounds; round++) { // container for all json data this round: HashMap<String, Object> roundData = new HashMap<>(); // add round number (this is implied by the ordering but for debugging we are explicit) roundData.put("round", round); // add actions if this is not a precinct summary if (precinct == null || precinct.isEmpty()) { // actions is a list of one or more action objects ArrayList<Object> actions = new ArrayList<>(); addActionObjects("elected", roundToWinningCandidates.get(round), round, actions); // add any elimination actions addActionObjects("eliminated", roundToEliminatedCandidates.get(round), round, actions); // add action objects roundData.put("tallyResults", actions); } // add tally object roundData.put("tally", updateCandidateNamesInTally(roundTallies.get(round))); // add roundData to results list results.add(roundData); } // add config data to root object outputJson.put("config", configData); // add results to root object outputJson.put("results", results); // write results to disk generateJsonFile(jsonPath, outputJson); } private Map<String, BigDecimal> updateCandidateNamesInTally(Map<String, BigDecimal> tally) { Map<String, BigDecimal> newTally = new HashMap<>(); for (String key : tally.keySet()) { newTally.put(config.getNameForCandidateCode(key), tally.get(key)); } return newTally; } // function: addActionObjects // purpose: adds action objects to input action list representing all actions applied this round // each action will have a type followed by a list of 0 or more vote transfers // (sometimes there is no vote transfer if a candidate had no votes to transfer) // param: actionType is this an elimination or election action // param: candidates list of all candidates action is applied to // param: round which this action occurred // param: actions list to add new action objects to private void addActionObjects( String actionType, List<String> candidates, int round, ArrayList<Object> actions) { // check for valid candidates: // "drop undeclared write-in" may result in no one actually being eliminated if (candidates != null && candidates.size() > 0) { // transfers contains all vote transfers for this round // we add one to the round since transfers are currently stored under the round AFTER // the tallies which triggered them Map<String, Map<String, BigDecimal>> roundTransfers = tallyTransfers.getTransfersForRound(round + 1); // candidate iterates over all candidates who had this action applied to them for (String candidate : candidates) { // for each candidate create an action object HashMap<String, Object> action = new HashMap<>(); // add the specified action type action.put(actionType, config.getNameForCandidateCode(candidate)); // check if there are any transfers if (roundTransfers != null) { Map<String, BigDecimal> transfersFromCandidate = roundTransfers.get(candidate); if (transfersFromCandidate != null) { // We want to replace candidate IDs with names here, too. Map<String, BigDecimal> translatedTransfers = new HashMap<>(); for (String candidateId : transfersFromCandidate.keySet()) { // candidateName will be null for special values like "exhausted" String candidateName = config.getNameForCandidateCode(candidateId); translatedTransfers.put( candidateName != null ? candidateName : candidateId, transfersFromCandidate.get(candidateId)); } action.put("transfers", translatedTransfers); } } if (!action.containsKey("transfers")) { // add an empty map action.put("transfers", new HashMap<String, BigDecimal>()); } // add the action object to list actions.add(action); } } } // Exception class used when we're unexpectedly missing snapshot data for a cast vote record // during CDF JSON generation. If this happens, there's a bug in the tabulation code. static class RoundSnapshotDataMissingException extends Exception { private final String cvrId; RoundSnapshotDataMissingException(String cvrId) { this.cvrId = cvrId; } String getCvrId() { return cvrId; } } }
package org.csanchez.jenkins.plugins.kubernetes; import edu.umd.cs.findbugs.annotations.NonNull; import java.io.IOException; import java.util.HashSet; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.logging.Level; import java.util.logging.Logger; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.FilePath; import hudson.Util; import hudson.slaves.SlaveComputer; import io.fabric8.kubernetes.api.model.Container; import io.fabric8.kubernetes.client.utils.Serialization; import jenkins.metrics.api.Metrics; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.csanchez.jenkins.plugins.kubernetes.pod.retention.PodRetention; import org.jenkinsci.plugins.durabletask.executors.OnceRetentionStrategy; import org.jenkinsci.plugins.kubernetes.auth.KubernetesAuthException; import org.jvnet.localizer.ResourceBundleHolder; import org.kohsuke.stapler.DataBoundConstructor; import hudson.Extension; import hudson.Launcher; import hudson.console.ModelHyperlinkNote; import hudson.model.Computer; import hudson.model.Descriptor; import hudson.model.Executor; import hudson.model.Label; import hudson.model.Node; import hudson.model.Queue; import hudson.model.TaskListener; import hudson.remoting.Engine; import hudson.remoting.VirtualChannel; import hudson.slaves.AbstractCloudSlave; import hudson.slaves.Cloud; import hudson.slaves.CloudRetentionStrategy; import hudson.slaves.ComputerLauncher; import hudson.slaves.RetentionStrategy; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.KubernetesClientException; import jenkins.model.Jenkins; import jenkins.security.MasterToSlaveCallable; import static org.csanchez.jenkins.plugins.kubernetes.KubernetesCloud.JNLP_NAME; /** * @author Carlos Sanchez carlos@apache.org */ public class KubernetesSlave extends AbstractCloudSlave { private static final Logger LOGGER = Logger.getLogger(KubernetesSlave.class.getName()); private static final Integer DISCONNECTION_TIMEOUT = Integer .getInteger(KubernetesSlave.class.getName() + ".disconnectionTimeout", 5); private static final long serialVersionUID = -8642936855413034232L; private static final String DEFAULT_AGENT_PREFIX = "jenkins-agent"; /** * The resource bundle reference */ private static final ResourceBundleHolder HOLDER = ResourceBundleHolder.get(Messages.class); private final String cloudName; private String namespace; @NonNull private String podTemplateId; private transient PodTemplate template; private transient Set<Queue.Executable> executables = new HashSet<>(); @CheckForNull private transient Pod pod; @NonNull public PodTemplate getTemplate() { // Look up updated pod template after a restart PodTemplate template = getTemplateOrNull(); if (template == null) { throw new IllegalStateException("Unable to resolve pod template from id=" + podTemplateId); } return template; } @NonNull public String getTemplateId() { return podTemplateId; } @CheckForNull public PodTemplate getTemplateOrNull() { if (template == null) { template = getKubernetesCloud().getTemplateById(podTemplateId); } return template; } /** * @deprecated Use {@link Builder} instead. */ @Deprecated public KubernetesSlave(PodTemplate template, String nodeDescription, KubernetesCloud cloud, String labelStr) throws Descriptor.FormException, IOException { this(template, nodeDescription, cloud.name, labelStr, new OnceRetentionStrategy(cloud.getRetentionTimeout())); } /** * @deprecated Use {@link Builder} instead. */ @Deprecated public KubernetesSlave(PodTemplate template, String nodeDescription, KubernetesCloud cloud, Label label) throws Descriptor.FormException, IOException { this(template, nodeDescription, cloud.name, label.toString(), new OnceRetentionStrategy(cloud.getRetentionTimeout())) ; } /** * @deprecated Use {@link Builder} instead. */ @Deprecated public KubernetesSlave(PodTemplate template, String nodeDescription, KubernetesCloud cloud, String labelStr, RetentionStrategy rs) throws Descriptor.FormException, IOException { this(template, nodeDescription, cloud.name, labelStr, rs); } /** * @deprecated Use {@link Builder} instead. */ @Deprecated @DataBoundConstructor // make stapler happy. Not actually used. public KubernetesSlave(PodTemplate template, String nodeDescription, String cloudName, String labelStr, RetentionStrategy rs) throws Descriptor.FormException, IOException { this(getSlaveName(template), template, nodeDescription, cloudName, labelStr, new KubernetesLauncher(), rs); } protected KubernetesSlave(String name, @NonNull PodTemplate template, String nodeDescription, String cloudName, String labelStr, ComputerLauncher computerLauncher, RetentionStrategy rs) throws Descriptor.FormException, IOException { super(name, null, computerLauncher); setNodeDescription(nodeDescription); setNumExecutors(1); setMode(template.getNodeUsageMode() != null ? template.getNodeUsageMode() : Node.Mode.NORMAL); setLabelString(labelStr); setRetentionStrategy(rs); setNodeProperties(template.getNodeProperties()); this.cloudName = cloudName; this.template = template; this.podTemplateId = template.getId(); } public String getCloudName() { return cloudName; } public void setNamespace(@NonNull String namespace) { this.namespace = namespace; } @NonNull public String getNamespace() { return namespace; } public String getPodName() { return PodTemplateUtils.substituteEnv(getNodeName()); } private String remoteFS; @Override public String getRemoteFS() { if (remoteFS == null) { Optional<Pod> optionalPod = getPod(); if (optionalPod.isPresent()) { Optional<Container> optionalJnlp = optionalPod.get().getSpec().getContainers().stream().filter(c -> JNLP_NAME.equals(c.getName())).findFirst(); if (optionalJnlp.isPresent()) { remoteFS = StringUtils.defaultIfBlank(optionalJnlp.get().getWorkingDir(), ContainerTemplate.DEFAULT_WORKING_DIR); } } } return Util.fixNull(remoteFS); } // Copied from Slave#getRootPath because this uses the underlying field @CheckForNull @Override public FilePath getRootPath() { final SlaveComputer computer = getComputer(); if (computer == null) { // if computer is null then channel is null and thus we were going to return null anyway return null; } else { return createPath(StringUtils.defaultString(computer.getAbsoluteRemoteFs(), getRemoteFS())); } } /** * @deprecated Please use the strongly typed getKubernetesCloud() instead. */ @Deprecated public Cloud getCloud() { return Jenkins.getInstance().getCloud(getCloudName()); } public Optional<Pod> getPod() { return pod == null ? Optional.empty() : Optional.of(pod); } @NonNull public KubernetesCloud getKubernetesCloud() { return getKubernetesCloud(getCloudName()); } private static KubernetesCloud getKubernetesCloud(String cloudName) { Cloud cloud = Jenkins.get().getCloud(cloudName); if (cloud instanceof KubernetesCloud) { return (KubernetesCloud) cloud; } else { throw new IllegalStateException(KubernetesSlave.class.getName() + " can be launched only by instances of " + KubernetesCloud.class.getName() + ". Cloud is " + cloud.getClass().getName()); } } static String getSlaveName(PodTemplate template) { String randString = RandomStringUtils.random(5, "bcdfghjklmnpqrstvwxz0123456789"); String name = template.getName(); if (StringUtils.isEmpty(name)) { return String.format("%s-%s", DEFAULT_AGENT_PREFIX, randString); } // no spaces name = name.replaceAll("[ _]", "-").toLowerCase(); // keep it under 63 chars (62 is used to account for the '-') name = name.substring(0, Math.min(name.length(), 62 - randString.length())); String slaveName = String.format("%s-%s", name, randString); if (!slaveName.matches("[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*")) { return String.format("%s-%s", DEFAULT_AGENT_PREFIX, randString); } return slaveName; } @Override public KubernetesComputer createComputer() { return KubernetesComputerFactory.createInstance(this); } public PodRetention getPodRetention(KubernetesCloud cloud) { PodRetention retentionPolicy = cloud.getPodRetention(); PodTemplate template = getTemplateOrNull(); if (template != null) { PodRetention pr = template.getPodRetention(); // even though we default the pod template's retention // strategy, there are various legacy paths for injecting // pod templates where the // value can still be null, so check for it here so // as to not blow up termination path //if (pr != null) { retentionPolicy = pr; //} else { // LOGGER.fine("Template pod retention policy was null"); } return retentionPolicy; } @Override protected void _terminate(TaskListener listener) throws IOException, InterruptedException { LOGGER.log(Level.INFO, "Terminating Kubernetes instance for agent {0}", name); KubernetesCloud cloud; try { cloud = getKubernetesCloud(); } catch (IllegalStateException e) { e.printStackTrace(listener.fatalError("Unable to terminate agent. Cloud may have been removed. There may be leftover resources on the Kubernetes cluster.")); LOGGER.log(Level.SEVERE, String.format("Unable to terminate agent %s. Cloud may have been removed. There may be leftover resources on the Kubernetes cluster.", name)); return; } KubernetesClient client; try { client = cloud.connect(); } catch (KubernetesAuthException | IOException e) { String msg = String.format("Failed to connect to cloud %s. There may be leftover resources on the Kubernetes cluster.", getCloudName()); e.printStackTrace(listener.fatalError(msg)); LOGGER.log(Level.SEVERE, msg); return; } // Prior to termination, determine if we should delete the slave pod based on // the slave pod's current state and the pod retention policy. // Healthy slave pods should still have a JNLP agent running at this point. Pod pod = client.pods().inNamespace(getNamespace()).withName(name).get(); boolean deletePod = getPodRetention(cloud).shouldDeletePod(cloud, pod); Computer computer = toComputer(); if (computer == null) { String msg = String.format("Computer for agent is null: %s", name); LOGGER.log(Level.SEVERE, msg); listener.fatalError(msg); return; } // Tell the slave to stop JNLP reconnects. VirtualChannel ch = computer.getChannel(); if (ch != null) { Future<Void> disconnectorFuture = ch.callAsync(new SlaveDisconnector()); try { disconnectorFuture.get(DISCONNECTION_TIMEOUT, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { String msg = String.format("Ignoring error sending order to not reconnect agent %s: %s", name, e.getMessage()); LOGGER.log(Level.INFO, msg, e); } } if (getCloudName() == null) { String msg = String.format("Cloud name is not set for agent, can't terminate: %s", name); LOGGER.log(Level.SEVERE, msg); listener.fatalError(msg); return; } if (deletePod) { deleteSlavePod(listener, client); Metrics.metricRegistry().counter(MetricNames.PODS_TERMINATED).inc(); } else { // Log warning, as the agent pod may still be running LOGGER.log(Level.WARNING, "Agent pod {0} was not deleted due to retention policy {1}.", new Object[] { name, getPodRetention(cloud) }); } String msg = String.format("Disconnected computer %s", name); LOGGER.log(Level.INFO, msg); listener.getLogger().println(msg); } private void deleteSlavePod(TaskListener listener, KubernetesClient client) throws IOException { try { Boolean deleted = client.pods().inNamespace(getNamespace()).withName(name). cascading(true). delete(); if (!Boolean.TRUE.equals(deleted)) { String msg = String.format("Failed to delete pod for agent %s/%s: not found", getNamespace(), name); LOGGER.log(Level.WARNING, msg); listener.error(msg); return; } } catch (KubernetesClientException e) { String msg = String.format("Failed to delete pod for agent %s/%s: %s", getNamespace(), name, e.getMessage()); LOGGER.log(Level.WARNING, msg, e); listener.error(msg); return; } String msg = String.format("Terminated Kubernetes instance for agent %s/%s", getNamespace(), name); LOGGER.log(Level.INFO, msg); listener.getLogger().println(msg); } @Override public String toString() { return String.format("KubernetesSlave name: %s", name); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; KubernetesSlave that = (KubernetesSlave) o; return cloudName.equals(that.cloudName); } @Override public int hashCode() { return Objects.hash(super.hashCode(), cloudName); } @Override public Launcher createLauncher(TaskListener listener) { Launcher launcher = super.createLauncher(listener); if (template != null) { Executor executor = Executor.currentExecutor(); if (executor != null) { Queue.Executable currentExecutable = executor.getCurrentExecutable(); if (currentExecutable != null && executables.add(currentExecutable)) { listener.getLogger().println(Messages.KubernetesSlave_AgentIsProvisionedFromTemplate( ModelHyperlinkNote.encodeTo("/computer/" + getNodeName(), getNodeName()), getTemplate().getName()) ); printAgentDescription(listener); checkHomeAndWarnIfNeeded(listener); } } } return launcher; } void assignPod(@CheckForNull Pod pod) { this.pod = pod; } private void printAgentDescription(TaskListener listener) { if (pod != null && template.isShowRawYaml()) { listener.getLogger().println(podAsYaml()); } } private String podAsYaml() { String x = Serialization.asYaml(pod); Computer computer = toComputer(); if (computer instanceof SlaveComputer) { SlaveComputer sc = (SlaveComputer) computer; return x.replaceAll(sc.getJnlpMac(),"********"); } return x; } private void checkHomeAndWarnIfNeeded(TaskListener listener) { try { Computer computer = toComputer(); if (computer != null) { String home = computer.getEnvironment().get("HOME"); if ("/".equals(home)) { listener.getLogger().println(Messages.KubernetesSlave_HomeWarning()); } } } catch (IOException|InterruptedException e) { e.printStackTrace(listener.error("[WARNING] Unable to retrieve HOME environment variable")); } } protected Object readResolve() { this.executables = new HashSet<>(); return this; } /** * Returns a new {@link Builder} instance. * @return a new {@link Builder} instance. */ public static Builder builder() { return new Builder(); } /** * Builds a {@link KubernetesSlave} instance. */ public static class Builder { private String name; private String nodeDescription; private PodTemplate podTemplate; private KubernetesCloud cloud; private String label; private ComputerLauncher computerLauncher; private RetentionStrategy retentionStrategy; /** * @param name The name of the future {@link KubernetesSlave} * @return the current instance for method chaining */ public Builder name(String name) { this.name = name; return this; } /** * @param nodeDescription The node description of the future {@link KubernetesSlave} * @return the current instance for method chaining */ public Builder nodeDescription(String nodeDescription) { this.nodeDescription = nodeDescription; return this; } /** * @param podTemplate The pod template the future {@link KubernetesSlave} has been created from * @return the current instance for method chaining */ public Builder podTemplate(PodTemplate podTemplate) { this.podTemplate = podTemplate; return this; } /** * @param cloud The cloud that is provisioning the {@link KubernetesSlave} instance. * @return the current instance for method chaining */ public Builder cloud(KubernetesCloud cloud) { this.cloud = cloud; return this; } /** * @param label The label the {@link KubernetesSlave} has. * @return the current instance for method chaining */ public Builder label(String label) { this.label = label; return this; } /** * @param computerLauncher The computer launcher to use to launch the {@link KubernetesSlave} instance. * @return the current instance for method chaining */ public Builder computerLauncher(ComputerLauncher computerLauncher) { this.computerLauncher = computerLauncher; return this; } /** * @param retentionStrategy The retention strategy to use for the {@link KubernetesSlave} instance. * @return the current instance for method chaining */ public Builder retentionStrategy(RetentionStrategy retentionStrategy) { this.retentionStrategy = retentionStrategy; return this; } private RetentionStrategy determineRetentionStrategy() { if (podTemplate.getIdleMinutes() == 0) { return new OnceRetentionStrategy(cloud.getRetentionTimeout()); } else { return new CloudRetentionStrategy(podTemplate.getIdleMinutes()); } } /** * Builds the resulting {@link KubernetesSlave} instance. * @return an initialized {@link KubernetesSlave} instance. * @throws IOException * @throws Descriptor.FormException */ public KubernetesSlave build() throws IOException, Descriptor.FormException { Validate.notNull(podTemplate); Validate.notNull(cloud); return new KubernetesSlave( name == null ? getSlaveName(podTemplate) : name, podTemplate, nodeDescription == null ? podTemplate.getName() : nodeDescription, cloud.name, label == null ? podTemplate.getLabel() : label, decorateLauncher(computerLauncher == null ? new KubernetesLauncher(cloud.getJenkinsTunnel(), null) : computerLauncher), retentionStrategy == null ? determineRetentionStrategy() : retentionStrategy); } private ComputerLauncher decorateLauncher(@NonNull ComputerLauncher launcher) { if (launcher instanceof KubernetesLauncher) { ((KubernetesLauncher) launcher).setWebSocket(cloud.isWebSocket()); } return launcher; } } @Extension public static final class DescriptorImpl extends SlaveDescriptor { @Override public String getDisplayName() { return "Kubernetes Agent"; } @Override public boolean isInstantiable() { return false; } } private static class SlaveDisconnector extends MasterToSlaveCallable<Void, IOException> { private static final long serialVersionUID = 8683427258340193283L; private static final Logger LOGGER = Logger.getLogger(SlaveDisconnector.class.getName()); @Override public Void call() throws IOException { Engine e = Engine.current(); // No engine, do nothing. if (e == null) { return null; } // Tell the JNLP agent to not attempt further reconnects. e.setNoReconnect(true); LOGGER.log(Level.INFO, "Disabled agent engine reconnects."); return null; } } }
package com.sendgrid; import org.json.JSONObject; import com.sendgrid.smtpapi.SMTPAPI; import java.util.ArrayList; import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.io.FileInputStream; import java.io.File; import java.io.InputStream; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.HttpEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.util.EntityUtils; import org.apache.http.entity.ContentType; public class SendGrid { private static final String VERSION = "2.1.1"; private static final String USER_AGENT = "sendgrid/" + VERSION + ";java"; private static final String PARAM_TO = "to[%d]"; private static final String PARAM_TONAME = "toname[%d]"; private static final String PARAM_CC = "cc[%d]"; private static final String PARAM_FROM = "from"; private static final String PARAM_FROMNAME = "fromname"; private static final String PARAM_REPLYTO = "replyto"; private static final String PARAM_BCC = "bcc[%d]"; private static final String PARAM_SUBJECT = "subject"; private static final String PARAM_HTML = "html"; private static final String PARAM_TEXT = "text"; private static final String PARAM_FILES = "files[%s]"; private static final String PARAM_CONTENTS = "content[%s]"; private static final String PARAM_XSMTPAPI = "x-smtpapi"; private static final String PARAM_HEADERS = "headers"; private static final String TEXT_PLAIN = "text/plain"; private static final String UTF_8 = "UTF-8"; private String username; private String password; private String url; private String port; private String endpoint; private CloseableHttpClient client; public SendGrid(String username, String password) { this.username = username; this.password = password; this.url = "https://api.sendgrid.com"; this.endpoint = "/api/mail.send.json"; this.client = HttpClientBuilder.create().setUserAgent(USER_AGENT).build(); } public SendGrid setUrl(String url) { this.url = url; return this; } public SendGrid setEndpoint(String endpoint) { this.endpoint = endpoint; return this; } public String getVersion() { return VERSION; } public SendGrid setClient(CloseableHttpClient client) { this.client = client; return this; } public HttpEntity buildBody(Email email) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("api_user", this.username); builder.addTextBody("api_key", this.password); String[] tos = email.getTos(); String[] tonames = email.getToNames(); String[] ccs = email.getCcs(); String[] bccs = email.getBccs(); // If SMTPAPI Header is used, To is still required. #workaround. if (tos.length == 0) { builder.addTextBody(String.format(PARAM_TO, 0), email.getFrom(), ContentType.create(TEXT_PLAIN, UTF_8)); } for (int i = 0, len = tos.length; i < len; i++) builder.addTextBody(String.format(PARAM_TO, i), tos[i], ContentType.create(TEXT_PLAIN, UTF_8)); for (int i = 0, len = tonames.length; i < len; i++) builder.addTextBody(String.format(PARAM_TONAME, i), tonames[i], ContentType.create(TEXT_PLAIN, UTF_8)); for (int i = 0, len = ccs.length; i < len; i++) builder.addTextBody(String.format(PARAM_CC, i), ccs[i], ContentType.create(TEXT_PLAIN, UTF_8)); for (int i = 0, len = bccs.length; i < len; i++) builder.addTextBody(String.format(PARAM_BCC, i), bccs[i], ContentType.create(TEXT_PLAIN, UTF_8)); // Files if (email.getAttachments().size() > 0) { Iterator it = email.getAttachments().entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); builder.addBinaryBody(String.format(PARAM_FILES, entry.getKey()), (InputStream) entry.getValue()); } } if (email.getContentIds().size() > 0) { Iterator it = email.getContentIds().entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); builder.addTextBody(String.format(PARAM_CONTENTS, entry.getKey()), (String) entry.getValue()); } } if (email.getHeaders().size() > 0) builder.addTextBody(PARAM_HEADERS, new JSONObject(email.getHeaders()).toString(), ContentType.create(TEXT_PLAIN, UTF_8)); if (email.getFrom() != null && !email.getFrom().isEmpty()) builder.addTextBody(PARAM_FROM, email.getFrom(), ContentType.create(TEXT_PLAIN, UTF_8)); if (email.getFromName() != null && !email.getFromName().isEmpty()) builder.addTextBody(PARAM_FROMNAME, email.getFromName(), ContentType.create(TEXT_PLAIN, UTF_8)); if (email.getReplyTo() != null && !email.getReplyTo().isEmpty()) builder.addTextBody(PARAM_REPLYTO, email.getReplyTo(), ContentType.create(TEXT_PLAIN, UTF_8)); if (email.getSubject() != null && !email.getSubject().isEmpty()) builder.addTextBody(PARAM_SUBJECT, email.getSubject(), ContentType.create(TEXT_PLAIN, UTF_8)); if (email.getHtml() != null && !email.getHtml().isEmpty()) builder.addTextBody(PARAM_HTML, email.getHtml(), ContentType.create(TEXT_PLAIN, UTF_8)); if (email.getText() != null && !email.getText().isEmpty()) builder.addTextBody(PARAM_TEXT, email.getText(), ContentType.create(TEXT_PLAIN, UTF_8)); String tmpString = email.smtpapi.jsonString(); if (!tmpString.equals("{}")) builder.addTextBody(PARAM_XSMTPAPI, tmpString, ContentType.create(TEXT_PLAIN, UTF_8)); return builder.build(); } public SendGrid.Response send(Email email) throws SendGridException { HttpPost httppost = new HttpPost(this.url + this.endpoint); httppost.setEntity(this.buildBody(email)); try { HttpResponse res = this.client.execute(httppost); return new SendGrid.Response(res.getStatusLine().getStatusCode(), EntityUtils.toString(res.getEntity())); } catch (IOException e) { throw new SendGridException(e); } } public static class Email { private SMTPAPI smtpapi; private ArrayList<String> to; private ArrayList<String> toname; private ArrayList<String> cc; private String from; private String fromname; private String replyto; private String subject; private String text; private String html; private ArrayList<String> bcc; private Map<String, InputStream> attachments; private Map<String, String> contents; private Map<String, String> headers; public Email() { this.smtpapi = new SMTPAPI(); this.to = new ArrayList<String>(); this.toname = new ArrayList<String>(); this.cc = new ArrayList<String>(); this.bcc = new ArrayList<String>(); this.attachments = new HashMap<String, InputStream>(); this.contents = new HashMap<String, String>(); this.headers = new HashMap<String, String>(); } public Email addTo(String to) { this.to.add(to); return this; } public Email addTo(String[] tos) { this.to.addAll(Arrays.asList(tos)); return this; } public Email addTo(String to, String name) { this.addTo(to); return this.addToName(name); } public Email setTo(String[] tos) { this.to = new ArrayList<String>(Arrays.asList(tos)); return this; } public String[] getTos() { return this.to.toArray(new String[this.to.size()]); } public Email addSmtpApiTo(String to) { this.smtpapi.addTo(to); return this; } public Email addSmtpApiTo(String[] to) { this.smtpapi.addTos(to); return this; } public Email addToName(String toname) { this.toname.add(toname); return this; } public Email addToName(String[] tonames) { this.toname.addAll(Arrays.asList(tonames)); return this; } public Email setToName(String[] tonames) { this.toname = new ArrayList<String>(Arrays.asList(tonames)); return this; } public String[] getToNames() { return this.toname.toArray(new String[this.toname.size()]); } public Email addCc(String cc) { this.cc.add(cc); return this; } public Email addCc(String[] ccs) { this.cc.addAll(Arrays.asList(ccs)); return this; } public Email setCc(String[] ccs) { this.cc = new ArrayList<String>(Arrays.asList(ccs)); return this; } public String[] getCcs() { return this.cc.toArray(new String[this.cc.size()]); } public Email setFrom(String from) { this.from = from; return this; } public String getFrom() { return this.from; } public Email setFromName(String fromname) { this.fromname = fromname; return this; } public String getFromName() { return this.fromname; } public Email setReplyTo(String replyto) { this.replyto = replyto; return this; } public String getReplyTo() { return this.replyto; } public Email addBcc(String bcc) { this.bcc.add(bcc); return this; } public Email addBcc(String[] bccs) { this.bcc.addAll(Arrays.asList(bccs)); return this; } public Email setBcc(String[] bccs) { this.bcc = new ArrayList<String>(Arrays.asList(bccs)); return this; } public String[] getBccs() { return this.bcc.toArray(new String[this.bcc.size()]); } public Email setSubject(String subject) { this.subject = subject; return this; } public String getSubject() { return this.subject; } public Email setText(String text) { this.text = text; return this; } public String getText() { return this.text; } public Email setHtml(String html) { this.html = html; return this; } public String getHtml() { return this.html; } public Email addSubstitution(String key, String[] val) { this.smtpapi.addSubstitutions(key, val); return this; } public JSONObject getSubstitutions() { return this.smtpapi.getSubstitutions(); } public Email addUniqueArg(String key, String val) { this.smtpapi.addUniqueArg(key, val); return this; } public JSONObject getUniqueArgs() { return this.smtpapi.getUniqueArgs(); } public Email addCategory(String category) { this.smtpapi.addCategory(category); return this; } public String[] getCategories() { return this.smtpapi.getCategories(); } public Email addSection(String key, String val) { this.smtpapi.addSection(key, val); return this; } public JSONObject getSections() { return this.smtpapi.getSections(); } public Email addFilter(String filter_name, String parameter_name, String parameter_value) { this.smtpapi.addFilter(filter_name, parameter_name, parameter_value); return this; } public JSONObject getFilters() { return this.smtpapi.getFilters(); } public Email setASMGroupId(int val) { this.smtpapi.setASMGroupId(val); return this; } public Integer getASMGroupId() { return this.smtpapi.getASMGroupId(); } public Email setSendAt(int sendAt) { this.smtpapi.setSendAt(sendAt); return this; } public int getSendAt() { return this.smtpapi.getSendAt(); } public Email addAttachment(String name, File file) throws IOException, FileNotFoundException { return this.addAttachment(name, new FileInputStream(file)); } public Email addAttachment(String name, String file) throws IOException { return this.addAttachment(name, new ByteArrayInputStream(file.getBytes())); } public Email addAttachment(String name, InputStream file) throws IOException { this.attachments.put(name, file); return this; } public Map getAttachments() { return this.attachments; } public Email addContentId(String attachmentName, String cid) { this.contents.put(attachmentName, cid); return this; } public Map getContentIds() { return this.contents; } public Email addHeader(String key, String val) { this.headers.put(key, val); return this; } public Map getHeaders() { return this.headers; } public SMTPAPI getSMTPAPI() { return this.smtpapi; } } public static class Response { private int code; private boolean success; private String message; public Response(int code, String msg) { this.code = code; this.success = code == 200; this.message = msg; } public int getCode() { return this.code; } public boolean getStatus() { return this.success; } public String getMessage() { return this.message; } } }
package org.threadly.concurrent.future; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.threadly.concurrent.event.RunnableListenerHelper; import org.threadly.util.Clock; /** * <p>This class is designed to be a helper when returning a single result asynchronously. This * is particularly useful if this result is produced over multiple threads (and thus the scheduler * returned future is not useful).</p> * * @author jent - Mike Jensen * @since 1.2.0 * @param <T> The result object type returned by this future */ public class SettableListenableFuture<T> implements ListenableFuture<T>, FutureCallback<T> { protected final RunnableListenerHelper listenerHelper; protected final Object resultLock; private volatile Thread runningThread; private volatile boolean done; private volatile boolean canceled; private boolean resultCleared; private T result; private Throwable failure; /** * Constructs a new {@link SettableListenableFuture}. You can return this immediately and * provide a result to the object later when it is ready. */ public SettableListenableFuture() { this.listenerHelper = new RunnableListenerHelper(true); resultLock = new Object(); done = false; resultCleared = false; result = null; failure = null; } @Override public void addListener(Runnable listener) { listenerHelper.addListener(listener); } @Override public void addListener(Runnable listener, Executor executor) { listenerHelper.addListener(listener, executor); } @Override public void addCallback(FutureCallback<? super T> callback) { addCallback(callback, null); } @Override public void addCallback(FutureCallback<? super T> callback, Executor executor) { addListener(new RunnableFutureCallbackAdapter<T>(this, callback), executor); } /** * This call defers to {@link #setResult(Object)}. It is implemented so that you can construct * this, return it immediately, but only later provide this as a callback to another * {@link ListenableFuture} implementation. * * This should never be invoked by the implementor, this should only be invoked by other * {@link ListenableFuture}'s. * * If this is being used to chain together {@link ListenableFuture}'s, * {@link #setResult(Object)}/{@link #setFailure(Throwable)} should never be called manually (or * an exception will occur). * * @param result Result object to provide to the future to be returned from {@link #get()} call */ @Override public void handleResult(T result) { setResult(result); } /** * This call defers to {@link #setFailure(Throwable)}. It is implemented so that you can * construct this, return it immediately, but only later provide this as a callback to another * {@link ListenableFuture} implementation. * * This should never be invoked by the implementor, this should only be invoked by other * {@link ListenableFuture}'s. * * If this is being used to chain together {@link ListenableFuture}'s, * {@link #setResult(Object)}/{@link #setFailure(Throwable)} should never be called manually (or * an exception will occur). * * @param t Throwable to be provided as the cause from the ExecutionException thrown from {@link #get()} call */ @Override public void handleFailure(Throwable t) { setFailure(t); } /** * Call to indicate this future is done, and provide the given result. It is expected that only * this or {@link #setFailure(Throwable)} are called, and only called once. * * @param result result to provide for {@link #get()} call, can be {@code null} */ public void setResult(T result) { synchronized (resultLock) { this.result = result; setDone(); resultLock.notifyAll(); } // call outside of lock listenerHelper.callListeners(); } /** * Call to indicate this future is done, and provide the occurred failure. It is expected that * only this or {@link #setResult(Object)} are called, and only called once. If the provided * failure is {@code null}, a new {@link Exception} will be created so that something is always * provided in the {@link ExecutionException} on calls to {@link #get()}. * * @param failure Throwable that caused failure during computation. */ public void setFailure(Throwable failure) { if (failure == null) { failure = new Exception(); } synchronized (resultLock) { this.failure = failure; setDone(); resultLock.notifyAll(); } // call outside of lock listenerHelper.callListeners(); } /** * Optional call to set the thread internally that will be generating the result for this * future. Setting this thread allows it so that if a {@link #cancel(boolean)} call is invoked * with {@code true}, we can send an interrupt to this thread. * * The reference to this thread will be cleared after this future has completed (thus allowing * it to be garbage collected). * * @param thread Thread that is generating the result for this future */ public void setRunningThread(Thread thread) { if (! done) { this.runningThread = thread; } } @Override public boolean cancel(boolean interruptThread) { if (done) { return false; } boolean canceled; synchronized (resultLock) { if (! done) { this.canceled = true; if (interruptThread) { Thread runningThread = this.runningThread; if (runningThread != null) { runningThread.interrupt(); } } setDone(); canceled = true; } else { canceled = false; } } if (canceled) { // call outside of lock listenerHelper.callListeners(); } return canceled; } @Override public boolean isCancelled() { return canceled; } public void clearResult() { synchronized (resultLock) { if (! done) { throw new IllegalStateException("Result not set yet"); } resultCleared = true; result = null; failure = null; } } // should be synchronized on resultLock before calling private void setDone() { if (done) { throw new IllegalStateException("Already done"); } done = true; runningThread = null; } @Override public boolean isDone() { return done; } @Override public T get() throws InterruptedException, ExecutionException { synchronized (resultLock) { while (! done) { resultLock.wait(); } if (resultCleared) { throw new IllegalStateException("Result cleared, future get's not possible"); } if (failure != null) { throw new ExecutionException(failure); } else if (canceled) { throw new CancellationException(); } else { return result; } } } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { long startTime = Clock.accurateForwardProgressingMillis(); long timeoutInMs = unit.toMillis(timeout); synchronized (resultLock) { long remainingInMs; while (! done && (remainingInMs = timeoutInMs - (Clock.accurateForwardProgressingMillis() - startTime)) > 0) { resultLock.wait(remainingInMs); } if (resultCleared) { throw new IllegalStateException("Result cleared, future get's not possible"); } if (failure != null) { throw new ExecutionException(failure); } else if (canceled) { throw new CancellationException(); } else if (done) { return result; } else { throw new TimeoutException(); } } } }
package com.sendgrid; import org.json.JSONObject; import com.mashape.unirest.http.*; import com.mashape.unirest.http.exceptions.*; import com.sendgrid.smtpapi.SMTPAPI; import com.mashape.unirest.http.JsonNode; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Scanner; import java.util.Map; import java.io.File; import java.io.InputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; public class SendGrid { private String username; private String password; private String url; private String port; private String endpoint; public SendGrid(String username, String password) { this.username = username; this.password = password; this.url = "https://api.sendgrid.com"; this.endpoint = "/api/mail.send.json"; } public SendGrid setUrl(String url) { this.url = url; return this; } public SendGrid setEndpoint(String endpoint) { this.endpoint = endpoint; return this; } public SendGrid.Response send(Email email) throws SendGridException { try { HttpResponse<JsonNode> res = Unirest.post(this.url + this.endpoint) .fields(email.toWebFormat()).field("api_user", this.username).field("api_key", this.password).asJson(); return new SendGrid.Response(res.getCode(), res.getBody()); } catch (UnirestException e) { throw new SendGridException(e); } } public static class Email { private static final String PARAM_TO = "to"; private static final String PARAM_FROM = "from"; private static final String PARAM_FROMNAME = "fromname"; private static final String PARAM_REPLYTO = "replyto"; private static final String PARAM_BCCS = "bcc[%d]"; private static final String PARAM_SUBJECT = "subject"; private static final String PARAM_HTML = "html"; private static final String PARAM_TEXT = "text"; private static final String PARAM_FILES = "files[%s]"; private static final String PARAM_XSMTPAPI = "x-smtpapi"; private static final String PARAM_HEADERS = "headers"; public SMTPAPI smtpapi; SMTPAPI header = new SMTPAPI(); public String to; public String from; public String fromname; public String replyto; public String subject; public String text; public String html; public ArrayList<String> bcc = new ArrayList<String>(); public Map attachments = new HashMap(); public Map headers = new HashMap(); public Email () { this.smtpapi = new SMTPAPI(); } public Email addTo(String to) { this.smtpapi.addTo(to); return this; } public Email setFrom(String from) { this.from = from; return this; } public Email setFromName(String fromname) { this.fromname = fromname; return this; } public Email setReplyTo(String replyto) { this.replyto = replyto; return this; } public Email addBcc(String bcc) { this.bcc.add(bcc); return this; } public Email setSubject(String subject) { this.subject = subject; return this; } public Email setText(String text) { this.text = text; return this; } public Email setHtml(String html) { this.html = html; return this; } public Email addSubstitution(String key, String[] val) { this.smtpapi.addSubstitutions(key, val); return this; } public Email addUniqueArg(String key, String val) { this.smtpapi.addUniqueArg(key, val); return this; } public Email addCategory(String category) { this.smtpapi.addCategory(category); return this; } public Email addSection(String key, String val) { this.smtpapi.addSection(key, val); return this; } public Email addFilter(String filter_name, String parameter_name, String parameter_value) { this.smtpapi.addFilter(filter_name, parameter_name, parameter_value); return this; } public Email addAttachment(String name, File file) { this.attachments.put(name, file); return this; } public Email addAttachment(String name, String file) { this.attachments.put(name, file); return this; } public Email addAttachment(String name, InputStream file) { Scanner scanner = new Scanner(file, "UTF-8"); String buffer = new String(); while (scanner.hasNextLine()) { buffer += scanner.nextLine(); } scanner.close(); return this.addAttachment(name, buffer); } public Email addHeader(String key, String val) { this.headers.put(key, val); return this; } public Map toWebFormat() { Map body = new HashMap(); // updateMissingTo - There needs to be at least 1 to address, // or else the mail won't send. if ((this.to == null || this.to.isEmpty()) && this.from != null && !this.from.isEmpty()) { String value = this.from; body.put(PARAM_TO, value); } if (this.from != null && !this.from.isEmpty()) { String value = this.from; body.put(PARAM_FROM, value); } if (this.fromname != null && !this.fromname.isEmpty()) { String value = this.fromname; body.put(PARAM_FROMNAME, value); } if (this.replyto != null && !this.replyto.isEmpty()) { String value = this.replyto; body.put(PARAM_REPLYTO, value); } for (int i = 0; i < this.bcc.size(); i++) { String key = String.format(PARAM_BCCS, i); String value = this.bcc.get(i); body.put(key, value); } if (this.subject != null && !this.subject.isEmpty()) { String value = this.subject; body.put(PARAM_SUBJECT, value); } if (this.text != null && !this.text.isEmpty()) { String value = this.text; body.put(PARAM_TEXT, value); } if (this.html != null && !this.html.isEmpty()) { String value = this.html; body.put(PARAM_HTML, value); } if (!this.headers.isEmpty()) { JSONObject json_headers = new JSONObject(this.headers); String serialized_headers = json_headers.toString(); body.put(PARAM_HEADERS, serialized_headers); } if (!this.smtpapi.jsonString().equals("{}")) { String value = this.smtpapi.jsonString(); body.put(PARAM_XSMTPAPI, value); } if (this.attachments.size() > 0) { Iterator it = this.attachments.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); body.put(String.format(PARAM_FILES, entry.getKey()), entry.getValue()); } } return body; } } public static class Response { private int code; private boolean success; private String message; public Response(int code, JsonNode body) { this.code = code; this.success = code == 200; this.message = body.toString(); } public int getCode() { return this.code; } public boolean getStatus() { return this.success; } public String getMessage() { return this.message; } } }
package input; import com.univocity.parsers.common.ParsingContext; import com.univocity.parsers.common.processor.ObjectRowProcessor; import com.univocity.parsers.tsv.TsvParser; import com.univocity.parsers.tsv.TsvParserSettings; import com.univocity.parsers.tsv.TsvWriter; import org.apache.log4j.Logger; import output.OutputHandler; import scala.Tuple2; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.Reader; /** * @author adrian */ public class InputHandlerTSV extends InputHandler { /** * Define a static logger variable so that it references the * Logger instance named "InputHandler". */ private static final Logger logger = Logger.getLogger(InputHandlerTSV.class); /** * The reader the parse()-method should read from. */ private Reader reader; /** * The file for writing the pre-processed data. */ private TsvWriter preprocessedWriter; /** * @param fileToRead The file the parse()-method should read from. * @throws FileNotFoundException If the file does not exist, * is a directory rather than a regular file, * or for some other reason cannot be opened for reading. */ public void setInputFile(String fileToRead) throws FileNotFoundException { this.inputFile = fileToRead; this.reader = new InputStreamReader(new FileInputStream(fileToRead)); } /** * Read the file given by reader and hands the data to the outputHandler. * * @param outputHandler Handles the data that should be written. */ public final void parseTo(final OutputHandler outputHandler) { //read in queries from .tsv TsvParserSettings parserSettings = new TsvParserSettings(); parserSettings.setLineSeparatorDetectionEnabled(true); parserSettings.setHeaderExtractionEnabled(true); parserSettings.setSkipEmptyLines(true); parserSettings.setReadInputOnSeparateThread(true); ObjectRowProcessor rowProcessor = new ObjectRowProcessor() { @Override public void rowProcessed(Object[] row, ParsingContext parsingContext) { if (row.length <= 1) { logger.warn("Ignoring line without tab while parsing."); return; } Tuple2<String, Integer> queryTuple = decode(row[0].toString(), inputFile, parsingContext.currentLine()); String query = queryTuple._1; Integer validity = queryTuple._2; String user_agent = row[2].toString(); Long current_line = parsingContext.currentLine(); outputHandler.writeLine(query, validity, user_agent, current_line, inputFile); } }; parserSettings.setProcessor(rowProcessor); TsvParser parser = new TsvParser(parserSettings); parser.parse(reader); outputHandler.closeFiles(); if (preprocessedWriter != null) { preprocessedWriter.close(); } } }
package io.teiler.server; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; /** * As of now, the only purpose of this class is to fire up the whole application. * * @author pbaechli */ @SpringBootApplication @ComponentScan("io.teiler") public class Tylr { public static void main(String[] args) { SpringApplication.run(Tylr.class, args); } public void test() { throw new java.lang.Exception(); } }